|
| 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::sync::{Arc, Mutex}; |
| 12 | + |
| 13 | +// The database file name. |
| 14 | +const SQLITE_DB_FILE: &str = "ldk_node.sqlite"; |
| 15 | + |
| 16 | +// The table in which we store all data. |
| 17 | +const KV_TABLE_NAME: &str = "ldk_node_data"; |
| 18 | + |
| 19 | +// The current SQLite `user_version`, which we can use if we'd ever need to do a schema migration. |
| 20 | +const SCHEMA_USER_VERSION: u16 = 1; |
| 21 | + |
| 22 | +/// A [`KVStore`] implementation that writes to and reads from an [SQLite] database. |
| 23 | +/// |
| 24 | +/// [SQLite]: https://sqlite.org |
| 25 | +pub struct SqliteStore { |
| 26 | + connection: Arc<Mutex<Connection>>, |
| 27 | +} |
| 28 | + |
| 29 | +impl SqliteStore { |
| 30 | + pub(crate) fn new(dest_dir: PathBuf) -> Self { |
| 31 | + fs::create_dir_all(dest_dir.clone()).unwrap_or_else(|_| { |
| 32 | + panic!("Failed to create database destination directory: {}", dest_dir.display()) |
| 33 | + }); |
| 34 | + let mut db_file_path = dest_dir.clone(); |
| 35 | + db_file_path.push(SQLITE_DB_FILE); |
| 36 | + |
| 37 | + let connection = Connection::open(db_file_path.clone()).unwrap_or_else(|_| { |
| 38 | + panic!("Failed to open/create database file: {}", db_file_path.display()) |
| 39 | + }); |
| 40 | + |
| 41 | + connection |
| 42 | + .pragma(Some(rusqlite::DatabaseName::Main), "user_version", SCHEMA_USER_VERSION, |_| { |
| 43 | + Ok(()) |
| 44 | + }) |
| 45 | + .unwrap_or_else(|_| panic!("Failed to set PRAGMA user_version")); |
| 46 | + |
| 47 | + let sql = format!( |
| 48 | + "CREATE TABLE IF NOT EXISTS {} ( |
| 49 | + namespace TEXT NOT NULL, |
| 50 | + key TEXT NOT NULL CHECK (key <> ''), |
| 51 | + value BLOB, PRIMARY KEY ( namespace, key ) |
| 52 | + );", |
| 53 | + KV_TABLE_NAME |
| 54 | + ); |
| 55 | + connection |
| 56 | + .execute(&sql, []) |
| 57 | + .unwrap_or_else(|_| panic!("Failed to create table: {}", KV_TABLE_NAME)); |
| 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 locked_conn = self.connection.lock().unwrap(); |
| 69 | + let sql = |
| 70 | + format!("SELECT value FROM {} WHERE namespace=:namespace AND key=:key;", KV_TABLE_NAME); |
| 71 | + |
| 72 | + let res = locked_conn |
| 73 | + .query_row( |
| 74 | + &sql, |
| 75 | + named_params! { |
| 76 | + ":namespace": namespace, |
| 77 | + ":key": key, |
| 78 | + }, |
| 79 | + |row| row.get(0), |
| 80 | + ) |
| 81 | + .map_err(|e| match e { |
| 82 | + rusqlite::Error::QueryReturnedNoRows => { |
| 83 | + let msg = |
| 84 | + format!("Failed to read as key could not be found: {}/{}", namespace, key); |
| 85 | + std::io::Error::new(std::io::ErrorKind::NotFound, msg) |
| 86 | + } |
| 87 | + e => { |
| 88 | + let msg = format!("Failed to read from key {}/{}: {}", namespace, key, e); |
| 89 | + std::io::Error::new(std::io::ErrorKind::Other, msg) |
| 90 | + } |
| 91 | + })?; |
| 92 | + Ok(Cursor::new(res)) |
| 93 | + } |
| 94 | + |
| 95 | + fn write(&self, namespace: &str, key: &str, buf: &[u8]) -> std::io::Result<()> { |
| 96 | + let locked_conn = self.connection.lock().unwrap(); |
| 97 | + |
| 98 | + let sql = format!( |
| 99 | + "INSERT OR REPLACE INTO {} (namespace, key, value) VALUES (:namespace, :key, :value);", |
| 100 | + KV_TABLE_NAME |
| 101 | + ); |
| 102 | + |
| 103 | + locked_conn |
| 104 | + .execute( |
| 105 | + &sql, |
| 106 | + named_params! { |
| 107 | + ":namespace": namespace, |
| 108 | + ":key": key, |
| 109 | + ":value": buf, |
| 110 | + }, |
| 111 | + ) |
| 112 | + .map(|_| ()) |
| 113 | + .map_err(|e| { |
| 114 | + let msg = format!("Failed to write to key {}/{}: {}", namespace, key, e); |
| 115 | + std::io::Error::new(std::io::ErrorKind::Other, msg) |
| 116 | + }) |
| 117 | + } |
| 118 | + |
| 119 | + fn remove(&self, namespace: &str, key: &str) -> std::io::Result<bool> { |
| 120 | + let locked_conn = self.connection.lock().unwrap(); |
| 121 | + |
| 122 | + let sql = format!("DELETE FROM {} WHERE namespace=:namespace AND key=:key;", KV_TABLE_NAME); |
| 123 | + let changes = locked_conn |
| 124 | + .execute( |
| 125 | + &sql, |
| 126 | + named_params! { |
| 127 | + ":namespace": namespace, |
| 128 | + ":key": key, |
| 129 | + }, |
| 130 | + ) |
| 131 | + .map_err(|e| { |
| 132 | + let msg = format!("Failed to delete key {}/{}: {}", namespace, key, e); |
| 133 | + std::io::Error::new(std::io::ErrorKind::Other, msg) |
| 134 | + })?; |
| 135 | + |
| 136 | + let was_present = changes != 0; |
| 137 | + |
| 138 | + Ok(was_present) |
| 139 | + } |
| 140 | + |
| 141 | + fn list(&self, namespace: &str) -> std::io::Result<Vec<String>> { |
| 142 | + let locked_conn = self.connection.lock().unwrap(); |
| 143 | + |
| 144 | + let sql = format!("SELECT key FROM {} WHERE namespace=:namespace", KV_TABLE_NAME); |
| 145 | + let mut stmt = locked_conn.prepare(&sql).map_err(|e| { |
| 146 | + let msg = format!("Failed to prepare statement: {}", e); |
| 147 | + std::io::Error::new(std::io::ErrorKind::Other, msg) |
| 148 | + })?; |
| 149 | + |
| 150 | + let mut keys = Vec::new(); |
| 151 | + |
| 152 | + let rows_iter = stmt |
| 153 | + .query_map(named_params! {":namespace": namespace, }, |row| row.get(0)) |
| 154 | + .map_err(|e| { |
| 155 | + let msg = format!("Failed to retrieve queried rows: {}", e); |
| 156 | + std::io::Error::new(std::io::ErrorKind::Other, msg) |
| 157 | + })?; |
| 158 | + |
| 159 | + for k in rows_iter { |
| 160 | + keys.push(k.map_err(|e| { |
| 161 | + let msg = format!("Failed to retrieve queried rows: {}", e); |
| 162 | + std::io::Error::new(std::io::ErrorKind::Other, msg) |
| 163 | + })?); |
| 164 | + } |
| 165 | + |
| 166 | + Ok(keys) |
| 167 | + } |
| 168 | +} |
| 169 | + |
| 170 | +impl KVStorePersister for SqliteStore { |
| 171 | + fn persist<W: Writeable>(&self, prefixed_key: &str, object: &W) -> lightning::io::Result<()> { |
| 172 | + let (namespace, key) = get_namespace_and_key_from_prefixed(prefixed_key)?; |
| 173 | + self.write(&namespace, &key, &object.encode()) |
| 174 | + } |
| 175 | +} |
| 176 | + |
| 177 | +#[cfg(test)] |
| 178 | +mod tests { |
| 179 | + use super::*; |
| 180 | + use crate::test::utils::random_storage_path; |
| 181 | + |
| 182 | + use proptest::prelude::*; |
| 183 | + proptest! { |
| 184 | + #[test] |
| 185 | + fn read_write_remove_list_persist(data in any::<[u8; 32]>()) { |
| 186 | + let rand_dir = random_storage_path(); |
| 187 | + let sqlite_store = SqliteStore::new(rand_dir.into()); |
| 188 | + |
| 189 | + do_read_write_remove_list_persist(&data, &sqlite_store); |
| 190 | + } |
| 191 | + } |
| 192 | +} |
0 commit comments