Files
keep/src/db.rs
Andrew Phillips b9bf5a831e Initial commit
2023-07-25 17:33:50 -03:00

37 lines
1.3 KiB
Rust

use rusqlite::{params, Connection, Error};
use rusqlite_migration::{Migrations, M};
use log::*;
use lazy_static::lazy_static;
lazy_static! {
static ref MIGRATIONS: Migrations<'static> = Migrations::new(vec![
M::up("CREATE TABLE keep(
id INTEGER AUTOINCREMENT NOT NULL,
ts TEXT NOT NULL,
compress TEXT NOT NULL,
hostname TEXT NOT NULL,
comment TEXT NOT NULL)
PRIMARY KEY(id);"),
M::up("CREATE TABLE tags (
id INTEGER NOT NULL,
name TEXT NOT NULL,
FOREIGN KEY(id) REFERENCES keep(id) ON DELETE CASCADE,
PRIMARY KEY(id, name));")
]);
}
fn open(path: String) -> Result<Connection, String> {
debug!("Opening DB {}", path);
match Connection::open(path) {
Ok(mut conn) => match conn.pragma_update(None, "foreign_keys", "ON") {
Ok(()) => match MIGRATIONS.to_latest(&mut conn) {
Ok(()) => Ok(conn),
Err(e) => Err(format!("Error migrating sqlite schema: {}", e))
},
Err(e) => Err(format!("Error setting sqlite pragma: {}", e))
}
Err(e) => Err(format!("Error connecting to database: {}", e))
}
}