use anyhow::{Context, Result};
use chrono::Utc;
use rusqlite::{Connection, Transaction, TransactionBehavior};
const DDL: &str = include_str!("schema.sql");
struct Migration {
version: i64,
name: &'static str,
sql: &'static str,
}
const SCHEMA_MIGRATIONS_TABLE_SQL: &str = include_str!("migrations/0002_schema_migrations.sql");
const MEMORIES_DEDUP_KEY_SQL: &str = include_str!("migrations/0003_memories_dedup_key.sql");
const DISTILLATION_LOG_DISTILLED_IDX_SQL: &str =
include_str!("migrations/0004_distillation_log_distilled_idx.sql");
const MEMORIES_RETIRED_REASON_SQL: &str =
include_str!("migrations/0005_memories_retired_reason.sql");
const MIGRATIONS: &[Migration] = &[
Migration {
version: 2,
name: "0002_schema_migrations",
sql: SCHEMA_MIGRATIONS_TABLE_SQL,
},
Migration {
version: 3,
name: "0003_memories_dedup_key",
sql: MEMORIES_DEDUP_KEY_SQL,
},
Migration {
version: 4,
name: "0004_distillation_log_distilled_idx",
sql: DISTILLATION_LOG_DISTILLED_IDX_SQL,
},
Migration {
version: 5,
name: "0005_memories_retired_reason",
sql: MEMORIES_RETIRED_REASON_SQL,
},
];
pub const BASELINE_VERSION: i64 = 1;
pub const SCHEMA_VERSION: i64 = BASELINE_VERSION + MIGRATIONS.len() as i64;
pub fn schema_version(conn: &Connection) -> Result<i64> {
conn.query_row("PRAGMA user_version", [], |r| r.get(0))
.context("reading PRAGMA user_version")
}
pub fn init_schema(conn: &Connection) -> Result<()> {
migrate_to(conn, SCHEMA_VERSION)?;
let version = schema_version(conn)?;
if version > SCHEMA_VERSION {
tracing::warn!(
db_version = version,
binary_schema_version = SCHEMA_VERSION,
"database schema is newer than this binary; opening without migrating"
);
}
Ok(())
}
fn migrate_to(conn: &Connection, target: i64) -> Result<()> {
conn.execute_batch(SCHEMA_MIGRATIONS_TABLE_SQL)
.context("bootstrapping schema_migrations table")?;
while apply_next_migration(conn, target)? {}
Ok(())
}
#[cfg(any(test, feature = "test-support"))]
pub(super) fn create_at_version(conn: &Connection, version: i64) -> Result<()> {
anyhow::ensure!(
(BASELINE_VERSION..=SCHEMA_VERSION).contains(&version),
"schema version {version} is not on the ladder \
({BASELINE_VERSION}..={SCHEMA_VERSION})"
);
if version == BASELINE_VERSION {
conn.execute_batch(DDL)
.context("applying the baseline schema")?;
conn.pragma_update(None, "user_version", BASELINE_VERSION)
.context("stamping the baseline user_version")?;
return Ok(());
}
migrate_to(conn, version)
}
fn apply_next_migration(conn: &Connection, target: i64) -> Result<bool> {
let tx = Transaction::new_unchecked(conn, TransactionBehavior::Immediate)
.context("beginning migration transaction")?;
let version = schema_version(&tx)?;
if version >= target {
return Ok(false);
}
let next = version + 1;
let (name, sql) = step_for_version(next)?;
tx.execute_batch(sql)
.with_context(|| format!("applying migration {next} ({name})"))?;
tx.pragma_update(None, "user_version", next)
.context("updating user_version")?;
record_migration(&tx, next, name)?;
tx.commit().context("committing migration transaction")?;
Ok(true)
}
fn step_for_version(version: i64) -> Result<(&'static str, &'static str)> {
if version == BASELINE_VERSION {
return Ok(("schema.sql", DDL));
}
MIGRATIONS
.iter()
.find(|m| m.version == version)
.map(|m| (m.name, m.sql))
.with_context(|| format!("no migration registered for schema version {version}"))
}
fn record_migration(tx: &Transaction<'_>, version: i64, name: &str) -> Result<()> {
tx.execute(
"INSERT INTO schema_migrations (version, name, applied_at) VALUES (?1, ?2, ?3)",
rusqlite::params![version, name, Utc::now().to_rfc3339()],
)
.with_context(|| format!("recording schema_migrations row for version {version}"))?;
Ok(())
}