drizzle 0.1.16

A type-safe SQL query builder for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
#[cfg(any(feature = "postgres-sync", feature = "tokio-postgres"))]
use drizzle::postgres::prelude::*;
#[cfg(any(feature = "postgres-sync", feature = "tokio-postgres"))]
use drizzle_migrations::{Migration, Tracking};

#[cfg(feature = "postgres-sync")]
#[PostgresTable(name = "items", schema = "push_creates_test")]
struct PushCreates {
    #[column(serial, primary)]
    id: i32,
    label: String,
    note: Option<String>,
}

#[cfg(feature = "postgres-sync")]
#[derive(PostgresSchema)]
struct PushCreatesSchema {
    items: PushCreates,
}

#[cfg(feature = "postgres-sync")]
#[PostgresTable(name = "items", schema = "push_idempotent_test")]
struct PushIdempotent {
    #[column(serial, primary)]
    id: i32,
    label: String,
    note: Option<String>,
}

#[cfg(feature = "postgres-sync")]
#[derive(PostgresSchema)]
struct PushIdempotentSchema {
    items: PushIdempotent,
}

#[cfg(feature = "postgres-sync")]
#[PostgresTable(name = "items", schema = "push_usable_test")]
struct PushUsable {
    #[column(serial, primary)]
    id: i32,
    label: String,
    note: Option<String>,
}

#[cfg(feature = "postgres-sync")]
#[derive(PostgresSchema)]
struct PushUsableSchema {
    items: PushUsable,
}

#[cfg(feature = "tokio-postgres")]
#[PostgresTable(name = "items", schema = "push_tokio_creates_test")]
struct TokioPushCreates {
    #[column(serial, primary)]
    id: i32,
    label: String,
    note: Option<String>,
}

#[cfg(feature = "tokio-postgres")]
#[derive(PostgresSchema)]
struct TokioPushCreatesSchema {
    items: TokioPushCreates,
}

#[cfg(feature = "tokio-postgres")]
#[PostgresTable(name = "items", schema = "push_tokio_idempotent_test")]
struct TokioPushIdempotent {
    #[column(serial, primary)]
    id: i32,
    label: String,
    note: Option<String>,
}

#[cfg(feature = "tokio-postgres")]
#[derive(PostgresSchema)]
struct TokioPushIdempotentSchema {
    items: TokioPushIdempotent,
}

#[cfg(feature = "tokio-postgres")]
#[PostgresTable(name = "items", schema = "push_tokio_usable_test")]
struct TokioPushUsable {
    #[column(serial, primary)]
    id: i32,
    label: String,
    note: Option<String>,
}

#[cfg(feature = "tokio-postgres")]
#[derive(PostgresSchema)]
struct TokioPushUsableSchema {
    items: TokioPushUsable,
}

#[cfg(feature = "postgres-sync")]
#[test]
fn postgres_sync_push_creates_table() {
    let (mut db, schema) = crate::common::helpers::postgres_sync_setup::setup_empty_named_db(
        "push_creates_test",
        PushCreatesSchema::default(),
    );
    let schema_name = db.schema_name().to_string();

    db.push(&schema).expect("push schema");

    let count = crate::common::helpers::postgres_sync_setup::table_exists(
        db.conn_mut(),
        &schema_name,
        "items",
    );
    assert_eq!(count, 1, "push should create the table");
}

#[cfg(feature = "postgres-sync")]
#[test]
fn postgres_sync_push_is_idempotent() {
    let (mut db, schema) = crate::common::helpers::postgres_sync_setup::setup_empty_named_db(
        "push_idempotent_test",
        PushIdempotentSchema::default(),
    );

    db.push(&schema).expect("first push");
    db.push(&schema).expect("second push should be a no-op");
}

