1use 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#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct MigrationFile {
26 pub name: String,
27 pub sql: String,
28}
29
30pub fn is_ignored(key: &str) -> bool {
35 key.split('/').any(|part| part.starts_with('.')) || key.ends_with('~')
36}
37
38pub type D1Migrations = BTreeMap<String, Vec<MigrationFile>>;
41
42pub const IDEMPOTENCY_BINDING: &str = "D1_IDEMPOTENCY";
47
48pub 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
69pub 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
80pub 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
93pub const PG_TEST_KEY: &str = "@postgres";
100
101pub fn pglite_on(migrations: &D1Migrations) -> bool {
103 migrations.contains_key(PG_TEST_KEY)
104}
105
106pub 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
122pub 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
132pub fn is_d1(instance: &crate::symbols::DerivedInstance) -> bool {
134 instance.base_unit == crate::firstparty::CLOUDFLARE_UNIT && instance.base_cap == "D1"
135}
136
137pub 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
161pub 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
184pub 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 #[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 #[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 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 #[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 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}