steid

@jamesgill /

steid/src/infrastructure/database_compat_tests.rs
Rust28.2 KBCode·Blame·History·Raw
1//! The expand/deploy/contract rule, enforced, and the databases a binary must still
2//! boot against.
3//!
4//! The rule and its reasons are in `plans/architecture.md` ("Migrations"): a migration
5//! lands the instant a new build boots, while the previous build may still be serving
6//! from the same file, so no release may drop, rename or tighten what the previous one
7//! reads.
8//!
9//! What is here, and how much each part proves:
10//!
11//! - `no_migration_contracts_the_schema` is a **lexical guard**. It reads the real
12//! `migrations/` directory at test time, so a migration written after this file was
13//! is covered without anyone remembering to add it to a list. Being a grep, it is
14//! fooled by a table rebuilt through `create`/`insert`/`drop` — the prose rule and
15//! review cover that.
16//! - `a_shipped_migration_is_never_edited` pins the bytes of every released migration
17//! set (`RELEASES`), and `every_released_set_is_a_prefix_of_the_migrations_on_disk`
18//! pins their names and order. sqlx refuses to boot on an applied migration whose
19//! file has changed, so these are what keep an upgrade bootable.
20//! `the_version_in_cargo_toml_has_a_releases_row` makes the cut add its row, so the
21//! release being built is never the one left out.
22//! - `the_current_reads_work_against_the_last_released_schema` replays the 0.5.0
23//! migration set and runs today's repository reads against it. That is the *reverse*
24//! of the direction the rule is about. It is kept because it is separately true and
25//! separately needed — `steid backup` opens the pool without migrating (see
26//! `database::open`), so a new binary really does read an old schema.
27//! - `a_database_one_migration_ahead_still_boots` is the **in-process stand-in for the
28//! direction that broke**: *this* binary, started against a database that a newer
29//! release has migrated one step further, which is exactly what a rollback onto this
30//! version meets. It proves the migrator lets the binary start and read rather than
31//! refusing with `VersionMissing`. It does not prove that a real previous release
32//! reads a real newer schema: that needs the previous release's binary, which is not
33//! linked in, and release binaries are Linux. That check is not here — see
34//! `plans/current.md`. `an_edited_migration_is_still_refused` is its other half:
35//! ignoring the migrations it does not know must not loosen the check on the ones it
36//! does.
37
38use std::{fs, path::PathBuf};
39
40use sqlx::{AssertSqlSafe, SqlitePool, migrate::MigrateError};
41
42use super::{migrate, test_support::test_pool};
43
44use crate::domain::{
45 IssueNumber, IssueState, OrgId, OrgName, PullRequestState, PushEventId, RepoId, RepoName,
46 UserId, WebhookId,
47 repository::{
48 IssueRepository, LabelRepository, MembershipRepository, OrgRepository,
49 PullRequestRepository, PushEventRepository, RepoRepository, TokenRepository,
50 UserRepository, WebhookDeliveryRepository, WebhookRepository,
51 },
52};
53use crate::infrastructure::repository::{
54 SqliteIssueRepo, SqliteLabelRepo, SqliteMembershipRepo, SqliteOrgRepo, SqlitePullRequestRepo,
55 SqlitePushEventRepo, SqliteRepoRepo, SqliteTokenRepo, SqliteUserRepo,
56 SqliteWebhookDeliveryRepo, SqliteWebhookRepo,
57};
58
59/// The cumulative migration set 0.5.0 shipped, which 0.6.0 and 0.7.0 shipped unchanged.
60const RELEASED_0_5_0: &[&str] = &[
61 "20260804093030_create_orgs.sql",
62 "20260804093031_create_users.sql",
63 "20260804093032_create_memberships.sql",
64 "20260804093033_create_sessions.sql",
65 "20260804093034_add_org_bio.sql",
66 "20260804093035_create_repositories.sql",
67 "20260828120000_create_tokens.sql",
68 "20260829090000_add_repository_recency.sql",
69 "20260906120100_add_repository_import.sql",
70 "20260906120200_create_issues.sql",
71 "20260906120201_create_issue_comments.sql",
72 "20260906120300_create_push_events.sql",
73 "20260906120301_create_webhooks.sql",
74 "20260906120302_create_webhook_deliveries.sql",
75 "20260906120400_add_repository_archived.sql",
76 "20260906140100_add_token_lifecycle.sql",
77 "20260906140200_create_labels.sql",
78 "20260906140201_create_issue_labels.sql",
79 "20260906180100_create_pull_requests.sql",
80 "20260906180101_create_pull_request_comments.sql",
81 "20260906190000_create_pull_request_labels.sql",
82 "20260908090500_create_password_resets.sql",
83];
84
85/// The cumulative migration set 0.8.0 shipped: 0.5.0's, and `instance_settings`. 0.8.1
86/// and 0.8.2 ship it unchanged.
87const RELEASED_0_8_0: &[&str] = &[
88 "20260804093030_create_orgs.sql",
89 "20260804093031_create_users.sql",
90 "20260804093032_create_memberships.sql",
91 "20260804093033_create_sessions.sql",
92 "20260804093034_add_org_bio.sql",
93 "20260804093035_create_repositories.sql",
94 "20260828120000_create_tokens.sql",
95 "20260829090000_add_repository_recency.sql",
96 "20260906120100_add_repository_import.sql",
97 "20260906120200_create_issues.sql",
98 "20260906120201_create_issue_comments.sql",
99 "20260906120300_create_push_events.sql",
100 "20260906120301_create_webhooks.sql",
101 "20260906120302_create_webhook_deliveries.sql",
102 "20260906120400_add_repository_archived.sql",
103 "20260906140100_add_token_lifecycle.sql",
104 "20260906140200_create_labels.sql",
105 "20260906140201_create_issue_labels.sql",
106 "20260906180100_create_pull_requests.sql",
107 "20260906180101_create_pull_request_comments.sql",
108 "20260906190000_create_pull_request_labels.sql",
109 "20260908090500_create_password_resets.sql",
110 "20260927100000_create_instance_settings.sql",
111];
112
113/// A release, the cumulative migration set it shipped, and the SHA-256 over those
114/// files' bytes in order.
115struct Released {
116 version: &'static str,
117 migrations: &'static [&'static str],
118 digest: &'static str,
119}
120
121/// Every release since the digest was first pinned (0.5.0), oldest first.
122///
123/// This is the authoritative copy of what each release shipped — `plans/releases.md` is
124/// the human record and must agree with it. 0.5.0's set holds everything 0.4.0 and
125/// earlier shipped, so every migration that has ever shipped is pinned.
126///
127/// `sqlx::migrate!` checksums each file — comments included — and refuses to boot when
128/// an applied migration's file has changed. So a shipped migration is immutable down to
129/// its prose: a one-word comment edit in a shipped file (which happened between 0.4.0
130/// and 0.5.0, and was reverted) would have stopped every existing instance from
131/// booting the new binary.
132///
133/// **When a release is cut**, add its row in the cut commit: a new `RELEASED_…` list
134/// only if it shipped a migration, and the digest of that list at that commit.
135/// `the_version_in_cargo_toml_has_a_releases_row` fails until the row is there. A digest
136/// is never changed to make the test pass. Each one here was taken from git at the
137/// release's commit and, where the artefact is still on hand, checked against the
138/// migrations its binaries embed — `plans/releases.md`, "Which bytes each release
139/// shipped".
140const RELEASES: &[Released] = &[
141 Released {
142 version: "0.5.0",
143 migrations: RELEASED_0_5_0,
144 digest: "e94827d74e0e715897f5f66e2d7a9709860dfcdc7b1741db2e059fcf59612b4e",
145 },
146 // 0.6.0 and 0.7.0 shipped no migration, so their sets and digests are 0.5.0's.
147 Released {
148 version: "0.6.0",
149 migrations: RELEASED_0_5_0,
150 digest: "e94827d74e0e715897f5f66e2d7a9709860dfcdc7b1741db2e059fcf59612b4e",
151 },
152 Released {
153 version: "0.7.0",
154 migrations: RELEASED_0_5_0,
155 digest: "e94827d74e0e715897f5f66e2d7a9709860dfcdc7b1741db2e059fcf59612b4e",
156 },
157 Released {
158 version: "0.8.0",
159 migrations: RELEASED_0_8_0,
160 digest: "6761cb04105b31cb4890d937ab96de5d84f6e986b40b34b8be010e350de02e4c",
161 },
162 // 0.8.1 is the rollback fix and shipped no migration, so its set is 0.8.0's.
163 Released {
164 version: "0.8.1",
165 migrations: RELEASED_0_8_0,
166 digest: "6761cb04105b31cb4890d937ab96de5d84f6e986b40b34b8be010e350de02e4c",
167 },
168 // 0.8.2 is launch phase 2's Steid fixes and ships no migration either.
169 Released {
170 version: "0.8.2",
171 migrations: RELEASED_0_8_0,
172 digest: "6761cb04105b31cb4890d937ab96de5d84f6e986b40b34b8be010e350de02e4c",
173 },
174];
175
176#[test]
177fn a_shipped_migration_is_never_edited() {
178 use sha2::{Digest, Sha256};
179
180 for release in RELEASES {
181 let mut hasher = Sha256::new();
182 for name in release.migrations {
183 hasher.update(fs::read(migrations_dir().join(name)).expect("a released migration"));
184 }
185 let digest = format!("{:x}", hasher.finalize());
186 assert_eq!(
187 digest, release.digest,
188 "a migration that shipped in {} has been edited; sqlx would refuse to boot on \
189 every instance that applied it. Revert the edit — a new migration is the only \
190 way to change a shipped schema.",
191 release.version
192 );
193 }
194}
195
196/// The version `Cargo.toml` names has a `RELEASES` row.
197///
198/// The digest and prefix tests check only the rows that exist, so a cut that adds no row
199/// leaves its release unpinned and every test still green. That is how 0.8.0 shipped: an
200/// edit to `instance_settings` would have passed until 0.8.1's step added the pin after
201/// the fact. With this, the version bump and the row are one commit.
202#[test]
203fn the_version_in_cargo_toml_has_a_releases_row() {
204 let version = env!("CARGO_PKG_VERSION");
205 assert!(
206 RELEASES.iter().any(|release| release.version == version),
207 "Cargo.toml says {version} and RELEASES has no row for it. Add the row in the same \
208 commit as the version bump: {version}'s cumulative migration set (the previous \
209 release's list if it ships no migration, a new RELEASED_… with the full list if it \
210 does) and the SHA-256 of that set at this commit — see plans/releases.md. An \
211 unpinned release is one whose migrations can be edited after shipping without a \
212 test noticing."
213 );
214}
215
216/// Migrations written before the rule existed and grandfathered past the guard.
217///
218/// Empty, and it should stay that way: every migration to date already complies, so the
219/// baseline is the beginning of history rather than a line drawn to make a test pass. An
220/// entry here is a promise that a released instance survived it, not a way to land a
221/// contracting migration.
222const GRANDFATHERED: &[&str] = &[];
223
224fn migrations_dir() -> PathBuf {
225 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("migrations")
226}
227
228/// Every `*.sql` in `migrations/`, in the order sqlx would apply them.
229fn migration_files() -> Vec<(String, String)> {
230 let mut files: Vec<_> = fs::read_dir(migrations_dir())
231 .expect("migrations/ should be readable")
232 .map(|entry| entry.expect("a directory entry").path())
233 .filter(|path| path.extension().is_some_and(|ext| ext == "sql"))
234 .map(|path| {
235 let name = path
236 .file_name()
237 .expect("a file name")
238 .to_string_lossy()
239 .into_owned();
240 let body = fs::read_to_string(&path).expect("a migration should be readable");
241 (name, body)
242 })
243 .collect();
244
245 // The timestamp prefix is fixed-width, so lexical order is application order — the
246 // same thing sqlx does with the version it parses out of the name.
247 files.sort_by(|(a, _), (b, _)| a.cmp(b));
248 files
249}
250
251/// A migration with its `--` comments removed, and nothing else touched.
252///
253/// Comments have to go before anything else looks at the SQL: every migration in this
254/// tree opens with several paragraphs explaining itself, and half of them use the word
255/// "drop" while doing nothing of the kind. Matching on the prose would make the guard
256/// unusable within a week — `prose_about_dropping_things_is_not_a_dropped_column` is
257/// the test of that.
258fn without_comments(body: &str) -> String {
259 let mut out = String::with_capacity(body.len());
260 let mut chars = body.chars().peekable();
261 let mut in_string = false;
262
263 while let Some(c) = chars.next() {
264 if in_string {
265 out.push(c);
266 if c == '\'' {
267 in_string = false;
268 }
269 continue;
270 }
271 match c {
272 '\'' => {
273 in_string = true;
274 out.push(c);
275 }
276 '-' if chars.peek() == Some(&'-') => {
277 for skipped in chars.by_ref() {
278 if skipped == '\n' {
279 break;
280 }
281 }
282 out.push(' ');
283 }
284 _ => out.push(c),
285 }
286 }
287
288 out
289}
290
291/// A migration reduced to what the guard reads: no comments, no string literals,
292/// lowercase, whitespace collapsed.
293///
294/// String literals go too, so a migration that inserts the text "drop column" into a
295/// row is not mistaken for one that runs it. Collapsing whitespace is what lets
296/// `drop\n column` be found by searching for a phrase rather than a regex.
297fn statements_only(body: &str) -> String {
298 let mut out = String::with_capacity(body.len());
299 let stripped = without_comments(body);
300 let mut in_string = false;
301
302 for c in stripped.chars() {
303 if in_string {
304 if c == '\'' {
305 in_string = false;
306 }
307 continue;
308 }
309 if c == '\'' {
310 in_string = true;
311 } else {
312 out.push(c.to_ascii_lowercase());
313 }
314 }
315
316 out.split_whitespace().collect::<Vec<_>>().join(" ")
317}
318
319#[test]
320fn no_migration_contracts_the_schema() {
321 for (name, body) in migration_files() {
322 if GRANDFATHERED.contains(&name.as_str()) {
323 continue;
324 }
325 let sql = statements_only(&body);
326
327 for forbidden in ["drop column", "drop table", "rename to", "rename column"] {
328 assert!(
329 !sql.contains(forbidden),
330 "{name} contains `{forbidden}`, which the previous release's binary \
331 cannot survive. Contracting waits a release — see plans/architecture.md."
332 );
333 }
334
335 // `add column … not null` needs a `default`, and the check has to be per
336 // statement: a migration adding three columns must not be excused because one
337 // of the others carries a default.
338 for statement in sql.split(';') {
339 let statement = statement.trim();
340 if !statement.contains("add column") || !statement.contains("not null") {
341 continue;
342 }
343 assert!(
344 statement.contains("default"),
345 "{name} adds a `not null` column without a `default`:\n {statement}\n\
346 SQLite refuses that on a non-empty table, and the previous release's \
347 inserts would omit the column. Give it a default — see \
348 plans/architecture.md."
349 );
350 }
351 }
352}
353
354#[test]
355fn every_released_set_is_a_prefix_of_the_migrations_on_disk() {
356 let on_disk: Vec<String> = migration_files()
357 .into_iter()
358 .map(|(name, _)| name)
359 .collect();
360
361 for release in RELEASES {
362 let shipped = release.migrations;
363 assert!(
364 on_disk.len() >= shipped.len(),
365 "there are fewer migrations on disk than {} shipped — one has been deleted",
366 release.version
367 );
368 assert_eq!(
369 &on_disk[..shipped.len()],
370 shipped,
371 "{}'s set no longer matches the start of migrations/. Either a name is \
372 mistyped, or a new migration has been back-dated in front of a released one — \
373 which would make it run on an instance that has already recorded a later \
374 version. See plans/releases.md.",
375 release.version
376 );
377 }
378}
379
380/// Applies exactly the 0.5.0 set to a fresh database, without sqlx's migrator.
381///
382/// The migrator refuses to stop part-way, and the point is to stand at an older
383/// version, so the files are applied by hand — statement by statement, split on `;`,
384/// which every migration in this tree is written to tolerate (the same split the
385/// repository column-migration test uses).
386async fn pool_at_release_0_5_0() -> SqlitePool {
387 let pool = SqlitePool::connect("sqlite::memory:")
388 .await
389 .expect("in-memory database should open");
390
391 let dir = migrations_dir();
392 for name in RELEASED_0_5_0 {
393 let body = fs::read_to_string(dir.join(name)).expect("a released migration should exist");
394 let sql = without_comments(&body);
395 for statement in sql
396 .split(';')
397 .filter(|statement| !statement.trim().is_empty())
398 {
399 // `AssertSqlSafe` because the string is read from this repository's own
400 // `migrations/` at test time, not from anything a user can reach.
401 sqlx::query(AssertSqlSafe(statement.to_owned()))
402 .execute(&pool)
403 .await
404 .unwrap_or_else(|error| panic!("{name} should apply: {error}\n {statement}"));
405 }
406 }
407
408 pool
409}
410
411/// Today's reads, against the schema 0.5.0 left behind.
412///
413/// One read per table the released schema has — a `find`, a `list` or a `count`, so a
414/// column added since and selected by name would fail here. The reads are run for their
415/// errors, not their answers: the database is empty, and what is being proved is that
416/// every query still *compiles against the old columns*.
417///
418/// Not yet true of two tables. `password_resets` arrived in 0.5.0 and has no read here.
419/// `instance_settings` arrived in 0.8.0, so it does not exist at this schema, and 0.5.0
420/// is no longer the last released one: moving the baseline to 0.8.0, with both reads, is
421/// open in `plans/current.md`.
422#[tokio::test]
423async fn the_current_reads_work_against_the_last_released_schema() {
424 let pool = pool_at_release_0_5_0().await;
425
426 let org_id = OrgId::from_trusted("o1");
427 let user_id = UserId::from_trusted("u1");
428 let repo_id = RepoId::from_trusted("r1");
429
430 // orgs, users, memberships, sessions
431 let orgs = SqliteOrgRepo::new(pool.clone());
432 orgs.find_by_id(&org_id).await.expect("orgs.find_by_id");
433 orgs.find_by_name(&OrgName::new("james").expect("valid name"))
434 .await
435 .expect("orgs.find_by_name");
436 assert_eq!(orgs.count().await.expect("orgs.count"), 0);
437
438 let users = SqliteUserRepo::new(pool.clone());
439 users.find_by_id(&user_id).await.expect("users.find_by_id");
440 users
441 .find_by_personal_org(&org_id)
442 .await
443 .expect("users.find_by_personal_org");
444 assert_eq!(users.count().await.expect("users.count"), 0);
445 assert!(!users.any_exist().await.expect("users.any_exist"));
446 assert!(users.sole_user().await.expect("users.sole_user").is_none());
447
448 let memberships = SqliteMembershipRepo::new(pool.clone());
449 memberships
450 .find(&org_id, &user_id)
451 .await
452 .expect("memberships.find");
453 memberships
454 .list_for_user(&user_id)
455 .await
456 .expect("memberships.list_for_user");
457
458 // Sessions are read through a `SessionTokenHash`, which is built by hashing rather
459 // than from a string, so the useful read here is the sweep: it touches the same
460 // columns and needs no value the domain will not hand out.
461 crate::domain::repository::SessionRepository::delete_expired(
462 &crate::infrastructure::repository::SqliteSessionRepo::new(pool.clone()),
463 std::time::SystemTime::UNIX_EPOCH,
464 )
465 .await
466 .expect("sessions.delete_expired");
467
468 // repositories, including the three columns 0.4.0 added
469 let repos = SqliteRepoRepo::new(pool.clone());
470 repos.find_by_id(&repo_id).await.expect("repos.find_by_id");
471 repos
472 .find_by_org_and_name(&org_id, &RepoName::new("steid").expect("valid name"))
473 .await
474 .expect("repos.find_by_org_and_name");
475 repos.list_by_org(&org_id).await.expect("repos.list_by_org");
476 assert_eq!(repos.count().await.expect("repos.count"), 0);
477
478 // tokens, with the lifecycle columns 0.4.0 added
479 let tokens = SqliteTokenRepo::new(pool.clone());
480 tokens
481 .list_by_user(&user_id)
482 .await
483 .expect("tokens.list_by_user");
484
485 // issues and issue comments
486 let issues = SqliteIssueRepo::new(pool.clone());
487 issues
488 .find_by_number(&repo_id, IssueNumber::new(1).expect("valid number"))
489 .await
490 .expect("issues.find_by_number");
491 issues
492 .list_by_repo(&repo_id, IssueState::Open, 0, 10)
493 .await
494 .expect("issues.list_by_repo");
495 issues.counts(&repo_id).await.expect("issues.counts");
496 issues
497 .comment_counts(&repo_id)
498 .await
499 .expect("issues.comment_counts");
500
501 // pull requests and their comments
502 let pulls = SqlitePullRequestRepo::new(pool.clone());
503 pulls
504 .find_by_number(&repo_id, IssueNumber::new(1).expect("valid number"))
505 .await
506 .expect("pulls.find_by_number");
507 pulls
508 .list_by_repo(&repo_id, PullRequestState::Open, 0, 10)
509 .await
510 .expect("pulls.list_by_repo");
511 pulls.counts(&repo_id).await.expect("pulls.counts");
512 pulls
513 .comment_counts(&repo_id)
514 .await
515 .expect("pulls.comment_counts");
516
517 // push events
518 let pushes = SqlitePushEventRepo::new(pool.clone());
519 pushes
520 .find(&PushEventId::from_trusted("p1"))
521 .await
522 .expect("pushes.find");
523 pushes
524 .list_by_repo(&repo_id, 10)
525 .await
526 .expect("pushes.list_by_repo");
527 pushes
528 .list_recent(std::slice::from_ref(&repo_id), 10)
529 .await
530 .expect("pushes.list_recent");
531
532 // webhooks and deliveries
533 let webhook_id = WebhookId::from_trusted("w1");
534 let webhooks = SqliteWebhookRepo::new(pool.clone());
535 webhooks.find(&webhook_id).await.expect("webhooks.find");
536 webhooks
537 .list_by_repo(&repo_id)
538 .await
539 .expect("webhooks.list_by_repo");
540
541 let deliveries = SqliteWebhookDeliveryRepo::new(pool.clone());
542 deliveries
543 .list_by_webhook(&webhook_id, 0, 10)
544 .await
545 .expect("deliveries.list_by_webhook");
546 assert_eq!(
547 deliveries
548 .count_by_webhook(&webhook_id)
549 .await
550 .expect("deliveries.count_by_webhook"),
551 0
552 );
553 deliveries
554 .latest_by_webhook(&webhook_id)
555 .await
556 .expect("deliveries.latest_by_webhook");
557
558 // labels, issue_labels, pull_request_labels
559 let labels = SqliteLabelRepo::new(pool.clone());
560 labels
561 .list_by_repo(&repo_id)
562 .await
563 .expect("labels.list_by_repo");
564 labels
565 .find_by_name(&repo_id, "bug")
566 .await
567 .expect("labels.find_by_name");
568 labels
569 .labels_for_repo(&repo_id)
570 .await
571 .expect("labels.labels_for_repo");
572 labels
573 .labels_for_repo_pulls(&repo_id)
574 .await
575 .expect("labels.labels_for_repo_pulls");
576 labels
577 .issue_counts(&repo_id)
578 .await
579 .expect("labels.issue_counts");
580 labels
581 .pull_counts(&repo_id)
582 .await
583 .expect("labels.pull_counts");
584}
585
586/// The newest migration this binary carries, read back from a database it has just
587/// migrated.
588async fn newest_applied(pool: &SqlitePool) -> i64 {
589 sqlx::query_scalar("select max(version) from _sqlx_migrations")
590 .fetch_one(pool)
591 .await
592 .expect("a migrated database records its migrations")
593}
594
595/// What a rollback onto this binary meets: a database a newer release has migrated.
596///
597/// The newer release leaves two things behind. Its migration's effect — an added column,
598/// because expand-only means it could only have added — and its migrator's record of
599/// it: a `_sqlx_migrations` row for a version past anything embedded here, applied
600/// successfully. This binary must boot against that, leave the record alone, and still
601/// read its own tables.
602#[tokio::test]
603async fn a_database_one_migration_ahead_still_boots() {
604 let pool = test_pool().await;
605 let ahead = newest_applied(&pool).await + 1;
606
607 sqlx::query("alter table users add column from_a_newer_release text")
608 .execute(&pool)
609 .await
610 .expect("the newer release's migration");
611 sqlx::query(
612 "insert into _sqlx_migrations (version, description, success, checksum, execution_time)
613 values (?, 'from a newer release', 1, ?, 0)",
614 )
615 .bind(ahead)
616 .bind(vec![0_u8; 48])
617 .execute(&pool)
618 .await
619 .expect("the newer release's record of it");
620
621 // sqlx's default refuses exactly this database, so it is the one a rollback could
622 // not boot against before `migrate` said otherwise — not one that never failed.
623 let refused = sqlx::migrate!("./migrations")
624 .run(&pool)
625 .await
626 .expect_err("sqlx's default refuses an applied migration it does not know");
627 assert!(
628 matches!(refused, MigrateError::VersionMissing(version) if version == ahead),
629 "expected VersionMissing({ahead}), got {refused}"
630 );
631
632 migrate(&pool)
633 .await
634 .expect("a binary one migration behind its database still boots");
635
636 let kept: i64 = sqlx::query_scalar("select count(*) from _sqlx_migrations where version = ?")
637 .bind(ahead)
638 .fetch_one(&pool)
639 .await
640 .expect("query");
641 assert_eq!(
642 kept, 1,
643 "the newer release's record of its migration is gone"
644 );
645
646 // And it serves: a read of the very table the newer release widened.
647 let users = SqliteUserRepo::new(pool.clone());
648 assert_eq!(users.count().await.expect("users.count"), 0);
649}
650
651/// Ignoring the migrations it does not know must not loosen the check on the ones it
652/// does: a shipped migration whose stored checksum disagrees with the embedded file is
653/// still refused.
654#[tokio::test]
655async fn an_edited_migration_is_still_refused() {
656 let pool = test_pool().await;
657 let edited = newest_applied(&pool).await;
658
659 sqlx::query("update _sqlx_migrations set checksum = ? where version = ?")
660 .bind(vec![0_u8; 48])
661 .bind(edited)
662 .execute(&pool)
663 .await
664 .expect("a checksum that is not the embedded file's");
665
666 let error = migrate(&pool)
667 .await
668 .expect_err("a known migration whose file has changed is refused");
669 match error {
670 sqlx::Error::Migrate(error) => assert!(
671 matches!(*error, MigrateError::VersionMismatch(version) if version == edited),
672 "expected VersionMismatch({edited}), got {error}"
673 ),
674 other => panic!("expected VersionMismatch({edited}), got {other}"),
675 }
676}
677
678#[test]
679fn the_guard_catches_a_contracting_migration() {
680 // The guard's own test: the four statements it exists to refuse, in the shape a
681 // real migration would write them, checked without touching migrations/. Without
682 // this, a guard that silently stopped matching would still pass every run.
683 for contracting in [
684 "alter table repositories drop column description;",
685 "drop table webhooks;",
686 "alter table orgs rename to organisations;",
687 "alter table users rename column email to address;",
688 ] {
689 let sql = statements_only(contracting);
690 assert!(
691 ["drop column", "drop table", "rename to", "rename column"]
692 .iter()
693 .any(|forbidden| sql.contains(forbidden)),
694 "the guard no longer recognises `{contracting}`"
695 );
696 }
697
698 let tightening = statements_only("alter table repositories add column stars integer not null;");
699 assert!(tightening.contains("add column") && tightening.contains("not null"));
700 assert!(
701 !tightening.contains("default"),
702 "the guard no longer recognises a `not null` column with no default"
703 );
704}
705
706#[test]
707fn prose_about_dropping_things_is_not_a_dropped_column() {
708 // Every migration here opens with paragraphs of reasoning, and they talk about
709 // dropping and renaming constantly. A guard that read the comments would have to be
710 // switched off within a week.
711 let sql = statements_only(
712 "-- We could DROP COLUMN `bio` here, or RENAME TO something else, but\n\
713 -- contracting waits a release. See architecture.md.\n\
714 alter table orgs add column tagline text;\n",
715 );
716
717 assert_eq!(sql, "alter table orgs add column tagline text;");
718
719 // And a literal is not a statement either.
720 let sql = statements_only("insert into notes (body) values ('drop table orgs');");
721 assert_eq!(sql, "insert into notes (body) values ();");
722}