#[cfg(feature = "postgres-sync")]
#[test]
fn postgres_sync_push_table_is_usable() {
    let (mut db, schema) = crate::common::helpers::postgres_sync_setup::setup_empty_named_db(
        "push_usable_test",
        PushUsableSchema::default(),
    );
    let schema_name = db.schema_name().to_string();

    db.push(&schema).expect("push schema");

    let id: i32 = db
        .conn_mut()
        .query_one(
            &format!(
                "INSERT INTO \"{}\".items (label) VALUES ('hello') RETURNING id",
                schema_name
            ),
            &[],
        )
        .expect("insert into pushed table")
        .get(0);

    let label: String = db
        .conn_mut()
        .query_one(
            &format!("SELECT label FROM \"{}\".items WHERE id = $1", schema_name),
            &[&id],
        )
        .expect("select from pushed table")
        .get(0);
    assert_eq!(label, "hello");
}

#[cfg(feature = "postgres-sync")]
#[test]
fn postgres_sync_runtime_migrate_upgrades_legacy_tracking_table() {
    let mut db =
        crate::common::helpers::postgres_sync_setup::setup_empty_named("runtime_upgrade_sync_test");
    let schema_name = db.schema_name().to_string();

    crate::common::helpers::postgres_sync_setup::create_legacy_tracking_table(
        db.conn_mut(),
        &schema_name,
        "__drizzle_migrations",
    );
    db.conn_mut()
        .execute(
            &format!(
                "INSERT INTO \"{}\".\"__drizzle_migrations\" (hash, created_at) VALUES ($1, $2)",
                schema_name
            ),
            &[&"runtime_hash_a", &1_680_271_923_000_i64],
        )
        .expect("insert legacy migration row");

    let migration = Migration::with_hash(
        "20230331141203_runtime_first",
        "runtime_hash_a",
        1_680_271_923_000,
        vec![format!(
            "CREATE TABLE \"{}\".runtime_created_at_a (id INTEGER PRIMARY KEY)",
            schema_name
        )],
    );

    db.migrate(&[migration], Tracking::POSTGRES.schema(schema_name.clone()))
        .expect("upgrade legacy runtime metadata");

    let columns = crate::common::helpers::postgres_sync_setup::legacy_tracking_columns(
        db.conn_mut(),
        &schema_name,
        "__drizzle_migrations",
    );
    assert_eq!(
        columns,
        vec!["id", "hash", "created_at", "name", "applied_at"],
        "tracking table should be upgraded in place"
    );

    let row = db
        .conn_mut()
        .query_one(
            &format!(
                "SELECT name, applied_at::text FROM \"{}\".\"__drizzle_migrations\" LIMIT 1",
                schema_name
            ),
            &[],
        )
        .expect("select upgraded migration row");
    let name: String = row.get(0);
    let applied_at: Option<String> = row.get(1);
    assert_eq!(name, "20230331141203_runtime_first");
    assert!(
        applied_at.is_some(),
        "legacy rows get applied_at backfilled so they cannot read as interrupted"
    );

    let migrated_table_exists = crate::common::helpers::postgres_sync_setup::table_exists(
        db.conn_mut(),
        &schema_name,
        "runtime_created_at_a",
    );
    assert_eq!(
        migrated_table_exists, 0,
        "already-applied migration should not run again during metadata upgrade"
    );
}

#[cfg(feature = "postgres-sync")]
#[test]
fn postgres_sync_runtime_migrate_upgrade_uses_hash_for_same_timestamp() {
    let mut db = crate::common::helpers::postgres_sync_setup::setup_empty_named(
        "runtime_upgrade_collision_sync_test",
    );
    let schema_name = db.schema_name().to_string();

    crate::common::helpers::postgres_sync_setup::create_legacy_tracking_table(
        db.conn_mut(),
        &schema_name,
        "__drizzle_migrations",
    );
    db.conn_mut()
        .execute(
            &format!(
                "INSERT INTO \"{}\".\"__drizzle_migrations\" (hash, created_at) VALUES ($1, $2)",
                schema_name
            ),
            &[&"runtime_hash_b", &1_680_271_923_000_i64],
        )
        .expect("insert legacy migration row");

    let migrations = vec![
        Migration::with_hash(
            "20230331141203_runtime_alpha",
            "runtime_hash_a",
            1_680_271_923_000,
            vec![format!(
                "CREATE TABLE \"{}\".runtime_created_at_a (id INTEGER PRIMARY KEY)",
                schema_name
            )],
        ),
        Migration::with_hash(
            "20230331141203_runtime_beta",
            "runtime_hash_b",
            1_680_271_923_000,
            vec![format!(
                "CREATE TABLE \"{}\".runtime_created_at_b (id INTEGER PRIMARY KEY)",
                schema_name
            )],
        ),
    ];

    db.migrate(&migrations, Tracking::POSTGRES.schema(schema_name.clone()))
        .expect("upgrade legacy runtime metadata with timestamp collision");

    let name: String = db
        .conn_mut()
        .query_one(
            &format!(
                "SELECT name FROM \"{}\".\"__drizzle_migrations\" LIMIT 1",
                schema_name
            ),
            &[],
        )
        .expect("select upgraded migration name")
        .get(0);
    assert_eq!(name, "20230331141203_runtime_beta");
}

