use {Args, to_hex};
use config::{Configure, GitBoxConfigResult};
use filter::{Clean, Filter, GitBoxFilterResult, Smudge};
use git2::Config;
use rusqlite::{self, Connection, DatabaseName};
use rusqlite::types::ToSql;
use sodium_sys::crypto::hash::generichash;
use std::io::Read;
#[derive(Default)]
pub struct SqliteBox {
path: String,
table: String,
}
impl From<Config> for SqliteBox {
fn from(config: Config) -> SqliteBox {
SqliteBox {
path: match config.get_string("box.sqlite.path") {
Ok(u) => u.to_owned(),
Err(_) => String::new(),
},
table: match config.get_string("box.sqlite.table") {
Ok(t) => t.to_owned(),
Err(_) => String::new(),
},
}
}
}
impl From<Args> for SqliteBox {
fn from(args: Args) -> SqliteBox {
SqliteBox {
path: args.arg_path,
table: args.arg_table,
}
}
}
impl Configure for SqliteBox {
fn set_config(&self, config: &mut Config) -> GitBoxConfigResult {
try!(config.set_str("box.storagetype", "SQLITE"));
try!(config.set_str("box.sqlite.path", &self.path[..]));
try!(config.set_str("box.sqlite.table", &self.table[..]));
if ::enabled() {
debug!("Set git-box SQLITE config:");
debug!(" box.storagetype: {}", "SQLITE");
debug!(" box.sqlite.path: {}", self.path);
debug!(" box.sqlite.table: {}", self.table);
}
Ok(0)
}
fn remove_config(&self, config: &mut Config) -> GitBoxConfigResult {
try!(config.remove("box.storagetype"));
try!(config.remove("box.sqlite.path"));
try!(config.remove("box.sqlite.table"));
if ::enabled() {
debug!("Unset git-box SQLITE config");
}
Ok(0)
}
}
impl Clean for SqliteBox {
fn clean(&self, buf: &mut Vec<u8>, hash: &str, size: usize) -> GitBoxFilterResult {
let chkhash = to_hex(try!(generichash::hash(&buf[..], None, None)));
assert!(chkhash == hash);
assert!(buf.len() == size);
let create_sql = format!("CREATE TABLE IF NOT EXISTS {} (id CHARACTER(65) PRIMARY KEY, \
box BLOB NOT NULL)",
&self.table);
let insert_sql = format!("INSERT OR IGNORE INTO {} VALUES (:id, :box)", &self.table);
let conn = try!(Connection::open(&self.path));
try!(conn.execute_named(&create_sql[..], &[]));
let params: &[(&str, &ToSql)] = &[(":id", &hash), (":box", &&buf[..])];
try!(conn.execute_named(&insert_sql[..], params));
Ok(size)
}
}
impl Smudge for SqliteBox {
fn smudge(&self, buf: &mut Vec<u8>, hash: &str, size: usize) -> GitBoxFilterResult {
let select_sql = format!("SELECT rowid FROM {} WHERE id = :id", &self.table);
let conn = try!(Connection::open(&self.path));
let params: &[(&str, &ToSql)] = &[(":id", &hash)];
let res: Result<i64, rusqlite::Error> = try!(conn.query_row_named(&select_sql[..],
params,
|row| {
row.get_checked(0)
}));
if let Ok(rowid) = res {
let mut blob = try!(conn.blob_open(DatabaseName::Main,
&self.table,
"box",
rowid,
true));
let actual_size = try!(blob.read_to_end(buf));
assert!(size == actual_size);
}
let chkhash = to_hex(try!(generichash::hash(&buf[..], None, None)));
assert!(chkhash == hash);
assert!(buf.len() == size);
Ok(size)
}
}
impl Filter for SqliteBox {}