Skip to main content

coven_database/
migration.rs

1//! Numbered app migrations and their transaction-scoped SQL access.
2
3use crate::migration_names::MigrationNames;
4use crate::sqlite::StoreSql;
5use crate::SyncedTable;
6use crate::{DbError, MigrationError};
7use sqlive::rusqlite::{Params, Row};
8use std::cell::RefCell;
9use std::sync::Arc;
10
11/// How one migration changed the schema and synced rows (§18.1).
12#[derive(Clone, Debug, Eq, PartialEq)]
13pub enum MigrationChange {
14    /// No synced definition or row changed and no table disappeared. Local-only and
15    /// view changes must not be mistaken for a synced schema addition (§18.1).
16    NoChange,
17    /// Only synced tables or their columns were added.
18    Addition,
19    /// A table disappeared, a synced definition changed beyond an addition,
20    /// or statements changed rows of synced tables.
21    Breaking,
22}
23
24/// The classification of a migration committed by this open.
25#[derive(Clone, Debug, Eq, PartialEq)]
26pub struct MigrationOutcome {
27    /// Its position in the app's migration sequence.
28    pub version: u32,
29    /// The app's name for this migration.
30    pub name: &'static str,
31    /// Its schema comparison and row changes, before subsequent migrations.
32    pub change: MigrationChange,
33}
34
35pub(crate) type MigrationOperation =
36    dyn Fn(u32) -> Result<crate::NewOperation, DbError> + Send + Sync;
37
38type WriteConversion = dyn Fn(&mut crate::RowChange) -> Result<(), DbError> + Send + Sync;
39
40type MigrationBody = dyn Fn(&MigrationContext<'_>) -> Result<(), DbError> + Send + Sync;
41
42/// What a breaking migration does with received late old-version writes.
43#[derive(Clone)]
44pub enum OldWrites {
45    /// Convert eligible changes without rewriting their original upload records.
46    Convert(Arc<WriteConversion>),
47    /// Keep each original change as a frozen schema loss; never discard its values.
48    Drop,
49}
50
51#[derive(Clone)]
52pub(crate) enum MigrationKind {
53    Addition,
54    Breaking(OldWrites),
55}
56
57/// One numbered change to the app's database, with its declared kind.
58/// Clones retain the same callbacks across bootstrap and database opening.
59#[derive(Clone)]
60pub struct Migration {
61    pub(crate) version: u32,
62    pub(crate) name: &'static str,
63    body: Arc<MigrationBody>,
64    pub(crate) kind: MigrationKind,
65    /// The synced tables the schema before a breaking migration declares
66    /// (§18.3); empty for an addition.
67    pub(crate) starts_from: Vec<SyncedTable>,
68}
69
70impl Migration {
71    /// SQL that adds tables or columns, or changes only local objects.
72    /// A runtime breaking classification refuses the whole migration batch.
73    pub fn addition(version: u32, name: &'static str, sql: &'static str) -> Self {
74        Self::addition_with(version, name, move |context| {
75            context.execute_batch(sql)?;
76            Ok(())
77        })
78    }
79
80    /// Code that adds tables or columns, or changes only local objects.
81    pub fn addition_with<F>(version: u32, name: &'static str, f: F) -> Self
82    where
83        F: Fn(&MigrationContext<'_>) -> Result<(), DbError> + Send + Sync + 'static,
84    {
85        Self {
86            version,
87            name,
88            body: Arc::new(f),
89            kind: MigrationKind::Addition,
90            starts_from: Vec::new(),
91        }
92    }
93
94    /// Breaking SQL with an explicit choice for late old-version writes, and the
95    /// synced tables the schema before it declares (`starts_from`, §18.3).
96    /// An addition or local-only classification refuses the whole batch.
97    ///
98    /// A breaking migration cannot omit the old-write choice:
99    /// ```compile_fail
100    /// use coven_database::Migration;
101    /// Migration::breaking(2, "rename", "ALTER TABLE notes RENAME COLUMN title TO name", vec![]);
102    /// ```
103    pub fn breaking(
104        version: u32,
105        name: &'static str,
106        sql: &'static str,
107        old_writes: OldWrites,
108        starts_from: Vec<SyncedTable>,
109    ) -> Self {
110        Self::breaking_with(
111            version,
112            name,
113            move |context| {
114                context.execute_batch(sql)?;
115                Ok(())
116            },
117            old_writes,
118            starts_from,
119        )
120    }
121
122    /// Breaking code, including backfills and rebuilds, with its old-write choice
123    /// and the synced tables the schema before it declares (`starts_from`).
124    ///
125    /// ```compile_fail
126    /// use coven_database::Migration;
127    /// Migration::breaking_with(2, "backfill", |context| {
128    ///     context.execute_batch("UPDATE notes SET title=upper(title)")?;
129    ///     Ok(())
130    /// });
131    /// ```
132    pub fn breaking_with<F>(
133        version: u32,
134        name: &'static str,
135        f: F,
136        old_writes: OldWrites,
137        starts_from: Vec<SyncedTable>,
138    ) -> Self
139    where
140        F: Fn(&MigrationContext<'_>) -> Result<(), DbError> + Send + Sync + 'static,
141    {
142        Self {
143            version,
144            name,
145            body: Arc::new(f),
146            kind: MigrationKind::Breaking(old_writes),
147            starts_from,
148        }
149    }
150
151    pub(crate) fn check_kind(&self, breaking: bool) -> Result<(), DbError> {
152        if matches!(self.kind, MigrationKind::Breaking(_)) != breaking {
153            return Err(DbError::MigrationKindMismatch { version: self.version });
154        }
155        Ok(())
156    }
157
158    pub(crate) fn apply(&self, context: &MigrationContext<'_>) -> Result<(), DbError> {
159        (self.body)(context)
160    }
161}
162
163/// The version of the newest breaking migration in `migrations`, zero if none:
164/// the breaking version an installation that runs them all reaches (§16.3).
165pub fn newest_breaking_version(migrations: &[Migration]) -> u32 {
166    migrations
167        .iter()
168        .filter(|m| matches!(m.kind, MigrationKind::Breaking(_)))
169        .map(|m| m.version)
170        .max()
171        .unwrap_or(0)
172}
173
174pub(crate) fn validate_versions(migrations: &[Migration]) -> Result<u32, MigrationError> {
175    let mut supported = 0u32;
176    for (position, migration) in migrations.iter().enumerate() {
177        let expected = supported.checked_add(1).expect("migration list fits in u32");
178        if migration.version != expected {
179            return Err(MigrationError::NotContiguous {
180                position,
181                found: migration.version,
182                expected,
183            });
184        }
185        supported = expected;
186    }
187    Ok(supported)
188}
189
190/// App SQL inside the transaction owned by the migration run.
191/// The context borrows its owner and cannot change the transaction or connection.
192pub struct MigrationContext<'connection> {
193    database: &'connection StoreSql,
194    names: RefCell<MigrationNames>,
195    /// The schema before this step, which the step hands back when it ends.
196    before: crate::schema::Schema,
197    /// The run's capture, which each step takes from the last.
198    capture: RefCell<crate::migration_snapshot::MigrationCapture<'connection>>,
199}
200
201impl<'connection> MigrationContext<'connection> {
202    pub(crate) fn new(
203        database: &'connection StoreSql,
204        before: crate::schema::Schema,
205        capture: crate::migration_snapshot::MigrationCapture<'connection>,
206    ) -> Self {
207        Self {
208            database,
209            names: RefCell::new(MigrationNames::new(&before)),
210            before,
211            capture: RefCell::new(capture),
212        }
213    }
214
215    /// The step's effects on the schema, the schema it started from, and the
216    /// run's capture for the next step.
217    pub(crate) fn finish(
218        self,
219        after: &crate::schema::Schema,
220    ) -> (
221        crate::migration_names::MigrationEffects,
222        crate::schema::Schema,
223        crate::migration_snapshot::MigrationCapture<'connection>,
224    ) {
225        (
226            self.names.into_inner().finish(&self.before, after),
227            self.before,
228            self.capture.into_inner(),
229        )
230    }
231
232    fn statement<T>(
233        &self,
234        sql: &str,
235        run: impl FnOnce() -> sqlive::rusqlite::Result<T>,
236    ) -> sqlive::rusqlite::Result<T> {
237        self.before_statement(sql)?;
238        let before = self.database.schema_cookie()?;
239        let result = run();
240        if self.database.schema_cookie()? != before {
241            self.record(sql)?;
242        }
243        result
244    }
245
246    fn before_statement(&self, sql: &str) -> sqlive::rusqlite::Result<()> {
247        self.capture.borrow_mut().before(&self.before, sql)
248    }
249
250    fn record(&self, sql: &str) -> sqlive::rusqlite::Result<()> {
251        self.names.borrow_mut().record(sql)
252    }
253
254    /// Execute one app statement with parameters.
255    pub fn execute<P: Params>(&self, sql: &str, params: P) -> sqlive::rusqlite::Result<usize> {
256        self.statement(sql, || self.database.app_execute(sql, params))
257    }
258
259    /// Execute app statements without escaping the migration transaction.
260    pub fn execute_batch(&self, sql: &str) -> sqlive::rusqlite::Result<()> {
261        self.database.app_batch_each(sql, |text, step| self.statement(text, &mut *step))
262    }
263
264    /// Map one row from an app query.
265    pub fn query_row<T, P, F>(&self, sql: &str, params: P, map: F) -> sqlive::rusqlite::Result<T>
266    where
267        P: Params,
268        F: FnOnce(&Row<'_>) -> sqlive::rusqlite::Result<T>,
269    {
270        self.statement(sql, || self.database.app_query_row(sqlive::Recorded::No, sql, params, map))
271    }
272
273    /// Map every result of an app query.
274    pub fn query<T, P, F>(&self, sql: &str, params: P, map: F) -> sqlive::rusqlite::Result<Vec<T>>
275    where
276        P: Params,
277        F: FnMut(&Row<'_>) -> sqlive::rusqlite::Result<T>,
278    {
279        self.statement(sql, || self.database.app_query(sqlive::Recorded::No, sql, params, map))
280    }
281}
282
283#[cfg(test)]
284#[path = "migration_tests.rs"]
285pub(crate) mod tests;