#[cfg(feature = "postgres-sync")]
#[test]
fn postgres_sync_runtime_migrate_upgrade_rejects_unmatched_legacy_rows() {
    let mut db = crate::common::helpers::postgres_sync_setup::setup_empty_named(
        "runtime_upgrade_unmatched_sync_test",
    );
    let schema_name = db.schema_name().to_string();

    crate::common::helpers::postgres_sync_setup::create_legacy_tracking_table(
        db.conn_mut(),
        &schema_name,
        "__drizzle_migrations",
    );
    db.conn_mut()
        .execute(
            &format!(
                "INSERT INTO \"{}\".\"__drizzle_migrations\" (hash, created_at) VALUES ($1, $2)",
                schema_name
            ),
            &[&"unknown_hash", &1_680_271_924_000_i64],
        )
        .expect("insert unmatched legacy row");

    let migration = Migration::with_hash(
        "20230331141203_runtime_first",
        "runtime_hash_a",
        1_680_271_923_000,
        vec![format!(
            "CREATE TABLE \"{}\".runtime_created_at_a (id INTEGER PRIMARY KEY)",
            schema_name
        )],
    );

    let err = db
        .migrate(&[migration], Tracking::POSTGRES.schema(schema_name.clone()))
        .expect_err("unmatched legacy metadata should fail");
    assert!(err.to_string().contains("do not match local migrations"));

    let columns = crate::common::helpers::postgres_sync_setup::legacy_tracking_columns(
        db.conn_mut(),
        &schema_name,
        "__drizzle_migrations",
    );
    assert_eq!(columns, vec!["id", "hash", "created_at"]);
}

#[cfg(feature = "tokio-postgres")]
#[tokio::test]
async fn tokio_postgres_runtime_migrate_upgrades_legacy_tracking_table() {
    let mut db = crate::common::helpers::tokio_postgres_setup::setup_empty_named(
        "runtime_upgrade_tokio_test",
    )
    .await;
    let schema_name = db.schema_name().to_string();

    crate::common::helpers::tokio_postgres_setup::create_legacy_tracking_table(
        db.conn(),
        &schema_name,
        "__drizzle_migrations",
    )
    .await;
    db.conn()
        .execute(
            &format!(
                "INSERT INTO \"{}\".\"__drizzle_migrations\" (hash, created_at) VALUES ($1, $2)",
                schema_name
            ),
            &[&"runtime_hash_a", &1_680_271_923_000_i64],
        )
        .await
        .expect("insert legacy migration row");

    let migration = Migration::with_hash(
        "20230331141203_runtime_first",
        "runtime_hash_a",
        1_680_271_923_000,
        vec![format!(
            "CREATE TABLE \"{}\".runtime_created_at_a (id INTEGER PRIMARY KEY)",
            schema_name
        )],
    );

    db.migrate(&[migration], Tracking::POSTGRES.schema(schema_name.clone()))
        .await
        .expect("upgrade legacy runtime metadata");

    let columns = crate::common::helpers::tokio_postgres_setup::legacy_tracking_columns(
        db.conn(),
        &schema_name,
        "__drizzle_migrations",
    )
    .await;
    assert_eq!(
        columns,
        vec!["id", "hash", "created_at", "name", "applied_at"],
        "tracking table should be upgraded in place"
    );

    let row = db
        .conn()
        .query_one(
            &format!(
                "SELECT name, applied_at::text FROM \"{}\".\"__drizzle_migrations\" LIMIT 1",
                schema_name
            ),
            &[],
        )
        .await
        .expect("select upgraded migration row");
    let name: String = row.get(0);
    let applied_at: Option<String> = row.get(1);
    assert_eq!(name, "20230331141203_runtime_first");
    assert!(
        applied_at.is_some(),
        "legacy rows get applied_at backfilled so they cannot read as interrupted"
    );

    let migrated_table_exists = crate::common::helpers::tokio_postgres_setup::table_exists(
        db.conn(),
        &schema_name,
        "runtime_created_at_a",
    )
    .await;
    assert_eq!(
        migrated_table_exists, 0,
        "already-applied migration should not run again during metadata upgrade"
    );
}

