Files
rukosync/src/writer.rs
T
2026-10-06 18:11:20 +03:00

54 lines
2.5 KiB
Rust

use std::path::Path;
use sha2::{Digest as _, Sha256};
use tokio_rusqlite::{Connection, OptionalExtension as _, named_params, rusqlite};
pub struct Writer {
// Note that I don't need to wrap this in a mutex because
// tokio_rusqlite already serializes each request into a single executor
pub connection: Connection,
}
const MIGRATIONS : [&str; 8] = [
"create table if not exists users (id primary key, username not null, secret not null, unique(username))",
"create table if not exists progress (user_id not null, document_id not null, progress not null, percentage not null, device not null, device_id, timestamp not null, unique(user_id, document_id), foreign key (user_id) references users(id))",
"create table document (id not null primary key, title, filename, author)",
"insert into document (id) select distinct(document_id) from progress",
"alter table progress rename to progress_bak",
"create table progress (user_id not null, document_id not null, progress not null, percentage not null, device not null, device_id, timestamp not null, foreign key (user_id) references users(id), foreign key (document_id) references document(id))",
"insert into progress (user_id, document_id, progress, percentage, device, device_id, timestamp) select user_id, document_id, progress, percentage, device, device_id, timestamp from progress_bak",
"drop table progress_bak",
];
struct Migration { sql: String, fingerprint: Vec<u8> }
fn get_migrations() -> Vec<Migration> {
MIGRATIONS
.iter()
.map(|m| { Migration{sql: m.to_string(), fingerprint: Sha256::digest(m).to_vec() } })
.collect()
}
impl Writer {
#[tracing::instrument]
pub async fn new(path: &Path) -> Result<Self, tokio_rusqlite::Error> {
let connection = Connection::open(path).await?;
connection.call(|conn| -> rusqlite::Result<()> {
conn.execute("create table if not exists migrations (hash not null, created_at)", [])?;
for Migration{sql,fingerprint} in get_migrations() {
if let None = conn.query_one("select * from migrations where hash = :hash", named_params! {":hash": fingerprint}, |_| Ok(true)).optional()? {
tracing::debug!("Applying {:?}", sql);
conn.execute(&sql, [])?;
conn.execute("insert into migrations (hash, created_at) values (:hash, :now)", named_params! {":hash": fingerprint, ":now": 0 })?;
}
}
Ok(())
}).await?;
Ok(Self{connection})
}
}