1use crate::history::{history_version, Applied};
4use cufflink_types::manifest::validate::MAX_MIGRATION_VERSION;
5use cufflink_types::SqlMigration;
6use siphasher::sip::SipHasher13;
7use std::collections::BTreeMap;
8use std::hash::{Hash, Hasher};
9
10pub fn checksum(migration: &SqlMigration) -> u64 {
14 let mut hasher = SipHasher13::new();
15 migration.name.hash(&mut hasher);
16 history_version(migration.version).hash(&mut hasher);
17 migration.sql.as_str().hash(&mut hasher);
18 hasher.finish()
19}
20
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct Plan {
23 pub pending: Vec<SqlMigration>,
25 pub verified: usize,
27 pub baselined: Vec<i32>,
30}
31
32#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]
33pub enum PlanError {
34 #[error(
35 "migration V{version} diverges from the one applied: applied '{applied_name}' \
36 (checksum {applied_checksum}), local '{local_name}' (checksum {local_checksum})"
37 )]
38 Divergent {
39 version: i32,
40 applied_name: String,
41 local_name: String,
42 applied_checksum: u64,
43 local_checksum: u64,
44 },
45 #[error(
46 "applied migration {} has no local file",
47 SqlMigration::stem_of(version, name)
48 )]
49 Missing { version: i32, name: String },
50 #[error(
51 "migration V{version} is not applied and precedes V{max_applied}, which is; \
52 a new migration takes a version above every applied one"
53 )]
54 OutOfOrder { version: u32, max_applied: i32 },
55 #[error("migration version {version} is declared twice")]
56 Duplicate { version: u32 },
57 #[error("migration version {version} is above {MAX_MIGRATION_VERSION}")]
58 VersionOutOfRange { version: u32 },
59 #[error("history row of version {version} is unreadable: {reason}")]
60 BadHistoryRow { version: i32, reason: String },
61}
62
63fn by_version(local: &[SqlMigration]) -> Result<BTreeMap<i64, &SqlMigration>, PlanError> {
64 local.iter().try_fold(BTreeMap::new(), |mut found, m| {
65 if m.version > MAX_MIGRATION_VERSION {
66 return Err(PlanError::VersionOutOfRange { version: m.version });
67 }
68 match found.insert(i64::from(m.version), m) {
69 Some(_) => Err(PlanError::Duplicate { version: m.version }),
70 None => Ok(found),
71 }
72 })
73}
74
75enum Standing {
76 Verified,
77 Baselined,
78}
79
80fn standing(
81 applied: &Applied,
82 local: Option<&SqlMigration>,
83 baseline: Option<u32>,
84) -> Result<Standing, PlanError> {
85 let under_baseline =
86 baseline.is_some_and(|baseline| i64::from(applied.version) <= i64::from(baseline));
87 match local.map(|local| (local, checksum(local))) {
88 Some((local, sum)) if local.name == applied.name && sum == applied.checksum => {
89 Ok(Standing::Verified)
90 }
91 _ if under_baseline => Ok(Standing::Baselined),
92 Some((local, sum)) => Err(PlanError::Divergent {
93 version: applied.version,
94 applied_name: applied.name.clone(),
95 local_name: local.name.clone(),
96 applied_checksum: applied.checksum,
97 local_checksum: sum,
98 }),
99 None => Err(PlanError::Missing {
100 version: applied.version,
101 name: applied.name.clone(),
102 }),
103 }
104}
105
106pub fn plan(
110 applied: &[Applied],
111 local: &[SqlMigration],
112 baseline: Option<u32>,
113) -> Result<Plan, PlanError> {
114 let files = by_version(local)?;
115 let (verified, baselined) =
116 applied
117 .iter()
118 .try_fold((0usize, Vec::new()), |(verified, mut baselined), row| {
119 let file = files.get(&i64::from(row.version)).copied();
120 standing(row, file, baseline).map(|standing| match standing {
121 Standing::Verified => (verified + 1, baselined),
122 Standing::Baselined => {
123 baselined.push(row.version);
124 (verified, baselined)
125 }
126 })
127 })?;
128 let max_applied = applied.iter().map(|row| row.version).max();
129 let is_applied = |version: i64| applied.iter().any(|row| i64::from(row.version) == version);
130 let pending: Vec<SqlMigration> = files
131 .iter()
132 .filter(|(version, _)| !is_applied(**version))
133 .map(|(version, file)| match max_applied {
134 Some(max_applied) if *version < i64::from(max_applied) => Err(PlanError::OutOfOrder {
135 version: file.version,
136 max_applied,
137 }),
138 _ => Ok((*file).clone()),
139 })
140 .collect::<Result<_, _>>()?;
141 Ok(Plan {
142 pending,
143 verified,
144 baselined,
145 })
146}
147
148#[cfg(test)]
149mod tests {
150 use super::*;
151
152 fn file(version: u32, name: &str, sql: &str) -> SqlMigration {
153 SqlMigration {
154 version,
155 name: name.into(),
156 sql: sql.into(),
157 no_transaction: false,
158 }
159 }
160
161 fn row(file: &SqlMigration) -> Applied {
162 Applied {
163 version: file.version as i32,
164 name: file.name.clone(),
165 checksum: checksum(file),
166 applied_on: "2024-05-01T09:30:00Z".into(),
167 }
168 }
169
170 fn foreign(version: i32) -> Applied {
171 Applied {
172 version,
173 name: format!("deferred_{version}"),
174 checksum: 7,
175 applied_on: "2024-05-01T09:30:00Z".into(),
176 }
177 }
178
179 fn loan_service() -> Vec<SqlMigration> {
180 vec![
181 file(
182 1,
183 "initial_tables",
184 "CREATE TABLE loans (id UUID PRIMARY KEY);\n",
185 ),
186 file(
187 6,
188 "add_loan_kind",
189 "ALTER TABLE loans ADD COLUMN kind TEXT;\r\n",
190 ),
191 file(
192 7,
193 "renewal_index",
194 "CREATE INDEX loans_renewal ON loans (id);",
195 ),
196 ]
197 }
198
199 fn versions(plan: &Plan) -> Vec<u32> {
200 plan.pending.iter().map(|m| m.version).collect()
201 }
202
203 #[test]
204 fn the_checksum_is_refinerys() {
205 for migration in loan_service().into_iter().chain([
206 file(2_147_483_647, "last", "SELECT 1;"),
207 file(0, "zero", "\u{feff}-- cufflink:no-transaction\nSELECT 'é';"),
208 file(
209 8,
210 "windows_line_endings",
211 "CREATE TABLE loans (\r\n id uuid PRIMARY KEY\r\n);\r\n",
212 ),
213 ]) {
214 let refinery =
215 refinery_core::Migration::unapplied(&migration.file_stem(), &migration.sql)
216 .expect("a refinery migration");
217 assert_eq!(checksum(&migration), refinery.checksum(), "{migration:?}");
218 }
219 }
220
221 #[test]
222 fn a_fresh_history_applies_everything_in_order() {
223 let mut local = loan_service();
224 local.reverse();
225 let plan = plan(&[], &local, None).expect("plan");
226 assert_eq!(versions(&plan), [1, 6, 7]);
227 assert_eq!((plan.verified, plan.baselined), (0, vec![]));
228 }
229
230 #[test]
231 fn a_history_is_continued_after_a_gap() {
232 let local = loan_service();
233 let applied = [row(&local[0]), row(&local[1])];
234 let plan = plan(&applied, &local, None).expect("plan");
235 assert_eq!(versions(&plan), [7]);
236 assert_eq!((plan.verified, plan.baselined), (2, vec![]));
237 let done = [row(&local[0]), row(&local[1]), row(&local[2])];
238 assert_eq!(
239 super::plan(&done, &local, None),
240 Ok(Plan {
241 pending: vec![],
242 verified: 3,
243 baselined: vec![]
244 })
245 );
246 }
247
248 #[test]
249 fn a_changed_name_or_checksum_diverges() {
250 let local = loan_service();
251 let renamed = Applied {
252 name: "add_kind".into(),
253 ..row(&local[1])
254 };
255 assert_eq!(
256 plan(&[row(&local[0]), renamed], &local, None),
257 Err(PlanError::Divergent {
258 version: 6,
259 applied_name: "add_kind".into(),
260 local_name: "add_loan_kind".into(),
261 applied_checksum: checksum(&local[1]),
262 local_checksum: checksum(&local[1]),
263 })
264 );
265 let edited = Applied {
266 checksum: 42,
267 ..row(&local[1])
268 };
269 let error = plan(&[row(&local[0]), edited], &local, None).expect_err("diverges");
270 assert_eq!(
271 error.to_string(),
272 format!(
273 "migration V6 diverges from the one applied: applied 'add_loan_kind' \
274 (checksum 42), local 'add_loan_kind' (checksum {})",
275 checksum(&local[1])
276 )
277 );
278 }
279
280 #[test]
281 fn an_applied_migration_needs_its_file_above_the_baseline() {
282 let local = loan_service();
283 let applied = [row(&local[0]), foreign(3), row(&local[1])];
284 assert_eq!(
285 plan(&applied, &local, None),
286 Err(PlanError::Missing {
287 version: 3,
288 name: "deferred_3".into()
289 })
290 );
291 assert_eq!(
292 plan(&applied, &local, Some(2)),
293 Err(PlanError::Missing {
294 version: 3,
295 name: "deferred_3".into()
296 })
297 );
298 let plan = plan(&applied, &local, Some(3)).expect("plan");
299 assert_eq!(versions(&plan), [7]);
300 assert_eq!((plan.verified, plan.baselined), (2, vec![3]));
301 }
302
303 #[test]
304 fn a_history_under_the_baseline_is_accepted_unverified() {
305 let applied: Vec<Applied> = (1..=15).map(foreign).collect();
306 let local: Vec<SqlMigration> = (14..=16)
307 .map(|v| file(v, &format!("report_{v}"), "SELECT 1;"))
308 .collect();
309 let plan = plan(&applied, &local, Some(15)).expect("plan");
310 assert_eq!(versions(&plan), [16]);
311 assert_eq!(plan.verified, 0);
312 assert_eq!(plan.baselined, (1..=15).collect::<Vec<i32>>());
313 }
314
315 #[test]
316 fn a_new_file_under_an_applied_version_is_out_of_order() {
317 let mut local = loan_service();
318 let applied = [row(&local[0]), row(&local[1])];
319 local.push(file(4, "late", "SELECT 1;"));
320 assert_eq!(
321 plan(&applied, &local, None),
322 Err(PlanError::OutOfOrder {
323 version: 4,
324 max_applied: 6
325 })
326 );
327 assert_eq!(
328 plan(&applied, &local, Some(6)),
329 Err(PlanError::OutOfOrder {
330 version: 4,
331 max_applied: 6
332 })
333 );
334 }
335
336 #[test]
337 fn line_endings_are_part_of_what_is_checksummed() {
338 assert_ne!(
339 checksum(&file(8, "loans", "SELECT 1;\r\nSELECT 2;\r\n")),
340 checksum(&file(8, "loans", "SELECT 1;\nSELECT 2;\n")),
341 "a checkout that rewrites line endings diverges, as it does under refinery"
342 );
343 }
344
345 #[test]
346 fn a_version_the_history_cannot_hold_is_refused() {
347 let mut local = loan_service();
348 local.push(file(2_147_483_648, "too_far", "SELECT 1;"));
349 assert_eq!(
350 plan(&[], &local, None),
351 Err(PlanError::VersionOutOfRange {
352 version: 2_147_483_648
353 })
354 );
355 }
356
357 #[test]
358 fn a_version_declared_twice_is_refused() {
359 let mut local = loan_service();
360 local.push(file(6, "again", "SELECT 1;"));
361 assert_eq!(
362 plan(&[], &local, None),
363 Err(PlanError::Duplicate { version: 6 })
364 );
365 }
366}