#[cfg(feature = "tokio-postgres")]
#[tokio::test]
async fn tokio_postgres_runtime_migrate_upgrade_uses_hash_for_same_timestamp() {
    let mut db = crate::common::helpers::tokio_postgres_setup::setup_empty_named(
        "runtime_upgrade_collision_tokio_test",
    )
    .await;
    let schema_name = db.schema_name().to_string();

    crate::common::helpers::tokio_postgres_setup::create_legacy_tracking_table(
        db.conn(),
        &schema_name,
        "__drizzle_migrations",
    )
    .await;
    db.conn()
        .execute(
            &format!(
                "INSERT INTO \"{}\".\"__drizzle_migrations\" (hash, created_at) VALUES ($1, $2)",
                schema_name
            ),
            &[&"runtime_hash_b", &1_680_271_923_000_i64],
        )
        .await
        .expect("insert legacy migration row");

    let migrations = vec![
        Migration::with_hash(
            "20230331141203_runtime_alpha",
            "runtime_hash_a",
            1_680_271_923_000,
            vec![format!(
                "CREATE TABLE \"{}\".runtime_created_at_a (id INTEGER PRIMARY KEY)",
                schema_name
            )],
        ),
        Migration::with_hash(
            "20230331141203_runtime_beta",
            "runtime_hash_b",
            1_680_271_923_000,
            vec![format!(
                "CREATE TABLE \"{}\".runtime_created_at_b (id INTEGER PRIMARY KEY)",
                schema_name
            )],
        ),
    ];

    db.migrate(&migrations, Tracking::POSTGRES.schema(schema_name.clone()))
        .await
        .expect("upgrade legacy runtime metadata with timestamp collision");

    let name: String = db
        .conn()
        .query_one(
            &format!(
                "SELECT name FROM \"{}\".\"__drizzle_migrations\" LIMIT 1",
                schema_name
            ),
            &[],
        )
        .await
        .expect("select upgraded migration name")
        .get(0);
    assert_eq!(name, "20230331141203_runtime_beta");
}

#[cfg(feature = "tokio-postgres")]
#[tokio::test]
async fn tokio_postgres_runtime_migrate_upgrade_rejects_unmatched_legacy_rows() {
    let mut db = crate::common::helpers::tokio_postgres_setup::setup_empty_named(
        "runtime_upgrade_unmatched_tokio_test",
    )
    .await;
    let schema_name = db.schema_name().to_string();

    crate::common::helpers::tokio_postgres_setup::create_legacy_tracking_table(
        db.conn(),
        &schema_name,
        "__drizzle_migrations",
    )
    .await;
    db.conn()
        .execute(
            &format!(
                "INSERT INTO \"{}\".\"__drizzle_migrations\" (hash, created_at) VALUES ($1, $2)",
                schema_name
            ),
            &[&"unknown_hash", &1_680_271_924_000_i64],
        )
        .await
        .expect("insert unmatched legacy row");

    let migration = Migration::with_hash(
        "20230331141203_runtime_first",
        "runtime_hash_a",
        1_680_271_923_000,
        vec![format!(
            "CREATE TABLE \"{}\".runtime_created_at_a (id INTEGER PRIMARY KEY)",
            schema_name
        )],
    );

    let err = db
        .migrate(&[migration], Tracking::POSTGRES.schema(schema_name.clone()))
        .await
        .expect_err("unmatched legacy metadata should fail");
    assert!(err.to_string().contains("do not match local migrations"));

    let columns = crate::common::helpers::tokio_postgres_setup::legacy_tracking_columns(
        db.conn(),
        &schema_name,
        "__drizzle_migrations",
    )
    .await;
    assert_eq!(columns, vec!["id", "hash", "created_at"]);
}

