steid

@jamesgill /

steid/src/infrastructure/database_compat_tests.rs
Rust27.9 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/// ships 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];
169
170#[test]
171fn a_shipped_migration_is_never_edited() {
172 use sha2::{Digest, Sha256};
173
174 for release in RELEASES {
175 let mut hasher = Sha256::new();
176 for name in release.migrations {
177 hasher.update(fs::read(migrations_dir().join(name)).expect("a released migration"));
178 }
179 let digest = format!("{:x}", hasher.finalize());
180 assert_eq!(
181 digest, release.digest,
182 "a migration that shipped in {} has been edited; sqlx would refuse to boot on \
183 every instance that applied it. Revert the edit — a new migration is the only \
184 way to change a shipped schema.",
185 release.version
186 );
187 }
188}
189
190/// The version `Cargo.toml` names has a `RELEASES` row.
191///
192/// The digest and prefix tests check only the rows that exist, so a cut that adds no row
193/// leaves its release unpinned and every test still green. That is how 0.8.0 shipped: an
194/// edit to `instance_settings` would have passed until 0.8.1's step added the pin after
195/// the fact. With this, the version bump and the row are one commit.
196#[test]
197fn the_version_in_cargo_toml_has_a_releases_row() {
198 let version = env!("CARGO_PKG_VERSION");
199 assert!(
200 RELEASES.iter().any(|release| release.version == version),
201 "Cargo.toml says {version} and RELEASES has no row for it. Add the row in the same \
202 commit as the version bump: {version}'s cumulative migration set (the previous \
203 release's list if it ships no migration, a new RELEASED_… with the full list if it \
204 does) and the SHA-256 of that set at this commit — see plans/releases.md. An \
205 unpinned release is one whose migrations can be edited after shipping without a \
206 test noticing."
207 );
208}
209
210/// Migrations written before the rule existed and grandfathered past the guard.
211///
212/// Empty, and it should stay that way: every migration to date already complies, so the
213/// baseline is the beginning of history rather than a line drawn to make a test pass. An
214/// entry here is a promise that a released instance survived it, not a way to land a
215/// contracting migration.
216const GRANDFATHERED: &[&str] = &[];
217
218fn migrations_dir() -> PathBuf {
219 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("migrations")
220}
221
222/// Every `*.sql` in `migrations/`, in the order sqlx would apply them.
223fn migration_files() -> Vec<(String, String)> {
224 let mut files: Vec<_> = fs::read_dir(migrations_dir())
225 .expect("migrations/ should be readable")
226 .map(|entry| entry.expect("a directory entry").path())
227 .filter(|path| path.extension().is_some_and(|ext| ext == "sql"))
228 .map(|path| {
229 let name = path
230 .file_name()
231 .expect("a file name")
232 .to_string_lossy()
233 .into_owned();
234 let body = fs::read_to_string(&path).expect("a migration should be readable");
235 (name, body)
236 })
237 .collect();
238
239 // The timestamp prefix is fixed-width, so lexical order is application order — the
240 // same thing sqlx does with the version it parses out of the name.
241 files.sort_by(|(a, _), (b, _)| a.cmp(b));
242 files
243}
244
245/// A migration with its `--` comments removed, and nothing else touched.
246///
247/// Comments have to go before anything else looks at the SQL: every migration in this
248/// tree opens with several paragraphs explaining itself, and half of them use the word
249/// "drop" while doing nothing of the kind. Matching on the prose would make the guard
250/// unusable within a week — `prose_about_dropping_things_is_not_a_dropped_column` is
251/// the test of that.
252fn without_comments(body: &str) -> String {
253 let mut out = String::with_capacity(body.len());
254 let mut chars = body.chars().peekable();
255 let mut in_string = false;
256
257 while let Some(c) = chars.next() {
258 if in_string {
259 out.push(c);
260 if c == '\'' {
261 in_string = false;
262 }
263 continue;
264 }
265 match c {
266 '\'' => {
267 in_string = true;
268 out.push(c);
269 }
270 '-' if chars.peek() == Some(&'-') => {
271 for skipped in chars.by_ref() {
272 if skipped == '\n' {
273 break;
274 }
275 }
276 out.push(' ');
277 }
278 _ => out.push(c),
279 }
280 }
281
282 out
283}
284
285/// A migration reduced to what the guard reads: no comments, no string literals,
286/// lowercase, whitespace collapsed.
287///
288/// String literals go too, so a migration that inserts the text "drop column" into a
289/// row is not mistaken for one that runs it. Collapsing whitespace is what lets
290/// `drop\n column` be found by searching for a phrase rather than a regex.
291fn statements_only(body: &str) -> String {
292 let mut out = String::with_capacity(body.len());
293 let stripped = without_comments(body);
294 let mut in_string = false;
295
296 for c in stripped.chars() {
297 if in_string {
298 if c == '\'' {
299 in_string = false;
300 }
301 continue;
302 }
303 if c == '\'' {
304 in_string = true;
305 } else {
306 out.push(c.to_ascii_lowercase());
307 }
308 }
309
310 out.split_whitespace().collect::<Vec<_>>().join(" ")
311}
312
313#[test]
314fn no_migration_contracts_the_schema() {
315 for (name, body) in migration_files() {
316 if GRANDFATHERED.contains(&name.as_str()) {
317 continue;
318 }
319 let sql = statements_only(&body);
320
321 for forbidden in ["drop column", "drop table", "rename to", "rename column"] {
322 assert!(
323 !sql.contains(forbidden),
324 "{name} contains `{forbidden}`, which the previous release's binary \
325 cannot survive. Contracting waits a release — see plans/architecture.md."
326 );
327 }
328
329 // `add column … not null` needs a `default`, and the check has to be per
330 // statement: a migration adding three columns must not be excused because one
331 // of the others carries a default.
332 for statement in sql.split(';') {
333 let statement = statement.trim();
334 if !statement.contains("add column") || !statement.contains("not null") {
335 continue;
336 }
337 assert!(
338 statement.contains("default"),
339 "{name} adds a `not null` column without a `default`:\n {statement}\n\
340 SQLite refuses that on a non-empty table, and the previous release's \
341 inserts would omit the column. Give it a default — see \
342 plans/architecture.md."
343 );
344 }
345 }
346}
347
348#[test]
349fn every_released_set_is_a_prefix_of_the_migrations_on_disk() {
350 let on_disk: Vec<String> = migration_files()
351 .into_iter()
352 .map(|(name, _)| name)
353 .collect();
354
355 for release in RELEASES {
356 let shipped = release.migrations;
357 assert!(
358 on_disk.len() >= shipped.len(),
359 "there are fewer migrations on disk than {} shipped — one has been deleted",
360 release.version
361 );
362 assert_eq!(
363 &on_disk[..shipped.len()],
364 shipped,
365 "{}'s set no longer matches the start of migrations/. Either a name is \
366 mistyped, or a new migration has been back-dated in front of a released one — \
367 which would make it run on an instance that has already recorded a later \
368 version. See plans/releases.md.",
369 release.version
370 );
371 }
372}
373
374/// Applies exactly the 0.5.0 set to a fresh database, without sqlx's migrator.
375///
376/// The migrator refuses to stop part-way, and the point is to stand at an older
377/// version, so the files are applied by hand — statement by statement, split on `;`,
378/// which every migration in this tree is written to tolerate (the same split the
379/// repository column-migration test uses).
380async fn pool_at_release_0_5_0() -> SqlitePool {
381 let pool = SqlitePool::connect("sqlite::memory:")
382 .await
383 .expect("in-memory database should open");
384
385 let dir = migrations_dir();
386 for name in RELEASED_0_5_0 {
387 let body = fs::read_to_string(dir.join(name)).expect("a released migration should exist");
388 let sql = without_comments(&body);
389 for statement in sql
390 .split(';')
391 .filter(|statement| !statement.trim().is_empty())
392 {
393 // `AssertSqlSafe` because the string is read from this repository's own
394 // `migrations/` at test time, not from anything a user can reach.
395 sqlx::query(AssertSqlSafe(statement.to_owned()))
396 .execute(&pool)
397 .await
398 .unwrap_or_else(|error| panic!("{name} should apply: {error}\n {statement}"));
399 }
400 }
401
402 pool
403}
404
405/// Today's reads, against the schema 0.5.0 left behind.
406///
407/// One read per table the released schema has — a `find`, a `list` or a `count`, so a
408/// column added since and selected by name would fail here. The reads are run for their
409/// errors, not their answers: the database is empty, and what is being proved is that
410/// every query still *compiles against the old columns*.
411///
412/// Not yet true of two tables. `password_resets` arrived in 0.5.0 and has no read here.
413/// `instance_settings` arrived in 0.8.0, so it does not exist at this schema, and 0.5.0
414/// is no longer the last released one: moving the baseline to 0.8.0, with both reads, is
415/// open in `plans/current.md`.
416#[tokio::test]
417async fn the_current_reads_work_against_the_last_released_schema() {
418 let pool = pool_at_release_0_5_0().await;
419
420 let org_id = OrgId::from_trusted("o1");
421 let user_id = UserId::from_trusted("u1");
422 let repo_id = RepoId::from_trusted("r1");
423
424 // orgs, users, memberships, sessions
425 let orgs = SqliteOrgRepo::new(pool.clone());
426 orgs.find_by_id(&org_id).await.expect("orgs.find_by_id");
427 orgs.find_by_name(&OrgName::new("james").expect("valid name"))
428 .await
429 .expect("orgs.find_by_name");
430 assert_eq!(orgs.count().await.expect("orgs.count"), 0);
431
432 let users = SqliteUserRepo::new(pool.clone());
433 users.find_by_id(&user_id).await.expect("users.find_by_id");
434 users
435 .find_by_personal_org(&org_id)
436 .await
437 .expect("users.find_by_personal_org");
438 assert_eq!(users.count().await.expect("users.count"), 0);
439 assert!(!users.any_exist().await.expect("users.any_exist"));
440 assert!(users.sole_user().await.expect("users.sole_user").is_none());
441
442 let memberships = SqliteMembershipRepo::new(pool.clone());
443 memberships
444 .find(&org_id, &user_id)
445 .await
446 .expect("memberships.find");
447 memberships
448 .list_for_user(&user_id)
449 .await
450 .expect("memberships.list_for_user");
451
452 // Sessions are read through a `SessionTokenHash`, which is built by hashing rather
453 // than from a string, so the useful read here is the sweep: it touches the same
454 // columns and needs no value the domain will not hand out.
455 crate::domain::repository::SessionRepository::delete_expired(
456 &crate::infrastructure::repository::SqliteSessionRepo::new(pool.clone()),
457 std::time::SystemTime::UNIX_EPOCH,
458 )
459 .await
460 .expect("sessions.delete_expired");
461
462 // repositories, including the three columns 0.4.0 added
463 let repos = SqliteRepoRepo::new(pool.clone());
464 repos.find_by_id(&repo_id).await.expect("repos.find_by_id");
465 repos
466 .find_by_org_and_name(&org_id, &RepoName::new("steid").expect("valid name"))
467 .await
468 .expect("repos.find_by_org_and_name");
469 repos.list_by_org(&org_id).await.expect("repos.list_by_org");
470 assert_eq!(repos.count().await.expect("repos.count"), 0);
471
472 // tokens, with the lifecycle columns 0.4.0 added
473 let tokens = SqliteTokenRepo::new(pool.clone());
474 tokens
475 .list_by_user(&user_id)
476 .await
477 .expect("tokens.list_by_user");
478
479 // issues and issue comments
480 let issues = SqliteIssueRepo::new(pool.clone());
481 issues
482 .find_by_number(&repo_id, IssueNumber::new(1).expect("valid number"))
483 .await
484 .expect("issues.find_by_number");
485 issues
486 .list_by_repo(&repo_id, IssueState::Open, 0, 10)
487 .await
488 .expect("issues.list_by_repo");
489 issues.counts(&repo_id).await.expect("issues.counts");
490 issues
491 .comment_counts(&repo_id)
492 .await
493 .expect("issues.comment_counts");
494
495 // pull requests and their comments
496 let pulls = SqlitePullRequestRepo::new(pool.clone());
497 pulls
498 .find_by_number(&repo_id, IssueNumber::new(1).expect("valid number"))
499 .await
500 .expect("pulls.find_by_number");
501 pulls
502 .list_by_repo(&repo_id, PullRequestState::Open, 0, 10)
503 .await
504 .expect("pulls.list_by_repo");
505 pulls.counts(&repo_id).await.expect("pulls.counts");
506 pulls
507 .comment_counts(&repo_id)
508 .await
509 .expect("pulls.comment_counts");
510
511 // push events
512 let pushes = SqlitePushEventRepo::new(pool.clone());
513 pushes
514 .find(&PushEventId::from_trusted("p1"))
515 .await
516 .expect("pushes.find");
517 pushes
518 .list_by_repo(&repo_id, 10)
519 .await
520 .expect("pushes.list_by_repo");
521 pushes
522 .list_recent(std::slice::from_ref(&repo_id), 10)
523 .await
524 .expect("pushes.list_recent");
525
526 // webhooks and deliveries
527 let webhook_id = WebhookId::from_trusted("w1");
528 let webhooks = SqliteWebhookRepo::new(pool.clone());
529 webhooks.find(&webhook_id).await.expect("webhooks.find");
530 webhooks
531 .list_by_repo(&repo_id)
532 .await
533 .expect("webhooks.list_by_repo");
534
535 let deliveries = SqliteWebhookDeliveryRepo::new(pool.clone());
536 deliveries
537 .list_by_webhook(&webhook_id, 0, 10)
538 .await
539 .expect("deliveries.list_by_webhook");
540 assert_eq!(
541 deliveries
542 .count_by_webhook(&webhook_id)
543 .await
544 .expect("deliveries.count_by_webhook"),
545 0
546 );
547 deliveries
548 .latest_by_webhook(&webhook_id)
549 .await
550 .expect("deliveries.latest_by_webhook");
551
552 // labels, issue_labels, pull_request_labels
553 let labels = SqliteLabelRepo::new(pool.clone());
554 labels
555 .list_by_repo(&repo_id)
556 .await
557 .expect("labels.list_by_repo");
558 labels
559 .find_by_name(&repo_id, "bug")
560 .await
561 .expect("labels.find_by_name");
562 labels
563 .labels_for_repo(&repo_id)
564 .await
565 .expect("labels.labels_for_repo");
566 labels
567 .labels_for_repo_pulls(&repo_id)
568 .await
569 .expect("labels.labels_for_repo_pulls");
570 labels
571 .issue_counts(&repo_id)
572 .await
573 .expect("labels.issue_counts");
574 labels
575 .pull_counts(&repo_id)
576 .await
577 .expect("labels.pull_counts");
578}
579
580/// The newest migration this binary carries, read back from a database it has just
581/// migrated.
582async fn newest_applied(pool: &SqlitePool) -> i64 {
583 sqlx::query_scalar("select max(version) from _sqlx_migrations")
584 .fetch_one(pool)
585 .await
586 .expect("a migrated database records its migrations")
587}
588
589/// What a rollback onto this binary meets: a database a newer release has migrated.
590///
591/// The newer release leaves two things behind. Its migration's effect — an added column,
592/// because expand-only means it could only have added — and its migrator's record of
593/// it: a `_sqlx_migrations` row for a version past anything embedded here, applied
594/// successfully. This binary must boot against that, leave the record alone, and still
595/// read its own tables.
596#[tokio::test]
597async fn a_database_one_migration_ahead_still_boots() {
598 let pool = test_pool().await;
599 let ahead = newest_applied(&pool).await + 1;
600
601 sqlx::query("alter table users add column from_a_newer_release text")
602 .execute(&pool)
603 .await
604 .expect("the newer release's migration");
605 sqlx::query(
606 "insert into _sqlx_migrations (version, description, success, checksum, execution_time)
607 values (?, 'from a newer release', 1, ?, 0)",
608 )
609 .bind(ahead)
610 .bind(vec![0_u8; 48])
611 .execute(&pool)
612 .await
613 .expect("the newer release's record of it");
614
615 // sqlx's default refuses exactly this database, so it is the one a rollback could
616 // not boot against before `migrate` said otherwise — not one that never failed.
617 let refused = sqlx::migrate!("./migrations")
618 .run(&pool)
619 .await
620 .expect_err("sqlx's default refuses an applied migration it does not know");
621 assert!(
622 matches!(refused, MigrateError::VersionMissing(version) if version == ahead),
623 "expected VersionMissing({ahead}), got {refused}"
624 );
625
626 migrate(&pool)
627 .await
628 .expect("a binary one migration behind its database still boots");
629
630 let kept: i64 = sqlx::query_scalar("select count(*) from _sqlx_migrations where version = ?")
631 .bind(ahead)
632 .fetch_one(&pool)
633 .await
634 .expect("query");
635 assert_eq!(
636 kept, 1,
637 "the newer release's record of its migration is gone"
638 );
639
640 // And it serves: a read of the very table the newer release widened.
641 let users = SqliteUserRepo::new(pool.clone());
642 assert_eq!(users.count().await.expect("users.count"), 0);
643}
644
645/// Ignoring the migrations it does not know must not loosen the check on the ones it
646/// does: a shipped migration whose stored checksum disagrees with the embedded file is
647/// still refused.
648#[tokio::test]
649async fn an_edited_migration_is_still_refused() {
650 let pool = test_pool().await;
651 let edited = newest_applied(&pool).await;
652
653 sqlx::query("update _sqlx_migrations set checksum = ? where version = ?")
654 .bind(vec![0_u8; 48])
655 .bind(edited)
656 .execute(&pool)
657 .await
658 .expect("a checksum that is not the embedded file's");
659
660 let error = migrate(&pool)
661 .await
662 .expect_err("a known migration whose file has changed is refused");
663 match error {
664 sqlx::Error::Migrate(error) => assert!(
665 matches!(*error, MigrateError::VersionMismatch(version) if version == edited),
666 "expected VersionMismatch({edited}), got {error}"
667 ),
668 other => panic!("expected VersionMismatch({edited}), got {other}"),
669 }
670}
671
672#[test]
673fn the_guard_catches_a_contracting_migration() {
674 // The guard's own test: the four statements it exists to refuse, in the shape a
675 // real migration would write them, checked without touching migrations/. Without
676 // this, a guard that silently stopped matching would still pass every run.
677 for contracting in [
678 "alter table repositories drop column description;",
679 "drop table webhooks;",
680 "alter table orgs rename to organisations;",
681 "alter table users rename column email to address;",
682 ] {
683 let sql = statements_only(contracting);
684 assert!(
685 ["drop column", "drop table", "rename to", "rename column"]
686 .iter()
687 .any(|forbidden| sql.contains(forbidden)),
688 "the guard no longer recognises `{contracting}`"
689 );
690 }
691
692 let tightening = statements_only("alter table repositories add column stars integer not null;");
693 assert!(tightening.contains("add column") && tightening.contains("not null"));
694 assert!(
695 !tightening.contains("default"),
696 "the guard no longer recognises a `not null` column with no default"
697 );
698}
699
700#[test]
701fn prose_about_dropping_things_is_not_a_dropped_column() {
702 // Every migration here opens with paragraphs of reasoning, and they talk about
703 // dropping and renaming constantly. A guard that read the comments would have to be
704 // switched off within a week.
705 let sql = statements_only(
706 "-- We could DROP COLUMN `bio` here, or RENAME TO something else, but\n\
707 -- contracting waits a release. See architecture.md.\n\
708 alter table orgs add column tagline text;\n",
709 );
710
711 assert_eq!(sql, "alter table orgs add column tagline text;");
712
713 // And a literal is not a statement either.
714 let sql = statements_only("insert into notes (body) values ('drop table orgs');");
715 assert_eq!(sql, "insert into notes (body) values ();");
716}