|
| 1 | +use super::*; |
| 2 | + |
| 3 | +use lightning::util::persist::KVStorePersister; |
| 4 | +use lightning::util::ser::Writeable; |
| 5 | + |
| 6 | +use rusqlite::{named_params, Connection}; |
| 7 | + |
| 8 | +use std::fs; |
| 9 | +use std::io::Cursor; |
| 10 | +use std::path::PathBuf; |
| 11 | +use std::str::FromStr; |
| 12 | +use std::sync::{Arc, Mutex}; |
| 13 | + |
| 14 | +// The database file name. |
| 15 | +const SQLITE_DB_FILE: &str = "ldk_node.sqlite"; |
| 16 | + |
| 17 | +// The table in which we store all data. |
| 18 | +const KV_TABLE_NAME: &str = "ldk_node_data"; |
| 19 | + |
| 20 | +// The current SQLite `user_version`, which we can use if we'd ever need to do a schema migration. |
| 21 | +const SCHEMA_USER_VERSION: u16 = 1; |
| 22 | + |
| 23 | +/// A [`KVStore`] implementation that writes to and reads from an [SQLite] database. |
| 24 | +/// |
| 25 | +/// [SQLIte]: https://sqlite.org |
| 26 | +pub struct SqliteStore { |
| 27 | + connection: Arc<Mutex<Connection>>, |
| 28 | +} |
| 29 | + |
| 30 | +impl SqliteStore { |
| 31 | + pub(crate) fn new(dest_dir: PathBuf) -> Self { |
| 32 | + let msg = |
| 33 | + format!("Failed to create database destination directory: {}", dest_dir.display()); |
| 34 | + fs::create_dir_all(dest_dir.clone()).expect(&msg); |
| 35 | + let mut db_file_path = dest_dir.clone(); |
| 36 | + db_file_path.push(SQLITE_DB_FILE); |
| 37 | + |
| 38 | + let msg = format!("Failed to open/create database file: {}", db_file_path.display()); |
| 39 | + let connection = Connection::open(db_file_path).expect(&msg); |
| 40 | + |
| 41 | + let msg = format!("Failed to set PRAGMA user_version"); |
| 42 | + connection |
| 43 | + .pragma(Some(rusqlite::DatabaseName::Main), "user_version", SCHEMA_USER_VERSION, |_| { |
| 44 | + Ok(()) |
| 45 | + }) |
| 46 | + .expect(&msg); |
| 47 | + |
| 48 | + let sql = format!( |
| 49 | + "CREATE TABLE IF NOT EXISTS {} ( |
| 50 | + namespace TEXT NOT NULL, |
| 51 | + key TEXT NOT NULL, |
| 52 | + value BLOB, PRIMARY KEY ( namespace, key ) |
| 53 | + );", |
| 54 | + KV_TABLE_NAME |
| 55 | + ); |
| 56 | + let msg = format!("Failed to create table: {}", KV_TABLE_NAME); |
| 57 | + connection.execute(&sql, []).expect(&msg); |
| 58 | + |
| 59 | + let connection = Arc::new(Mutex::new(connection)); |
| 60 | + Self { connection } |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +impl KVStore for SqliteStore { |
| 65 | + type Reader = Cursor<Vec<u8>>; |
| 66 | + |
| 67 | + fn read(&self, namespace: &str, key: &str) -> std::io::Result<Self::Reader> { |
| 68 | + let sql = |
| 69 | + format!("SELECT value FROM {} WHERE namespace=:namespace AND key=:key;", KV_TABLE_NAME); |
| 70 | + |
| 71 | + let msg = format!("Failed to read from key: {}/{}", namespace, key); |
| 72 | + let res = self |
| 73 | + .connection |
| 74 | + .lock() |
| 75 | + .unwrap() |
| 76 | + .query_row( |
| 77 | + &sql, |
| 78 | + named_params! { |
| 79 | + ":namespace": namespace, |
| 80 | + ":key": key, |
| 81 | + }, |
| 82 | + |row| row.get(0), |
| 83 | + ) |
| 84 | + .map_err(|_| std::io::Error::new(std::io::ErrorKind::NotFound, msg))?; |
| 85 | + Ok(Cursor::new(res)) |
| 86 | + } |
| 87 | + |
| 88 | + fn write(&self, namespace: &str, key: &str, buf: &[u8]) -> std::io::Result<()> { |
| 89 | + let mut locked_conn = self.connection.lock().unwrap(); |
| 90 | + |
| 91 | + let msg = format!("Failed to start transaction"); |
| 92 | + let sql_tx = locked_conn |
| 93 | + .transaction() |
| 94 | + .map_err(|_| std::io::Error::new(std::io::ErrorKind::Other, msg))?; |
| 95 | + |
| 96 | + let sql = format!( |
| 97 | + "INSERT OR REPLACE INTO {} (namespace, key, value) VALUES (:namespace, :key, :data);", |
| 98 | + KV_TABLE_NAME |
| 99 | + ); |
| 100 | + let msg = format!("Failed to write to key: {}/{}", namespace, key); |
| 101 | + sql_tx |
| 102 | + .execute( |
| 103 | + &sql, |
| 104 | + named_params! { |
| 105 | + ":namespace": namespace, |
| 106 | + ":key": key, |
| 107 | + ":data": buf, |
| 108 | + }, |
| 109 | + ) |
| 110 | + .map_err(|_| std::io::Error::new(std::io::ErrorKind::Other, msg))?; |
| 111 | + |
| 112 | + let msg = format!("Failed to commit transaction"); |
| 113 | + sql_tx.commit().map_err(|_| std::io::Error::new(std::io::ErrorKind::Other, msg))?; |
| 114 | + |
| 115 | + Ok(()) |
| 116 | + } |
| 117 | + |
| 118 | + fn remove(&self, namespace: &str, key: &str) -> std::io::Result<bool> { |
| 119 | + let sql = format!("DELETE FROM {} WHERE namespace=:namespace AND key=:key;", KV_TABLE_NAME); |
| 120 | + let msg = format!("Failed to delete key: {}/{}", namespace, key); |
| 121 | + let changes = self |
| 122 | + .connection |
| 123 | + .lock() |
| 124 | + .unwrap() |
| 125 | + .execute( |
| 126 | + &sql, |
| 127 | + named_params! { |
| 128 | + ":namespace": namespace, |
| 129 | + ":key": key, |
| 130 | + }, |
| 131 | + ) |
| 132 | + .map_err(|_| std::io::Error::new(std::io::ErrorKind::Other, msg))?; |
| 133 | + |
| 134 | + let was_present = changes != 0; |
| 135 | + |
| 136 | + Ok(was_present) |
| 137 | + } |
| 138 | + |
| 139 | + fn list(&self, namespace: &str) -> std::io::Result<Vec<String>> { |
| 140 | + let locked_conn = self.connection.lock().unwrap(); |
| 141 | + |
| 142 | + let sql = format!("SELECT key FROM {} WHERE namespace=:namespace", KV_TABLE_NAME); |
| 143 | + let msg = format!("Failed to prepare statement"); |
| 144 | + let mut stmt = locked_conn |
| 145 | + .prepare(&sql) |
| 146 | + .map_err(|_| std::io::Error::new(std::io::ErrorKind::Other, msg))?; |
| 147 | + |
| 148 | + let mut keys = Vec::new(); |
| 149 | + |
| 150 | + let msg = format!("Failed to retrieve queried rows"); |
| 151 | + let rows_iter = stmt |
| 152 | + .query_map(named_params! {":namespace": namespace, }, |row| row.get(0)) |
| 153 | + .map_err(|_| std::io::Error::new(std::io::ErrorKind::Other, msg))?; |
| 154 | + |
| 155 | + for k in rows_iter { |
| 156 | + let msg = format!("Failed to retrieve queried rows"); |
| 157 | + keys.push(k.map_err(|_| std::io::Error::new(std::io::ErrorKind::Other, msg))?); |
| 158 | + } |
| 159 | + |
| 160 | + Ok(keys) |
| 161 | + } |
| 162 | +} |
| 163 | + |
| 164 | +impl KVStorePersister for SqliteStore { |
| 165 | + fn persist<W: Writeable>(&self, prefixed_key: &str, object: &W) -> lightning::io::Result<()> { |
| 166 | + let msg = format!("Could not persist file for key {}.", prefixed_key); |
| 167 | + let dest_file_path = PathBuf::from_str(prefixed_key).map_err(|_| { |
| 168 | + lightning::io::Error::new(lightning::io::ErrorKind::InvalidInput, msg.clone()) |
| 169 | + })?; |
| 170 | + |
| 171 | + let parent_directory = dest_file_path.parent().ok_or(lightning::io::Error::new( |
| 172 | + lightning::io::ErrorKind::InvalidInput, |
| 173 | + msg.clone(), |
| 174 | + ))?; |
| 175 | + let namespace = parent_directory.display().to_string(); |
| 176 | + |
| 177 | + let dest_without_namespace = dest_file_path |
| 178 | + .strip_prefix(&namespace) |
| 179 | + .map_err(|_| lightning::io::Error::new(lightning::io::ErrorKind::InvalidInput, msg))?; |
| 180 | + let key = dest_without_namespace.display().to_string(); |
| 181 | + |
| 182 | + self.write(&namespace, &key, &object.encode())?; |
| 183 | + Ok(()) |
| 184 | + } |
| 185 | +} |
| 186 | + |
| 187 | +#[cfg(test)] |
| 188 | +mod tests { |
| 189 | + use super::*; |
| 190 | + use crate::test::utils::random_storage_path; |
| 191 | + use lightning::util::persist::KVStorePersister; |
| 192 | + use lightning::util::ser::Readable; |
| 193 | + |
| 194 | + use proptest::prelude::*; |
| 195 | + proptest! { |
| 196 | + #[test] |
| 197 | + fn read_write_remove_list_persist(data in any::<[u8; 32]>()) { |
| 198 | + let rand_dir = random_storage_path(); |
| 199 | + |
| 200 | + let sqlite_store = SqliteStore::new(rand_dir.into()); |
| 201 | + let namespace = "testspace"; |
| 202 | + let key = "testkey"; |
| 203 | + |
| 204 | + // Test the basic KVStore operations. |
| 205 | + sqlite_store.write(namespace, key, &data).unwrap(); |
| 206 | + |
| 207 | + let listed_keys = sqlite_store.list(namespace).unwrap(); |
| 208 | + assert_eq!(listed_keys.len(), 1); |
| 209 | + assert_eq!(listed_keys[0], "testkey"); |
| 210 | + |
| 211 | + let mut reader = sqlite_store.read(namespace, key).unwrap(); |
| 212 | + let read_data: [u8; 32] = Readable::read(&mut reader).unwrap(); |
| 213 | + assert_eq!(data, read_data); |
| 214 | + |
| 215 | + sqlite_store.remove(namespace, key).unwrap(); |
| 216 | + |
| 217 | + let listed_keys = sqlite_store.list(namespace).unwrap(); |
| 218 | + assert_eq!(listed_keys.len(), 0); |
| 219 | + |
| 220 | + // Test KVStorePersister |
| 221 | + let prefixed_key = format!("{}/{}", namespace, key); |
| 222 | + sqlite_store.persist(&prefixed_key, &data).unwrap(); |
| 223 | + let mut reader = sqlite_store.read(namespace, key).unwrap(); |
| 224 | + let read_data: [u8; 32] = Readable::read(&mut reader).unwrap(); |
| 225 | + assert_eq!(data, read_data); |
| 226 | + } |
| 227 | + } |
| 228 | +} |
0 commit comments