#[cfg(feature = "tokio-postgres")]
#[tokio::test]
async fn tokio_postgres_push_creates_table() {
    let (db, schema) = crate::common::helpers::tokio_postgres_setup::setup_empty_named_db(
        "push_tokio_creates_test",
        TokioPushCreatesSchema::default(),
    )
    .await;

    db.push(&schema).await.expect("push schema");

    let count = crate::common::helpers::tokio_postgres_setup::table_exists(
        db.conn(),
        db.schema_name(),
        "items",
    )
    .await;
    assert_eq!(count, 1, "push should create the table");
}

#[cfg(feature = "tokio-postgres")]
#[tokio::test]
async fn tokio_postgres_push_is_idempotent() {
    let (db, schema) = crate::common::helpers::tokio_postgres_setup::setup_empty_named_db(
        "push_tokio_idempotent_test",
        TokioPushIdempotentSchema::default(),
    )
    .await;

    db.push(&schema).await.expect("first push");
    db.push(&schema)
        .await
        .expect("second push should be a no-op");
}

#[cfg(feature = "tokio-postgres")]
#[tokio::test]
async fn tokio_postgres_push_table_is_usable() {
    let (db, schema) = crate::common::helpers::tokio_postgres_setup::setup_empty_named_db(
        "push_tokio_usable_test",
        TokioPushUsableSchema::default(),
    )
    .await;

    db.push(&schema).await.expect("push schema");

    let id: i32 = db
        .conn()
        .query_one(
            &format!(
                "INSERT INTO \"{}\".items (label) VALUES ('hello') RETURNING id",
                db.schema_name()
            ),
            &[],
        )
        .await
        .expect("insert into pushed table")
        .get(0);

    let label: String = db
        .conn()
        .query_one(
            &format!(
                "SELECT label FROM \"{}\".items WHERE id = $1",
                db.schema_name()
            ),
            &[&id],
        )
        .await
        .expect("select from pushed table")
        .get(0);
    assert_eq!(label, "hello");
}

// ============================================================================
// Partial-migration recovery (CONCURRENTLY path)
// ============================================================================
//
// A migration containing CREATE INDEX CONCURRENTLY cannot run in a
// transaction, so its statements execute autocommit. Two-phase tracking marks
// the migration dirty before the first statement and stamps `applied_at` only
// after the last one, so a crash in between leaves a recoverable dirty row
// instead of an untracked partial schema.

#[cfg(feature = "postgres-sync")]
#[test]
fn postgres_sync_concurrent_migration_uses_two_phase_tracking() {
    let mut db =
        crate::common::helpers::postgres_sync_setup::setup_empty_named("two_phase_sync_test");
    let schema_name = db.schema_name().to_string();
    let tracking = Tracking::POSTGRES.schema(schema_name.clone());

    let migration = Migration::new(
        "20260801000000_concurrent",
        &format!(
            "CREATE TABLE \"{schema_name}\".two_phase_items (id INTEGER PRIMARY KEY, label TEXT);\n\
             --> statement-breakpoint\n\
             CREATE INDEX CONCURRENTLY two_phase_items_label_idx \
             ON \"{schema_name}\".two_phase_items (label);"
        ),
    );

    let outcome = db
        .migrate(std::slice::from_ref(&migration), tracking.clone())
        .expect("concurrent migration");
    assert_eq!(outcome.applied_tags(), ["20260801000000_concurrent"]);

    // Phase 3 ran: the row is complete, not dirty.
    let dirty: i64 = db
        .conn_mut()
        .query_one(
            &format!(
                "SELECT COUNT(*) FROM \"{schema_name}\".\"__drizzle_migrations\" \
                 WHERE applied_at IS NULL"
            ),
            &[],
        )
        .expect("count dirty rows")
        .get(0);
    assert_eq!(dirty, 0, "a completed migration must not stay dirty");

    let outcome = db.migrate(&[migration], tracking).expect("second migrate");
    assert!(outcome.is_up_to_date());
}

