wallet_api.rs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. use crate::serial::{deserialize, serialize, Decodable, Encodable};
  2. use crate::Result;
  3. use rusqlite::Connection;
  4. use std::path::PathBuf;
  5. pub trait WalletApi {
  6. fn get_password(&self) -> String;
  7. fn get_path(&self) -> PathBuf;
  8. fn get_value_serialized<T: Encodable>(&self, data: &T) -> Result<Vec<u8>> {
  9. let v = serialize(data);
  10. Ok(v)
  11. }
  12. fn get_value_deserialized<D: Decodable>(&self, key: Vec<u8>) -> Result<D> {
  13. let v: D = deserialize(&key)?;
  14. Ok(v)
  15. }
  16. fn get_tables_name(&self) -> Result<Vec<String>> {
  17. let conn = Connection::open(&self.get_path())?;
  18. conn.pragma_update(None, "key", &self.get_password())?;
  19. let mut stmt = conn.prepare("SELECT name FROM sqlite_master WHERE type='table'")?;
  20. let table_iter = stmt.query_map::<String, _, _>([], |row| row.get(0))?;
  21. let mut tables = Vec::new();
  22. for table in table_iter {
  23. tables.push(table?);
  24. }
  25. Ok(tables)
  26. }
  27. fn destroy(&self) -> Result<()> {
  28. let conn = Connection::open(&self.get_path())?;
  29. conn.pragma_update(None, "key", &self.get_password())?;
  30. for table in self.get_tables_name()?.iter() {
  31. let drop_stmt = format!("DROP TABLE IF EXISTS {}", table);
  32. let drop_stmt = drop_stmt.as_str();
  33. conn.execute(drop_stmt, [])?;
  34. }
  35. Ok(())
  36. }
  37. }