From 38c67e3c27c789f0fc2afce3c7d3dfd514e1f585 Mon Sep 17 00:00:00 2001 From: Tom Alexander Date: Sun, 2 Jun 2019 22:21:53 -0400 Subject: [PATCH] writing and reading notes --- src/db.rs | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/src/db.rs b/src/db.rs index a854a61..b6a5a10 100644 --- a/src/db.rs +++ b/src/db.rs @@ -31,8 +31,16 @@ pub struct DbNamespace { pub name: EncryptedValue, } -#[derive(Debug)] pub struct DbNote { + pub id: i64, + pub namespace: DbNamespace, + pub category: String, + pub title: EncryptedValue, + pub value: EncryptedValue, +} + +#[derive(Debug)] +pub struct Note { pub id: i64, pub namespace: String, pub category: String, @@ -91,6 +99,54 @@ impl DbHandle { Ok(rowid) } + pub fn write_note(&mut self, master_key: [u8; 32], note: Note) { + let namespace_id = self.get_namespace_id(¬e.namespace, master_key).unwrap(); + let encrypted_title = crypt::encrypt_value(¬e.title, master_key); + let encrypted_value = crypt::encrypt_value(¬e.value, master_key); + self.conn + .execute( + "INSERT INTO notes (namespace, category, title, value) VALUES ($1, $2, $3, $4);", + params![ + namespace_id, + note.category, + encrypted_title, + encrypted_value + ], + ) + .unwrap(); + } + + pub fn read_notes(&mut self, master_key: [u8; 32]) -> rusqlite::Result> { + let mut stmt = self.conn.prepare("SELECT notes.id, notes.category, notes.title, notes.value, namespaces.id, namespaces.name FROM notes JOIN namespaces ON notes.namespace=namespaces.id").unwrap(); + let rows = stmt.query_map(params![], |row| { + Ok(DbNote { + id: row.get(0)?, + category: row.get(1)?, + title: row.get(2)?, + value: row.get(3)?, + namespace: DbNamespace { + id: row.get(4)?, + name: row.get(5)?, + }, + }) + })?; + + let notes: Result, _> = rows + .map(|note_result| match note_result { + Ok(note) => Ok(Note { + id: note.id, + namespace: note.namespace.name.decrypt_to_string(master_key).unwrap(), + category: note.category, + title: note.title.decrypt_to_string(master_key).unwrap(), + value: note.value.decrypt_to_string(master_key).unwrap(), + }), + Err(e) => return Err(e), + }) + .collect(); + + notes + } + pub fn get_db_property(&self, name: &str) -> Result, Box> { let mut stmt = self .conn