#[cfg(feature = "postgres-sync")]
#[test]
fn postgres_sync_repair_finishes_an_interrupted_concurrent_migration() {
    let mut db = crate::common::helpers::postgres_sync_setup::setup_empty_named("repair_sync_test");
    let schema_name = db.schema_name().to_string();
    let tracking = Tracking::POSTGRES.schema(schema_name.clone());

    let migration = Migration::new(
        "20260801000001_interrupted",
        &format!(
            "CREATE TABLE \"{schema_name}\".repair_items (id INTEGER PRIMARY KEY, label TEXT);\n\
             --> statement-breakpoint\n\
             CREATE INDEX CONCURRENTLY repair_items_label_idx \
             ON \"{schema_name}\".repair_items (label);"
        ),
    );
    let set = drizzle_migrations::Migrations::with_tracking(
        vec![migration.clone()],
        drizzle_types::Dialect::PostgreSQL,
        tracking.clone(),
    );

    // Reproduce the incident: schema + tracking table, phase-1 dirty marker,
    // first statement applied, then "crash" before phase 3.
    if let Some(schema_sql) = set.create_schema_sql() {
        db.conn_mut()
            .execute(schema_sql.as_str(), &[])
            .expect("create tracking schema");
    }
    db.conn_mut()
        .execute(set.create_table_sql().as_str(), &[])
        .expect("create tracking table");
    db.conn_mut()
        .execute(set.record_migration_started_sql(&migration).as_str(), &[])
        .expect("record migration started");
    db.conn_mut()
        .execute(migration.statements()[0].as_str(), &[])
        .expect("apply first statement");

    // Plain migrate() refuses and names the interrupted migration.
    let error = db
        .migrate(std::slice::from_ref(&migration), tracking.clone())
        .expect_err("a dirty tracking row must block migration");
    let text = error.to_string();
    assert!(text.contains("20260801000001_interrupted"), "{text}");
    assert!(text.contains("interrupted mid-apply"), "{text}");
    assert!(text.contains("--repair"), "{text}");

    // Repair proves statement 1 already landed, runs statement 2, clears the
    // marker.
    let outcome = db
        .migrate_with_repair(std::slice::from_ref(&migration), tracking.clone())
        .expect("repair should reconcile the interrupted migration");
    assert_eq!(outcome.applied_tags(), ["20260801000001_interrupted"]);

    let index_exists: i64 = db
        .conn_mut()
        .query_one(
            "SELECT COUNT(*) FROM pg_indexes WHERE schemaname = $1 AND indexname = $2",
            &[&schema_name, &"repair_items_label_idx"],
        )
        .expect("count index")
        .get(0);
    assert_eq!(
        index_exists, 1,
        "repair must run the statement that never landed"
    );

    let outcome = db.migrate(&[migration], tracking).expect("second migrate");
    assert!(
        outcome.is_up_to_date(),
        "repaired migration must count as applied: {outcome:?}"
    );
}

