Skip to main content

bynk_check/
d1_migrations.rs

1//! Standard-library P4b (#2608): the project's `migrations/` folder, which
2//! holds each `D1` instance's schema migrations as
3//! `migrations/<database>/NNNN_<name>.sql`, where `<database>` is the
4//! instance's undecorated database name ([`d1_database_name`]).
5//!
6//! The checker stays disk-free: the folder reaches it from the caller as a
7//! [`bynk_project::assets::AssetFolder`], and [`phase_d1_migrations`] checks
8//! the file names, reads every file of a declared database, and warns about a
9//! directory no instance owns. Wrangler applies the files and records which
10//! ran in the database itself, so nothing here tracks that.
11
12use std::collections::{BTreeMap, HashMap};
13use std::path::PathBuf;
14
15use bynk_syntax::error::CompileError;
16use bynk_syntax::span::Span;
17
18use crate::project_model::ErrorSink;
19use crate::symbols::UnitTable;
20use bynk_project::UnitKind;
21use bynk_project::assets::PROJECT_MIGRATIONS_DIR;
22
23/// One migration file: its name (`0001_create_orders.sql`) and its SQL.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct MigrationFile {
26    pub name: String,
27    pub sql: String,
28}
29
30/// Whether the listed `key` is hidden (`.DS_Store`, an editor's
31/// `.0001_create.sql.swp`, anything under a `.archive/` directory) or an
32/// editor backup (`0001_create.sql~`), which the folder holds without meaning
33/// to: it's neither checked nor copied.
34pub fn is_ignored(key: &str) -> bool {
35    key.split('/').any(|part| part.starts_with('.')) || key.ends_with('~')
36}
37
38/// Every declared database's migrations, in order, keyed by database name.
39/// A database without a directory has no entry.
40pub type D1Migrations = BTreeMap<String, Vec<MigrationFile>>;
41
42/// W30 (#2840): the binding of a Worker's implicit idempotency database, which
43/// holds `Idempotency.claim`'s claims. A Worker that calls `claim` declares it
44/// with no author action; its database is `<worker>-idempotency`
45/// ([`d1_database_name`]), and its schema is [`implicit_migrations`].
46pub const IDEMPOTENCY_BINDING: &str = "D1_IDEMPOTENCY";
47
48/// W30 (#2840): the migration files the compiler owns for an implicit database
49/// (the author writes no SQL), by its `binding`; `None` for any other binding.
50/// `idempotency_claims` holds one row per claimed key and the time it lapses;
51/// `idempotency_values` one per remembered key: its JSON value and the time it lapses.
52pub fn implicit_migrations(
53    binding: &crate::worker_bindings::WorkerBinding,
54) -> Option<Vec<MigrationFile>> {
55    is_implicit_idempotency(binding).then(|| {
56        vec![
57            MigrationFile {
58                name: "0001_idempotency_claims.sql".to_string(),
59                sql: "CREATE TABLE idempotency_claims (\n  key TEXT PRIMARY KEY NOT NULL,\n  expires_at INTEGER NOT NULL\n);\n\nCREATE INDEX idempotency_claims_expires_at ON idempotency_claims (expires_at);\n".to_string(),
60            },
61            MigrationFile {
62                name: "0002_idempotency_values.sql".to_string(),
63                sql: "CREATE TABLE idempotency_values (\n  key TEXT PRIMARY KEY NOT NULL,\n  value TEXT NOT NULL,\n  expires_at INTEGER NOT NULL\n);\n\nCREATE INDEX idempotency_values_expires_at ON idempotency_values (expires_at);\n".to_string(),
64            },
65        ]
66    })
67}
68
69/// Whether `binding` is a Worker's implicit idempotency database: decided by
70/// its source, not its name, so a project's own `D1` capability named
71/// `Idempotency` (also bound as `D1_IDEMPOTENCY`) keeps its own migrations.
72pub fn is_implicit_idempotency(binding: &crate::worker_bindings::WorkerBinding) -> bool {
73    matches!(
74        &binding.source,
75        crate::worker_bindings::BindingSource::D1Database { capability }
76            if capability == crate::worker_bindings::IMPLICIT_IDEMPOTENCY_CAPABILITY
77    )
78}
79
80/// The migration files of database `database`, bound as `binding`: the
81/// project's own (`migrations/<database>/`), or the compiler's for an implicit
82/// database ([`implicit_migrations`]).
83pub fn migrations_of(
84    migrations: &D1Migrations,
85    database: &str,
86    binding: &crate::worker_bindings::WorkerBinding,
87) -> Vec<MigrationFile> {
88    implicit_migrations(binding)
89        .or_else(|| migrations.get(database).cloned())
90        .unwrap_or_default()
91}
92
93/// #3321: the key the opt-in `Postgres` test double's schema rides under in a
94/// [`D1Migrations`] on its way to the test emitters. Not a database name (those
95/// are `<worker>-<capability>`, never starting `@`), so it cannot collide with
96/// one, and nothing that looks a database up finds it. Present exactly when the
97/// project has `[test] postgres = "pglite"`; its one file is `schema.sql`, or
98/// none when the project has none.
99pub const PG_TEST_KEY: &str = "@postgres";
100
101/// Whether the project opts in to the PGlite `Postgres` test double (#3321).
102pub fn pglite_on(migrations: &D1Migrations) -> bool {
103    migrations.contains_key(PG_TEST_KEY)
104}
105
106/// The `Postgres` test double's database, as test emitters look it up: the
107/// project's `schema.sql` for a `Postgres` instance, the migrations of a `D1`
108/// database named `d1_database` otherwise (#3321, P4b #2608).
109pub fn double_files<'a>(
110    migrations: &'a D1Migrations,
111    cap: &str,
112    d1_database: Option<String>,
113) -> Option<&'a [MigrationFile]> {
114    let key = if cap == "Postgres" {
115        Some(PG_TEST_KEY.to_string())
116    } else {
117        d1_database
118    };
119    migrations.get(&key?).map(Vec::as_slice)
120}
121
122/// P4a (#2602): the account-facing name of a `D1` instance's database,
123/// `<worker>-<capability, kebab>`: `shop-cart` and `D1_ORDERS` give
124/// `shop-cart-orders`. D1 database names are scoped to the account, as R2
125/// bucket names are. `bynk deploy` environment-qualifies it.
126pub fn d1_database_name(worker: &str, binding: &str) -> String {
127    let prefix = format!("{}_", crate::firstparty::D1_BINDING_PREFIX);
128    let stem = binding.strip_prefix(&prefix).unwrap_or(binding);
129    format!("{worker}-{}", stem.to_ascii_lowercase().replace('_', "-"))
130}
131
132/// Whether `instance` (a context's derived capability) is a `D1` database.
133pub fn is_d1(instance: &crate::symbols::DerivedInstance) -> bool {
134    instance.base_unit == crate::firstparty::CLOUDFLARE_UNIT && instance.base_cap == "D1"
135}
136
137/// Every `D1` instance's database name, from each context's derived
138/// capabilities.
139pub fn declared_databases(
140    kinds: &BTreeMap<String, UnitKind>,
141    unit_tables: &HashMap<String, UnitTable>,
142    layout: &bynk_project::worker_layout::WorkerLayout,
143) -> Vec<String> {
144    let mut out = Vec::new();
145    for (unit, kind) in kinds {
146        if *kind != UnitKind::Context {
147            continue;
148        }
149        let Some(table) = unit_tables.get(unit) else {
150            continue;
151        };
152        let worker = layout.dir(unit);
153        for instance in table.derived.values().filter(|d| is_d1(d)) {
154            out.push(d1_database_name(&worker, &instance.binding));
155        }
156    }
157    out.sort();
158    out
159}
160
161/// The number of a well-formed migration file name, `NNNN_<name>.sql`: four
162/// ASCII digits, an underscore, then one or more letters, digits, `_` or `-`.
163/// Wrangler applies a directory's `.sql` files in name order, so the fixed
164/// width keeps that order numeric.
165pub fn migration_number(file: &str) -> Option<&str> {
166    let stem = file.strip_suffix(".sql")?;
167    let (number, name) = (stem.get(..4)?, stem.get(4..)?);
168    let name = name.strip_prefix('_')?;
169    (number.bytes().all(|b| b.is_ascii_digit())
170        && !name.is_empty()
171        && name
172            .bytes()
173            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-'))
174    .then_some(number)
175}
176
177fn file_error(errors: &mut ErrorSink, key: &str, code: &'static str, message: String, note: &str) {
178    errors.push_for(
179        Some(&PathBuf::from(key)),
180        CompileError::new(code, Span::default(), message).with_note(note.to_string()),
181    );
182}
183
184/// Check the listed `migrations/` folder against the declared databases, and
185/// read the files of each. `None` means no filesystem was consulted, so there
186/// is nothing to check or read.
187///
188/// - `bynk.d1.migration_name`: a file that isn't `migrations/<database>/NNNN_<name>.sql`,
189///   or a second file with the same number in one directory;
190/// - `bynk.d1.migration_unreadable`: a file that can't be read, or isn't UTF-8;
191/// - `bynk.d1.migrations_unused` (warning): a directory no `D1` instance's
192///   database name matches, usually a renamed capability.
193pub fn phase_d1_migrations(
194    folder: Option<&bynk_project::assets::AssetFolder>,
195    databases: &[String],
196    errors: &mut ErrorSink,
197) -> D1Migrations {
198    let mut out = D1Migrations::new();
199    let Some(folder) = folder else {
200        return out;
201    };
202    let mut warned: Vec<&str> = Vec::new();
203    let mut numbers: BTreeMap<(String, String), String> = BTreeMap::new();
204    for key in folder.files() {
205        if is_ignored(key) {
206            continue;
207        }
208        let parts: Vec<&str> = key.split('/').collect();
209        let [dir, database, file] = parts.as_slice() else {
210            file_error(
211                errors,
212                key,
213                "bynk.d1.migration_name",
214                format!("`{key}` isn't in a database's migrations directory"),
215                "a migration is `migrations/<database>/NNNN_<name>.sql`, directly in its database's directory",
216            );
217            continue;
218        };
219        debug_assert_eq!(*dir, PROJECT_MIGRATIONS_DIR);
220        if !databases.iter().any(|d| d == database) {
221            if !warned.contains(database) {
222                warned.push(database);
223                let known = if databases.is_empty() {
224                    "the project declares no `D1` instance".to_string()
225                } else {
226                    format!(
227                        "the declared databases are {}",
228                        databases
229                            .iter()
230                            .map(|d| format!("`{d}`"))
231                            .collect::<Vec<_>>()
232                            .join(", ")
233                    )
234                };
235                file_error(
236                    errors,
237                    &format!("{PROJECT_MIGRATIONS_DIR}/{database}"),
238                    "bynk.d1.migrations_unused",
239                    format!(
240                        "`{PROJECT_MIGRATIONS_DIR}/{database}/` matches no `D1` instance's database, so its migrations are never applied"
241                    ),
242                    &format!(
243                        "{known}; a database is `<worker>-<capability>`, and a renamed capability is a new, empty database"
244                    ),
245                );
246            }
247            continue;
248        }
249        let Some(number) = migration_number(file) else {
250            file_error(
251                errors,
252                key,
253                "bynk.d1.migration_name",
254                format!("migration `{key}` isn't named `NNNN_<name>.sql`"),
255                "four digits, an underscore, then letters, digits, `_` or `-`, as in `0001_create_orders.sql`",
256            );
257            continue;
258        };
259        if let Some(first) =
260            numbers.insert((database.to_string(), number.to_string()), file.to_string())
261        {
262            file_error(
263                errors,
264                key,
265                "bynk.d1.migration_name",
266                format!("migration `{key}` has the same number as `{first}`"),
267                "each migration of a database needs its own number, since they are applied in order",
268            );
269            continue;
270        }
271        let sql = match folder.read(key) {
272            Ok(bytes) => match String::from_utf8(bytes) {
273                Ok(sql) => sql,
274                Err(_) => {
275                    file_error(
276                        errors,
277                        key,
278                        "bynk.d1.migration_unreadable",
279                        format!("migration `{key}` isn't UTF-8 text"),
280                        "save the file as UTF-8",
281                    );
282                    continue;
283                }
284            },
285            Err(e) => {
286                file_error(
287                    errors,
288                    key,
289                    "bynk.d1.migration_unreadable",
290                    format!("migration `{key}` can't be read: {e}"),
291                    "a migration must be a regular file; symbolic links are not followed",
292                );
293                continue;
294            }
295        };
296        out.entry(database.to_string())
297            .or_default()
298            .push(MigrationFile {
299                name: file.to_string(),
300                sql,
301            });
302    }
303    for files in out.values_mut() {
304        files.sort_by(|a, b| a.name.cmp(&b.name));
305    }
306    out
307}
308
309#[cfg(test)]
310mod tests {
311    use super::*;
312
313    #[test]
314    fn a_migration_name_is_four_digits_an_underscore_and_a_name() {
315        assert_eq!(migration_number("0001_create_orders.sql"), Some("0001"));
316        assert_eq!(migration_number("0042_add-index.sql"), Some("0042"));
317        for bad in [
318            "1_init.sql",
319            "00001_init.sql",
320            "0001init.sql",
321            "0001_.sql",
322            "0001_init.SQL",
323            "0001_init.txt",
324            "0001_in it.sql",
325            "abcd_init.sql",
326            "README.md",
327        ] {
328            assert_eq!(migration_number(bad), None, "{bad}");
329        }
330    }
331
332    #[test]
333    fn hidden_files_and_editor_backups_are_ignored() {
334        for key in [
335            "migrations/shop-orders/.DS_Store",
336            "migrations/shop-orders/.0001_create.sql.swp",
337            "migrations/shop-orders/0001_create.sql~",
338            "migrations/.DS_Store",
339            "migrations/shop-orders/.archive/0001_old.sql",
340            "migrations/.trash/0001_create.sql",
341        ] {
342            assert!(is_ignored(key), "{key}");
343        }
344        assert!(!is_ignored("migrations/shop-orders/0001_create.sql"));
345        assert!(!is_ignored("migrations/README.md"));
346    }
347
348    /// Review of #2609: a listed entry whose read is refused (a symbolic
349    /// link, which `migrations_on_disk` lists unfollowed) is reported rather
350    /// than dropped, and nothing of that database's later files is lost.
351    #[test]
352    fn a_refused_read_is_reported_not_dropped() {
353        let files = [
354            "migrations/shop-orders/0001_init.sql",
355            "migrations/shop-orders/0002_linked.sql",
356            "migrations/shop-orders/.archive/0001_old.sql",
357        ]
358        .into_iter()
359        .map(String::from)
360        .collect();
361        let folder = bynk_project::assets::AssetFolder::new(
362            files,
363            std::sync::Arc::new(|key: &str| {
364                if key.ends_with("linked.sql") {
365                    Err(std::io::Error::new(
366                        std::io::ErrorKind::InvalidInput,
367                        "not a regular file",
368                    ))
369                } else {
370                    Ok(b"CREATE TABLE t (id INTEGER);".to_vec())
371                }
372            }),
373        );
374        let mut errors = ErrorSink::new();
375        let out = phase_d1_migrations(Some(&folder), &["shop-orders".to_string()], &mut errors);
376        let names: Vec<&str> = out["shop-orders"].iter().map(|f| f.name.as_str()).collect();
377        assert_eq!(names, ["0001_init.sql"]);
378        let all = errors.into_all();
379        let categories: Vec<&str> = all.iter().map(|e| e.error.category).collect();
380        assert_eq!(categories, ["bynk.d1.migration_unreadable"]);
381        assert!(
382            all[0].error.message.contains("0002_linked.sql"),
383            "{}",
384            all[0].error.message
385        );
386    }
387
388    #[test]
389    fn the_database_name_is_the_worker_and_the_capability_in_kebab_case() {
390        assert_eq!(
391            d1_database_name("shop-cart", "D1_ORDERS"),
392            "shop-cart-orders"
393        );
394        assert_eq!(
395            d1_database_name("shop", "D1_ORDER_LINES"),
396            "shop-order-lines"
397        );
398    }
399
400    /// W30 (#2840): the idempotency database is `<worker>-idempotency`, its
401    /// migration is the compiler's, and no other binding gets one.
402    #[test]
403    fn the_implicit_idempotency_database_is_named_and_migrated_by_the_compiler() {
404        assert_eq!(
405            d1_database_name("shop-hooks", IDEMPOTENCY_BINDING),
406            "shop-hooks-idempotency"
407        );
408        let files = implicit_migrations(&crate::worker_bindings::idempotency_binding())
409            .expect("the compiler owns it");
410        assert_eq!(files.len(), 2);
411        assert!(files[0].sql.contains("CREATE TABLE idempotency_claims"));
412        assert!(files[1].sql.contains("CREATE TABLE idempotency_values"));
413        // A project's own `capability Idempotency = D1` is bound as `D1_IDEMPOTENCY`
414        // too, but is not the implicit database: it keeps its own migrations.
415        let own = crate::worker_bindings::WorkerBinding {
416            name: IDEMPOTENCY_BINDING.to_string(),
417            source: crate::worker_bindings::BindingSource::D1Database {
418                capability: "Idempotency".to_string(),
419            },
420        };
421        assert!(implicit_migrations(&own).is_none());
422    }
423
424    /// A project's own database keeps its folder's files; the implicit one
425    /// ignores the folder.
426    #[test]
427    fn migrations_of_reads_the_folder_for_a_project_database_only() {
428        let mut folder = D1Migrations::new();
429        folder.insert(
430            "shop-orders".to_string(),
431            vec![MigrationFile {
432                name: "0001_a.sql".to_string(),
433                sql: "SELECT 1;".to_string(),
434            }],
435        );
436        let derived = |name: &str, capability: &str| crate::worker_bindings::WorkerBinding {
437            name: name.to_string(),
438            source: crate::worker_bindings::BindingSource::D1Database {
439                capability: capability.to_string(),
440            },
441        };
442        assert_eq!(
443            migrations_of(&folder, "shop-orders", &derived("D1_ORDERS", "Orders")).len(),
444            1
445        );
446        assert!(migrations_of(&folder, "shop-cart", &derived("D1_CART", "Cart")).is_empty());
447        assert_eq!(
448            migrations_of(
449                &folder,
450                "shop-idempotency",
451                &crate::worker_bindings::idempotency_binding()
452            )[0]
453            .name,
454            "0001_idempotency_claims.sql"
455        );
456        // The project's own database of the same name keeps its folder.
457        folder.insert(
458            "shop-idempotency".to_string(),
459            vec![MigrationFile {
460                name: "0001_mine.sql".to_string(),
461                sql: "SELECT 1;".to_string(),
462            }],
463        );
464        assert_eq!(
465            migrations_of(
466                &folder,
467                "shop-idempotency",
468                &derived(IDEMPOTENCY_BINDING, "Idempotency")
469            )[0]
470            .name,
471            "0001_mine.sql"
472        );
473    }
474}