| 1 |
|
| 2 |
|
| 3 |
mod migrations; |
| 4 |
mod stats; |
| 5 |
|
| 6 |
use std::path::Path; |
| 7 |
|
| 8 |
use rusqlite::Connection; |
| 9 |
use synckit_config::{ConfigError, ConfigStore}; |
| 10 |
use thiserror::Error; |
| 11 |
use tracing::instrument; |
| 12 |
|
| 13 |
use crate::config_key::{CONFIG, ConfigKey}; |
| 14 |
use migrations::{MIGRATIONS, register_hash_row_id}; |
| 15 |
|
| 16 |
pub use migrations::SCHEMA_VERSION; |
| 17 |
|
| 18 |
#[derive(Error, Debug)] |
| 19 |
pub enum DbError { |
| 20 |
#[error("SQLite error: {0}")] |
| 21 |
Sqlite(#[from] rusqlite::Error), |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
#[error( |
| 27 |
"this vault was written by a newer version of audiofiles \ |
| 28 |
(vault schema {found}, this build understands {supported}). \ |
| 29 |
Update audiofiles to open it." |
| 30 |
)] |
| 31 |
VaultTooNew { |
| 32 |
|
| 33 |
found: i32, |
| 34 |
|
| 35 |
supported: i32, |
| 36 |
}, |
| 37 |
} |
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
impl From<ConfigError> for DbError { |
| 42 |
fn from(error: ConfigError) -> Self { |
| 43 |
match error { |
| 44 |
ConfigError::Db(error) => DbError::Sqlite(error), |
| 45 |
} |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
pub struct Database { |
| 52 |
conn: Connection, |
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
config: ConfigStore, |
| 57 |
} |
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
pub struct Tx(()); |
| 72 |
|
| 73 |
impl Database { |
| 74 |
|
| 75 |
#[instrument(skip_all)] |
| 76 |
pub fn open(path: impl AsRef<Path>) -> Result<Self, DbError> { |
| 77 |
let conn = Connection::open(path)?; |
| 78 |
conn.execute_batch( |
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
"PRAGMA journal_mode=WAL;\ |
| 87 |
PRAGMA synchronous=NORMAL;\ |
| 88 |
PRAGMA foreign_keys=ON;\ |
| 89 |
PRAGMA busy_timeout=5000;\ |
| 90 |
PRAGMA cache_size=-16000;\ |
| 91 |
PRAGMA mmap_size=268435456;\ |
| 92 |
PRAGMA temp_store=MEMORY;\ |
| 93 |
PRAGMA wal_checkpoint(TRUNCATE);", |
| 94 |
)?; |
| 95 |
register_hash_row_id(&conn)?; |
| 96 |
let mut db = Self { |
| 97 |
conn, |
| 98 |
config: ConfigStore::attached(&CONFIG), |
| 99 |
}; |
| 100 |
db.migrate()?; |
| 101 |
db.seed_config_key_policy()?; |
| 102 |
Ok(db) |
| 103 |
} |
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
pub fn wal_checkpoint(&self) -> Result<(), DbError> { |
| 110 |
self.conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")?; |
| 111 |
Ok(()) |
| 112 |
} |
| 113 |
|
| 114 |
|
| 115 |
#[instrument(skip_all)] |
| 116 |
pub fn open_in_memory() -> Result<Self, DbError> { |
| 117 |
let conn = Connection::open_in_memory()?; |
| 118 |
conn.execute_batch("PRAGMA foreign_keys=ON;")?; |
| 119 |
register_hash_row_id(&conn)?; |
| 120 |
let mut db = Self { |
| 121 |
conn, |
| 122 |
config: ConfigStore::attached(&CONFIG), |
| 123 |
}; |
| 124 |
db.migrate()?; |
| 125 |
db.seed_config_key_policy()?; |
| 126 |
Ok(db) |
| 127 |
} |
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
|
| 133 |
|
| 134 |
|
| 135 |
fn seed_config_key_policy(&self) -> Result<(), DbError> { |
| 136 |
self.conn.execute("DELETE FROM config_key_policy", [])?; |
| 137 |
let mut stmt = self |
| 138 |
.conn |
| 139 |
.prepare("INSERT INTO config_key_policy (key, replicated) VALUES (?1, ?2)")?; |
| 140 |
for row in CONFIG.policy_rows() { |
| 141 |
stmt.execute(rusqlite::params![row.key, i64::from(row.replicated)])?; |
| 142 |
} |
| 143 |
Ok(()) |
| 144 |
} |
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
|
| 149 |
pub fn get_config(&self, key: ConfigKey) -> Result<Option<String>, DbError> { |
| 150 |
Ok(self.config.get(&self.conn, key.as_str())?) |
| 151 |
} |
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
|
| 156 |
|
| 157 |
|
| 158 |
|
| 159 |
pub fn set_config(&self, key: ConfigKey, value: &str) -> Result<(), DbError> { |
| 160 |
self.config.set(&self.conn, key.as_str(), value)?; |
| 161 |
Ok(()) |
| 162 |
} |
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
pub fn delete_config(&self, key: ConfigKey) -> Result<(), DbError> { |
| 167 |
self.config.unset(&self.conn, key.as_str())?; |
| 168 |
Ok(()) |
| 169 |
} |
| 170 |
|
| 171 |
|
| 172 |
|
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
|
| 181 |
|
| 182 |
|
| 183 |
|
| 184 |
|
| 185 |
|
| 186 |
|
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
#[instrument(skip_all)] |
| 191 |
fn migrate(&mut self) -> Result<(), DbError> { |
| 192 |
let version: i32 = self |
| 193 |
.conn |
| 194 |
.query_row("PRAGMA user_version", [], |row| row.get(0))?; |
| 195 |
|
| 196 |
if version > SCHEMA_VERSION { |
| 197 |
return Err(DbError::VaultTooNew { |
| 198 |
found: version, |
| 199 |
supported: SCHEMA_VERSION, |
| 200 |
}); |
| 201 |
} |
| 202 |
|
| 203 |
for (i, sql) in MIGRATIONS.iter().enumerate() { |
| 204 |
let target = (i + 1) as i32; |
| 205 |
if version < target { |
| 206 |
let batch = format!("BEGIN;\n{sql}\nPRAGMA user_version = {target};\nCOMMIT;"); |
| 207 |
match self.conn.execute_batch(&batch) { |
| 208 |
Ok(()) => {} |
| 209 |
Err(e) if e.to_string().contains("duplicate column") => { |
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
|
| 215 |
|
| 216 |
|
| 217 |
|
| 218 |
|
| 219 |
let _ = self.conn.execute_batch("ROLLBACK"); |
| 220 |
self.conn.execute_batch("BEGIN")?; |
| 221 |
|
| 222 |
|
| 223 |
for line in sql.lines() { |
| 224 |
let trimmed = line.trim(); |
| 225 |
if trimmed.to_uppercase().starts_with("ALTER TABLE") |
| 226 |
&& trimmed.to_uppercase().contains("ADD COLUMN") |
| 227 |
&& let Err(alter_err) = self.conn.execute_batch(trimmed) |
| 228 |
&& !alter_err.to_string().contains("duplicate column") |
| 229 |
{ |
| 230 |
let _ = self.conn.execute_batch("ROLLBACK"); |
| 231 |
return Err(DbError::Sqlite(alter_err)); |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
|
| 241 |
|
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
let non_alter: String = sql |
| 247 |
.lines() |
| 248 |
.filter(|l| { |
| 249 |
let t = l.trim().to_uppercase(); |
| 250 |
!(t.starts_with("ALTER TABLE") && t.contains("ADD COLUMN")) |
| 251 |
}) |
| 252 |
.collect::<Vec<_>>() |
| 253 |
.join("\n"); |
| 254 |
if !non_alter.trim().is_empty() |
| 255 |
&& let Err(e) = self.conn.execute_batch(&non_alter) |
| 256 |
&& !e.to_string().contains("already exists") |
| 257 |
{ |
| 258 |
let _ = self.conn.execute_batch("ROLLBACK"); |
| 259 |
return Err(DbError::Sqlite(e)); |
| 260 |
} |
| 261 |
|
| 262 |
self.conn |
| 263 |
.execute_batch(&format!("PRAGMA user_version = {target};\nCOMMIT;"))?; |
| 264 |
} |
| 265 |
Err(e) => return Err(DbError::Sqlite(e)), |
| 266 |
} |
| 267 |
} |
| 268 |
} |
| 269 |
|
| 270 |
Ok(()) |
| 271 |
} |
| 272 |
|
| 273 |
|
| 274 |
|
| 275 |
|
| 276 |
|
| 277 |
|
| 278 |
|
| 279 |
|
| 280 |
|
| 281 |
|
| 282 |
#[instrument(skip_all)] |
| 283 |
pub fn transaction<T, F>(&self, f: F) -> Result<T, DbError> |
| 284 |
where |
| 285 |
F: FnOnce(&Tx) -> Result<T, DbError>, |
| 286 |
{ |
| 287 |
self.conn.execute_batch("BEGIN IMMEDIATE")?; |
| 288 |
match f(&Tx(())) { |
| 289 |
Ok(val) => { |
| 290 |
self.conn.execute_batch("COMMIT")?; |
| 291 |
Ok(val) |
| 292 |
} |
| 293 |
Err(e) => { |
| 294 |
if let Err(rb_err) = self.conn.execute_batch("ROLLBACK") { |
| 295 |
tracing::warn!("ROLLBACK failed after transaction error: {rb_err}"); |
| 296 |
} |
| 297 |
Err(e) |
| 298 |
} |
| 299 |
} |
| 300 |
} |
| 301 |
|
| 302 |
|
| 303 |
|
| 304 |
|
| 305 |
|
| 306 |
|
| 307 |
#[instrument(skip_all)] |
| 308 |
pub fn transaction_core<T, F>(&self, f: F) -> Result<T, crate::error::CoreError> |
| 309 |
where |
| 310 |
F: FnOnce(&Tx) -> Result<T, crate::error::CoreError>, |
| 311 |
{ |
| 312 |
self.conn.execute_batch("BEGIN IMMEDIATE")?; |
| 313 |
match f(&Tx(())) { |
| 314 |
Ok(val) => { |
| 315 |
self.conn.execute_batch("COMMIT")?; |
| 316 |
Ok(val) |
| 317 |
} |
| 318 |
Err(e) => { |
| 319 |
if let Err(rb_err) = self.conn.execute_batch("ROLLBACK") { |
| 320 |
tracing::warn!("ROLLBACK failed after transaction error: {rb_err}"); |
| 321 |
} |
| 322 |
Err(e) |
| 323 |
} |
| 324 |
} |
| 325 |
} |
| 326 |
|
| 327 |
|
| 328 |
pub fn conn(&self) -> &Connection { |
| 329 |
&self.conn |
| 330 |
} |
| 331 |
} |
| 332 |
|
| 333 |
#[cfg(test)] |
| 334 |
mod tests; |
| 335 |
|