#[cfg(feature = "postgres-sync")]
#[test]
fn postgres_sync_repair_refuses_statements_it_cannot_prove() {
    let mut db =
        crate::common::helpers::postgres_sync_setup::setup_empty_named("repair_refuse_sync_test");
    let schema_name = db.schema_name().to_string();
    let tracking = Tracking::POSTGRES.schema(schema_name.clone());

    db.conn_mut()
        .execute(
            &format!("CREATE TABLE \"{schema_name}\".refuse_items (id INTEGER PRIMARY KEY)"),
            &[],
        )
        .expect("seed table");

    // The interrupted migration leads with an ALTER: repair cannot tell
    // whether it ran, so it must refuse instead of guessing.
    let migration = Migration::new(
        "20260801000002_unprovable",
        &format!(
            "ALTER TABLE \"{schema_name}\".refuse_items ADD COLUMN note TEXT;\n\
             --> statement-breakpoint\n\
             CREATE INDEX CONCURRENTLY refuse_items_note_idx \
             ON \"{schema_name}\".refuse_items (note);"
        ),
    );
    let set = drizzle_migrations::Migrations::with_tracking(
        vec![migration.clone()],
        drizzle_types::Dialect::PostgreSQL,
        tracking.clone(),
    );

    if let Some(schema_sql) = set.create_schema_sql() {
        db.conn_mut()
            .execute(schema_sql.as_str(), &[])
            .expect("create tracking schema");
    }
    db.conn_mut()
        .execute(set.create_table_sql().as_str(), &[])
        .expect("create tracking table");
    db.conn_mut()
        .execute(set.record_migration_started_sql(&migration).as_str(), &[])
        .expect("record migration started");

    let error = db
        .migrate_with_repair(&[migration], tracking)
        .expect_err("an unprovable statement must not be silently skipped or re-run");
    let text = error.to_string();
    assert!(text.contains("cannot repair"), "{text}");
    assert!(text.contains("statement 1"), "{text}");
    assert!(text.contains("UPDATE"), "manual completion SQL: {text}");

    let index_exists: i64 = db
        .conn_mut()
        .query_one(
            "SELECT COUNT(*) FROM pg_indexes WHERE schemaname = $1 AND indexname = $2",
            &[&schema_name, &"refuse_items_note_idx"],
        )
        .expect("count index")
        .get(0);
    assert_eq!(index_exists, 0, "a refused repair must not apply anything");
}

#[cfg(feature = "tokio-postgres")]
#[tokio::test]
async fn tokio_postgres_repair_finishes_an_interrupted_concurrent_migration() {
    let mut db =
        crate::common::helpers::tokio_postgres_setup::setup_empty_named("repair_tokio_test").await;
    let schema_name = db.schema_name().to_string();
    let tracking = Tracking::POSTGRES.schema(schema_name.clone());

    let migration = Migration::new(
        "20260801000003_interrupted",
        &format!(
            "CREATE TABLE \"{schema_name}\".repair_async_items (id INTEGER PRIMARY KEY, label TEXT);\n\
             --> statement-breakpoint\n\
             CREATE INDEX CONCURRENTLY repair_async_items_label_idx \
             ON \"{schema_name}\".repair_async_items (label);"
        ),
    );
    let set = drizzle_migrations::Migrations::with_tracking(
        vec![migration.clone()],
        drizzle_types::Dialect::PostgreSQL,
        tracking.clone(),
    );

    if let Some(schema_sql) = set.create_schema_sql() {
        db.conn()
            .execute(schema_sql.as_str(), &[])
            .await
            .expect("create tracking schema");
    }
    db.conn()
        .execute(set.create_table_sql().as_str(), &[])
        .await
        .expect("create tracking table");
    db.conn()
        .execute(set.record_migration_started_sql(&migration).as_str(), &[])
        .await
        .expect("record migration started");
    db.conn()
        .execute(migration.statements()[0].as_str(), &[])
        .await
        .expect("apply first statement");

    let error = db
        .migrate(std::slice::from_ref(&migration), tracking.clone())
        .await
        .expect_err("a dirty tracking row must block migration");
    let text = error.to_string();
    assert!(text.contains("20260801000003_interrupted"), "{text}");
    assert!(text.contains("interrupted mid-apply"), "{text}");

    let outcome = db
        .migrate_with_repair(std::slice::from_ref(&migration), tracking.clone())
        .await
        .expect("repair should reconcile the interrupted migration");
    assert_eq!(outcome.applied_tags(), ["20260801000003_interrupted"]);

    let index_exists: i64 = db
        .conn()
        .query_one(
            "SELECT COUNT(*) FROM pg_indexes WHERE schemaname = $1 AND indexname = $2",
            &[&schema_name, &"repair_async_items_label_idx"],
        )
        .await
        .expect("count index")
        .get(0);
    assert_eq!(index_exists, 1);

    let outcome = db
        .migrate(&[migration], tracking)
        .await
        .expect("second migrate");
    assert!(outcome.is_up_to_date());
}