Skip to main content

cufflink_types/manifest/
migration.rs

1use serde::{Deserialize, Serialize};
2
3/// One `V{version}__{name}.sql` file of the service's migrations directory.
4#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
5pub struct SqlMigration {
6    pub version: u32,
7    pub name: String,
8    /// The file's exact text: its checksum covers every byte, so it is
9    /// never normalised.
10    pub sql: String,
11    /// Run outside a transaction, as `CREATE INDEX CONCURRENTLY` requires:
12    /// the file's first line is [`SqlMigration::NO_TRANSACTION_MARKER`].
13    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
14    pub no_transaction: bool,
15}
16
17impl SqlMigration {
18    pub const NO_TRANSACTION_MARKER: &'static str = "-- cufflink:no-transaction";
19
20    /// Whether `sql` opts out of the transaction a migration runs in.
21    pub fn declares_no_transaction(sql: &str) -> bool {
22        sql.trim_start_matches('\u{feff}')
23            .lines()
24            .next()
25            .is_some_and(|line| line.trim() == Self::NO_TRANSACTION_MARKER)
26    }
27
28    /// `V{version}__{name}`, the name the migration's checksum covers.
29    pub fn file_stem(&self) -> String {
30        Self::stem_of(self.version, &self.name)
31    }
32
33    /// The [`file_stem`](Self::file_stem) of the migration `version` named
34    /// `name`, wherever only the two are at hand.
35    pub fn stem_of(version: impl std::fmt::Display, name: &str) -> String {
36        format!("V{version}__{name}")
37    }
38}
39
40/// Where the service's applied migrations are recorded, for a service
41/// continuing a history another runner began.
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43pub struct MigrationHistory {
44    /// `table`, in the service's schema, or `schema.table`.
45    pub table: String,
46    /// Applied versions up to this one are accepted without a local file.
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub baseline: Option<u32>,
49    #[serde(default, skip_serializing_if = "MigrationLock::is_platform")]
50    pub lock: MigrationLock,
51    #[serde(default, skip_serializing_if = "HistoryMode::is_apply")]
52    pub mode: HistoryMode,
53}
54
55impl MigrationHistory {
56    /// The history table of a service that declares none.
57    pub const DEFAULT_TABLE: &'static str = "refinery_schema_history";
58}
59
60impl Default for MigrationHistory {
61    fn default() -> Self {
62        Self {
63            table: Self::DEFAULT_TABLE.to_string(),
64            baseline: None,
65            lock: MigrationLock::default(),
66            mode: HistoryMode::default(),
67        }
68    }
69}
70
71/// The advisory lock a migration run holds.
72#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
73#[serde(rename_all = "snake_case")]
74pub enum MigrationLock {
75    #[default]
76    Platform,
77    /// The key a legacy refinery runner derives from the history table's
78    /// name, so the two never run at once.
79    LegacyTableHash,
80}
81
82impl MigrationLock {
83    pub fn is_platform(&self) -> bool {
84        *self == MigrationLock::Platform
85    }
86}
87
88#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(rename_all = "snake_case")]
90pub enum HistoryMode {
91    #[default]
92    Apply,
93    /// Check the history against the local files and apply nothing: another
94    /// runner still owns the migrations.
95    VerifyOnly,
96}
97
98impl HistoryMode {
99    pub fn is_apply(&self) -> bool {
100        *self == HistoryMode::Apply
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107    use serde_json::json;
108
109    #[test]
110    fn a_migration_is_named_by_one_stem() {
111        let migration = SqlMigration {
112            version: 12,
113            name: "loan_state".into(),
114            ..SqlMigration::default()
115        };
116        assert_eq!(migration.file_stem(), "V12__loan_state");
117        assert_eq!(
118            SqlMigration::stem_of(12_i32, "loan_state"),
119            migration.file_stem()
120        );
121    }
122
123    #[test]
124    fn a_migration_keeps_its_bytes() {
125        let sql = "\u{feff}CREATE TABLE a (\r\n  id INT\r\n);\r\n";
126        let migration = SqlMigration {
127            version: 6,
128            name: "add_loan_kind".into(),
129            sql: sql.into(),
130            no_transaction: false,
131        };
132        let wire = json!({"version": 6, "name": "add_loan_kind", "sql": sql});
133        assert_eq!(serde_json::to_value(&migration).unwrap(), wire);
134        let parsed: SqlMigration = serde_json::from_value(wire).unwrap();
135        assert_eq!(parsed.sql.as_bytes(), sql.as_bytes());
136        assert_eq!(parsed.file_stem(), "V6__add_loan_kind");
137    }
138
139    #[test]
140    fn the_marker_is_the_first_line() {
141        for sql in [
142            "-- cufflink:no-transaction\nCREATE INDEX CONCURRENTLY i ON t (c);",
143            "-- cufflink:no-transaction",
144            "  -- cufflink:no-transaction  \r\nCREATE INDEX CONCURRENTLY i ON t (c);",
145            "\u{feff}-- cufflink:no-transaction\nSELECT 1;",
146        ] {
147            assert!(SqlMigration::declares_no_transaction(sql), "{sql:?}");
148        }
149        for sql in [
150            "",
151            "SELECT 1;\n-- cufflink:no-transaction",
152            "\n-- cufflink:no-transaction\nSELECT 1;",
153            "-- cufflink:no-transaction please",
154            "--cufflink:no-transaction",
155        ] {
156            assert!(!SqlMigration::declares_no_transaction(sql), "{sql:?}");
157        }
158        let migration = SqlMigration {
159            version: 7,
160            name: "renewal_index".into(),
161            sql: "-- cufflink:no-transaction\nSELECT 1;".into(),
162            no_transaction: true,
163        };
164        assert_eq!(
165            serde_json::to_value(&migration).unwrap()["no_transaction"],
166            json!(true)
167        );
168    }
169
170    #[test]
171    fn history_round_trips() {
172        let default = MigrationHistory::default();
173        assert_eq!(
174            serde_json::to_value(&default).unwrap(),
175            json!({"table": "refinery_schema_history"})
176        );
177        let legacy = MigrationHistory {
178            table: "public.schema_history_deferred".into(),
179            baseline: Some(15),
180            lock: MigrationLock::LegacyTableHash,
181            mode: HistoryMode::VerifyOnly,
182        };
183        let wire = json!({
184            "table": "public.schema_history_deferred",
185            "baseline": 15,
186            "lock": "legacy_table_hash",
187            "mode": "verify_only"
188        });
189        assert_eq!(serde_json::to_value(&legacy).unwrap(), wire);
190        assert_eq!(
191            serde_json::from_value::<MigrationHistory>(wire).unwrap(),
192            legacy
193        );
194    }
195}