1use 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#[derive(Clone, Debug, Eq, PartialEq)]
13pub enum MigrationChange {
14 NoChange,
17 Addition,
19 Breaking,
22}
23
24#[derive(Clone, Debug, Eq, PartialEq)]
26pub struct MigrationOutcome {
27 pub version: u32,
29 pub name: &'static str,
31 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#[derive(Clone)]
44pub enum OldWrites {
45 Convert(Arc<WriteConversion>),
47 Drop,
49}
50
51#[derive(Clone)]
52pub(crate) enum MigrationKind {
53 Addition,
54 Breaking(OldWrites),
55}
56
57#[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 pub(crate) starts_from: Vec<SyncedTable>,
68}
69
70impl Migration {
71 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 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 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 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
163pub 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
190pub struct MigrationContext<'connection> {
193 database: &'connection StoreSql,
194 names: RefCell<MigrationNames>,
195 before: crate::schema::Schema,
197 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 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 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 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 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 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;