drizzle 0.1.13

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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
// =============================================================================
// Temp DB Path Generation (file-based test isolation)
// =============================================================================

use std::path::PathBuf;
use std::sync::Once;
use std::sync::atomic::{AtomicU64, Ordering};

const TEST_DB_DIR: &str = "drizzle_rs_tests";

fn ensure_test_db_dir() {
    static INIT: Once = Once::new();
    INIT.call_once(|| {
        // Each process gets its own subdirectory keyed by PID, so concurrent
        // `cargo test` invocations never interfere with each other.
        let dir = std::env::temp_dir()
            .join(TEST_DB_DIR)
            .join(std::process::id().to_string());
        // Clean up any stale files from a previous run with the same PID.
        if dir.exists() {
            let _ = std::fs::remove_dir_all(&dir);
        }
        let _ = std::fs::create_dir_all(&dir);
    });
}

pub fn temp_db_path() -> PathBuf {
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    ensure_test_db_dir();
    let id = COUNTER.fetch_add(1, Ordering::Relaxed);
    let pid = std::process::id();
    std::env::temp_dir()
        .join(TEST_DB_DIR)
        .join(pid.to_string())
        .join(format!("test_{}.db", id))
}

// =============================================================================
// Test Failure Report Infrastructure
// =============================================================================

const BOX_WIDTH: usize = 80;
const CONTENT_WIDTH: usize = BOX_WIDTH - 4; // Account for "│ " prefix and " │" suffix

/// Captured SQL statement with optional error
#[derive(Clone, Debug)]
pub struct CapturedStatement {
    pub sql: String,
    pub params: Option<String>,
    pub source: Option<String>,
    pub error: Option<String>,
}

/// Process-global panic hook that prints the SQL trail for the currently
/// running `#[drizzle::test]` function.
///
/// The naive approach — `take_hook` / `set_hook` on every test entry — races
/// under parallel test execution: Test B's `take_hook` can capture Test A's
/// hook, and the saved `__prev_hook` chain ends up pointing at closures owned
/// by other tests. The result is cross-test SQL trails on panic.
///
/// Instead we install one global hook, keyed on a `thread_local!` that each
/// test sets via a RAII guard. The default `#[tokio::test]` runtime is
/// `flavor = "current_thread"`, so the whole test body (including async
/// polling) runs on the thread that constructed the guard. `#[test]` is
/// obviously single-threaded. Either way the hook finds the right trail.
pub mod panic_hook {
    use super::CapturedStatement;
    use std::cell::RefCell;
    use std::sync::{Arc, Mutex, Once};

    type StatementTrail = Arc<Mutex<Vec<CapturedStatement>>>;
    type TrailSlot = RefCell<Option<(String, StatementTrail)>>;

    thread_local! {
        static CURRENT_TRAIL: TrailSlot = const { RefCell::new(None) };
    }

    static INSTALL: Once = Once::new();

    /// Install the process-global panic hook. Idempotent — safe to call from
    /// every test's setup; the `Once` gate means the `take_hook`/`set_hook`
    /// swap happens exactly once for the whole process.
    pub fn install_once() {
        INSTALL.call_once(|| {
            let prev = std::panic::take_hook();
            std::panic::set_hook(Box::new(move |info| {
                let mut buf = String::new();
                CURRENT_TRAIL.with(|cell| {
                    // `try_borrow` (not `borrow`) — if the panic fires while
                    // the cell is borrowed mutably elsewhere we want to fall
                    // through to the default hook rather than double-panic.
                    let Ok(guard) = cell.try_borrow() else { return };
                    let Some((name, arc)) = guard.as_ref() else { return };
                    use std::fmt::Write as _;
                    let _ = writeln!(buf, "[{}] panicked", name);
                    // `try_lock` guards against deadlock if the panic happens
                    // while a `record_sql` / `report` caller holds the mutex.
                    match arc.try_lock() {
                        Ok(stmts) => {
                            if !stmts.is_empty() {
                                let _ = writeln!(buf, "captured statements ({}):", stmts.len());
                                for (i, s) in stmts.iter().enumerate() {
                                    if let Some(src) = &s.source {
                                        let _ = writeln!(buf, "  #{} {}", i + 1, src);
                                    }
                                    let _ = writeln!(buf, "     sql: {}", s.sql);
                                    if let Some(p) = &s.params {
                                        let _ = writeln!(buf, "     params: {}", p);
                                    }
                                    if let Some(e) = &s.error {
                                        let _ = writeln!(buf, "     error: {}", e);
                                    }
                                }
                            }
                        }
                        Err(_) => {
                            let _ = writeln!(
                                buf,
                                "(statements mutex was locked at time of panic; SQL trail unavailable)"
                            );
                        }
                    }
                });
                if !buf.is_empty() {
                    eprintln!("{}", buf);
                }
                prev(info);
            }));
        });
    }

    /// RAII guard that stashes `(test_name, statements)` in the thread-local
    /// on construction and restores the previous value on drop (normal exit
    /// or unwinding). Tests never nest today, but the save-and-restore keeps
    /// us safe if they ever do.
    pub struct TrailGuard {
        prev: Option<(String, StatementTrail)>,
    }

    impl TrailGuard {
        pub fn new(test_name: String, statements: StatementTrail) -> Self {
            let prev =
                CURRENT_TRAIL.with(|cell| cell.borrow_mut().replace((test_name, statements)));
            Self { prev }
        }
    }

    impl Drop for TrailGuard {
        fn drop(&mut self) {
            let prev = self.prev.take();
            CURRENT_TRAIL.with(|cell| {
                *cell.borrow_mut() = prev;
            });
        }
    }
}

/// Calculate display width accounting for special characters
fn display_width(s: &str) -> usize {
    s.chars()
        .map(|c| match c {
            '' | '' | '' => 1,
            _ if c.is_ascii() => 1,
            _ => 2,
        })
        .sum()
}

/// Expand tabs to spaces
fn expand_tabs(s: &str) -> String {
    s.replace('\t', "    ")
}

/// Wrap text to fit within a given width
fn wrap_text(text: &str, width: usize) -> Vec<String> {
    let text = expand_tabs(text);
    let mut lines = Vec::new();

    for line in text.lines() {
        if line.is_empty() {
            lines.push(String::new());
            continue;
        }

        if display_width(line) <= width {
            lines.push(line.to_string());
        } else {
            let mut current_line = String::new();
            let mut current_width = 0;

            for word in line.split_inclusive(' ') {
                let word_width = display_width(word);

                if current_width + word_width <= width {
                    current_line.push_str(word);
                    current_width += word_width;
                } else {
                    // Flush current line if non-empty
                    if !current_line.is_empty() {
                        lines.push(current_line.trim_end().to_string());
                        current_line = String::new();
                        current_width = 0;
                    }

                    if word_width <= width {
                        current_line.push_str(word);
                        current_width = word_width;
                    } else {
                        // Word is longer than width, force split
                        let mut chars = word.chars().peekable();
                        while chars.peek().is_some() {
                            let mut chunk = String::new();
                            let mut chunk_width = 0;
                            while let Some(&c) = chars.peek() {
                                let c_width = if c.is_ascii() { 1 } else { 2 };
                                if chunk_width + c_width > width {
                                    break;
                                }
                                chunk.push(chars.next().unwrap());
                                chunk_width += c_width;
                            }
                            if !chunk.is_empty() {
                                lines.push(chunk);
                            }
                        }
                    }
                }
            }

            if !current_line.is_empty() {
                lines.push(current_line.trim_end().to_string());
            }
        }
    }

    if lines.is_empty() {
        lines.push(String::new());
    }

    lines
}

/// Format a line with proper box drawing
fn box_line(content: &str, prefix: &str) -> String {
    let content = expand_tabs(content);
    let prefix_width = display_width(prefix);
    let content_width = display_width(&content);
    let total_used = prefix_width + content_width;
    let padding = CONTENT_WIDTH.saturating_sub(total_used);
    format!("{}{}{}\n", prefix, content, " ".repeat(padding))
}

/// Format a section header
fn section_header(title: &str) -> String {
    // Total inner width is BOX_WIDTH - 2 (for the ├ and ┤)
    // Format: ├─ TITLE ─────...─────┤
    // So: 1 (─) + 1 (space) + title + 1 (space) + remaining dashes = BOX_WIDTH - 2
    let inner_width = BOX_WIDTH - 2;
    let title_width = display_width(title);
    let used = 1 + 1 + title_width + 1; // "─ TITLE "
    let dashes = inner_width.saturating_sub(used);
    format!("├─ {} {}\n", title, "".repeat(dashes))
}

/// Format the top border
fn top_border() -> String {
    format!("{}\n", "".repeat(BOX_WIDTH - 2))
}

/// Format the bottom border
fn bottom_border() -> String {
    format!("{}\n", "".repeat(BOX_WIDTH - 2))
}

/// Format an empty line within the box
fn empty_box_line() -> String {
    format!("{}\n", " ".repeat(BOX_WIDTH - 2))
}

/// Context for generating a structured failure report
pub struct FailureContext<'a> {
    pub driver_name: &'a str,
    pub test_name: &'a str,
    pub error: &'a dyn std::fmt::Display,
    pub expected: Option<&'a str>,
    pub actual: Option<&'a str>,
    pub failed_operation: Option<&'a str>,
    pub schema_ddl: &'a [String],
    pub statements: &'a [CapturedStatement],
}

/// Generate a structured failure report for any driver
pub fn failure_report(ctx: &FailureContext<'_>) -> String {
    let FailureContext {
        driver_name,
        test_name,
        error,
        expected,
        actual,
        failed_operation,
        schema_ddl,
        statements,
    } = ctx;
    let mut report = String::new();

    // Header
    let header = "TEST FAILURE REPORT";
    let header_width = display_width(header);
    let header_padding = (BOX_WIDTH - 2 - header_width) / 2;
    let header_padding_right = BOX_WIDTH - 2 - header_width - header_padding;

    report.push('\n');
    report.push_str(&top_border());
    report.push_str(&format!(
        "{}{}{}\n",
        " ".repeat(header_padding),
        header,
        " ".repeat(header_padding_right)
    ));
    report.push_str(&bottom_border());
    report.push('\n');

    // Test identification section
    report.push_str(&top_border());
    report.push_str(&section_header("TEST"));
    let name_lines = wrap_text(test_name, CONTENT_WIDTH - 8);
    for (i, line) in name_lines.iter().enumerate() {
        let prefix = if i == 0 { "Name:   " } else { "        " };
        report.push_str(&box_line(line, prefix));
    }
    report.push_str(&box_line(driver_name, "Driver: "));
    report.push_str(&bottom_border());
    report.push('\n');

    // Error section
    report.push_str(&top_border());
    report.push_str(&section_header("ERROR"));
    let error_text = format!("{}", error);
    let error_lines = wrap_text(&error_text, CONTENT_WIDTH);
    for line in error_lines {
        report.push_str(&box_line(&line, ""));
    }
    report.push_str(&bottom_border());
    report.push('\n');

    // Expected vs Actual (if provided)
    if expected.is_some() || actual.is_some() {
        report.push_str(&top_border());
        report.push_str(&section_header("COMPARISON"));
        if let Some(exp) = expected {
            let exp_lines = wrap_text(exp, CONTENT_WIDTH - 10);
            for (i, line) in exp_lines.iter().enumerate() {
                if i == 0 {
                    report.push_str(&box_line(line, "Expected: "));
                } else {
                    report.push_str(&box_line(line, "          "));
                }
            }
        }
        if let Some(act) = actual {
            let act_lines = wrap_text(act, CONTENT_WIDTH - 10);
            for (i, line) in act_lines.iter().enumerate() {
                if i == 0 {
                    report.push_str(&box_line(line, "Actual:   "));
                } else {
                    report.push_str(&box_line(line, "          "));
                }
            }
        }
        report.push_str(&bottom_border());
        report.push('\n');
    }

    // Failed operation section (if provided, skip when redundant with last statement)
    if let Some(op) = failed_operation {
        let redundant = statements
            .last()
            .and_then(|s| s.source.as_deref())
            .is_some_and(|src| src == *op);
        if !redundant {
            report.push_str(&top_border());
            report.push_str(&section_header("FAILED OPERATION"));
            let op_lines = wrap_text(op, CONTENT_WIDTH - 2);
            for line in op_lines {
                report.push_str(&box_line(&line, "  "));
            }
            report.push_str(&bottom_border());
            report.push('\n');
        }
    }

    // Schema DDL section
    report.push_str(&top_border());
    report.push_str(&section_header("SCHEMA DDL"));
    if schema_ddl.is_empty() {
        report.push_str(&box_line("(no DDL statements captured)", ""));
    } else {
        for (i, ddl) in schema_ddl.iter().enumerate() {
            report.push_str(&box_line(&format!("[{}]", i + 1), ""));
            for line in ddl.lines() {
                let expanded = expand_tabs(line);
                let wrapped = wrap_text(&expanded, CONTENT_WIDTH - 2);
                for wrap_line in wrapped {
                    report.push_str(&box_line(&wrap_line, "  "));
                }
            }
            if i < schema_ddl.len() - 1 {
                report.push_str(&empty_box_line());
            }
        }
    }
    report.push_str(&bottom_border());
    report.push('\n');

    // Executed statements section
    report.push_str(&top_border());
    report.push_str(&section_header("EXECUTED STATEMENTS"));
    if statements.is_empty() {
        report.push_str(&box_line("(no statements executed)", ""));
    } else {
        for (i, stmt) in statements.iter().enumerate() {
            let status = if stmt.error.is_some() { "" } else { "" };
            report.push_str(&box_line(&format!("[{}]", i + 1), &format!("{} ", status)));

            if let Some(source) = &stmt.source {
                // Show Rust source expression
                for line in source.lines() {
                    let expanded = expand_tabs(line);
                    let wrapped = wrap_text(&expanded, CONTENT_WIDTH - 4);
                    for wrap_line in wrapped {
                        report.push_str(&box_line(&wrap_line, "    "));
                    }
                }
                // Blank line separating source from SQL/params/error
                report.push_str(&empty_box_line());
                // Show generated SQL on next line with arrow
                let sql_display = format!("{}", stmt.sql);
                for line in sql_display.lines() {
                    let expanded = expand_tabs(line);
                    let wrapped = wrap_text(&expanded, CONTENT_WIDTH - 4);
                    for wrap_line in wrapped {
                        report.push_str(&box_line(&wrap_line, "    "));
                    }
                }
                if let Some(params) = &stmt.params {
                    let params_display = format!("Params: {}", params);
                    let wrapped = wrap_text(&params_display, CONTENT_WIDTH - 4);
                    for wrap_line in wrapped {
                        report.push_str(&box_line(&wrap_line, "    "));
                    }
                }
                if let Some(err) = &stmt.error {
                    let err_display = format!("Error: {}", err);
                    let wrapped = wrap_text(&err_display, CONTENT_WIDTH - 4);
                    for wrap_line in wrapped {
                        report.push_str(&box_line(&wrap_line, "    "));
                    }
                }
            } else {
                // No source — show SQL directly (DDL or old pattern)
                for line in stmt.sql.lines() {
                    let expanded = expand_tabs(line);
                    let wrapped = wrap_text(&expanded, CONTENT_WIDTH - 4);
                    for wrap_line in wrapped {
                        report.push_str(&box_line(&wrap_line, "    "));
                    }
                }
                if let Some(err) = &stmt.error {
                    let err_display = format!("Error: {}", err);
                    let wrapped = wrap_text(&err_display, CONTENT_WIDTH - 4);
                    for wrap_line in wrapped {
                        report.push_str(&box_line(&wrap_line, "    "));
                    }
                }
            }

            if i < statements.len() - 1 {
                report.push_str(&empty_box_line());
            }
        }
    }
    report.push_str(&bottom_border());
    report.push('\n');

    report
}

/// Test database wrapper that captures execution context for failure reports
pub mod test_db {
    use super::{CapturedStatement, FailureContext, failure_report};
    use std::ops::{Deref, DerefMut};

    use std::path::PathBuf;
    use std::sync::{Arc, Mutex};

    /// Generic test database wrapper
    pub struct TestDb<D> {
        pub db: D,
        pub driver_name: String,
        pub schema_ddl: Vec<String>,
        // `Arc<Mutex<_>>` (not `RefCell`) so the statements trail can be shared
        // into the `set_hook` panic closure, which requires `Send + Sync`.
        pub statements: Arc<Mutex<Vec<CapturedStatement>>>,
        pub db_path: Option<PathBuf>,
    }

    impl<D> Deref for TestDb<D> {
        type Target = D;
        fn deref(&self) -> &Self::Target {
            &self.db
        }
    }

    impl<D> DerefMut for TestDb<D> {
        fn deref_mut(&mut self) -> &mut Self::Target {
            &mut self.db
        }
    }

    impl<D> Drop for TestDb<D> {
        fn drop(&mut self) {
            if let Some(path) = &self.db_path {
                let _ = std::fs::remove_file(path);
                // Clean up WAL/SHM sidecar files
                let path_str = path.to_string_lossy();
                let _ = std::fs::remove_file(format!("{}-wal", path_str));
                let _ = std::fs::remove_file(format!("{}-shm", path_str));
            }
        }
    }

    impl<D> TestDb<D> {
        pub fn new(db: D, driver_name: impl Into<String>, schema_ddl: Vec<String>) -> Self {
            Self {
                db,
                driver_name: driver_name.into(),
                schema_ddl,
                statements: Arc::new(Mutex::new(Vec::new())),
                db_path: None,
            }
        }

        pub fn with_db_path(mut self, path: PathBuf) -> Self {
            self.db_path = Some(path);
            self
        }

        /// Record a SQL statement execution
        pub fn record(&self, sql: impl Into<String>, error: Option<String>) {
            self.statements.lock().unwrap().push(CapturedStatement {
                sql: sql.into(),
                params: None,
                source: None,
                error,
            });
        }

        /// Record a SQL statement with source expression and params
        pub fn record_sql(&self, source: &str, sql: &str, params: &str, error: Option<String>) {
            self.statements.lock().unwrap().push(CapturedStatement {
                sql: sql.into(),
                params: Some(params.into()),
                source: Some(source.into()),
                error,
            });
        }

        /// Generate a failure report
        pub fn report(
            &self,
            test_name: &str,
            error: &dyn std::fmt::Display,
            expected: Option<&str>,
            actual: Option<&str>,
            failed_operation: Option<&str>,
        ) -> String {
            let stmts = self.statements.lock().unwrap();
            failure_report(&FailureContext {
                driver_name: &self.driver_name,
                test_name,
                error,
                expected,
                actual,
                failed_operation,
                schema_ddl: &self.schema_ddl,
                statements: &stmts,
            })
        }

        /// Panic with a formatted failure report
        pub fn fail(
            &self,
            test_name: &str,
            error: &dyn std::fmt::Display,
            expected: Option<&str>,
            actual: Option<&str>,
        ) -> ! {
            panic!("{}", self.report(test_name, error, expected, actual, None));
        }

        /// Panic with a formatted failure report including the failed operation
        pub fn fail_with_op(
            &self,
            test_name: &str,
            error: &dyn std::fmt::Display,
            failed_operation: &str,
        ) -> ! {
            panic!(
                "{}",
                self.report(test_name, error, None, None, Some(failed_operation))
            );
        }
    }
}

// =============================================================================
// Driver-specific setup modules
// =============================================================================

#[cfg(feature = "rusqlite")]
pub mod rusqlite_setup {
    use super::temp_db_path;
    use super::test_db::TestDb;
    use drizzle::sqlite::rusqlite::Drizzle;
    use drizzle_migrations::{Migration, Tracking};
    use rusqlite::Connection;

    pub fn setup_empty() -> TestDb<Drizzle<()>> {
        let db_path = temp_db_path();
        let conn = Connection::open(&db_path).expect("Failed to create database");
        conn.execute_batch("PRAGMA foreign_keys = ON")
            .expect("Failed to enable foreign keys");
        let (db, _) = Drizzle::new(conn, ());
        TestDb::new(db, "rusqlite", Vec::new()).with_db_path(db_path)
    }

    pub fn setup_empty_db<S: Copy + drizzle::core::SQLSchemaImpl>(
        schema: S,
    ) -> (TestDb<Drizzle<S>>, S) {
        let db_path = temp_db_path();
        let conn = Connection::open(&db_path).expect("Failed to create database");
        conn.execute_batch("PRAGMA foreign_keys = ON")
            .expect("Failed to enable foreign keys");
        let schema_ddl: Vec<_> = schema
            .create_statements()
            .expect("create statements")
            .collect();
        let (db, schema) = Drizzle::new(conn, schema);
        let test_db = TestDb::new(db, "rusqlite", schema_ddl).with_db_path(db_path);
        (test_db, schema)
    }

    pub fn legacy_tracking_columns(conn: &Connection, table: &str) -> Vec<String> {
        let pragma = format!("SELECT name FROM pragma_table_info('{table}') ORDER BY cid");
        let mut stmt = conn.prepare(&pragma).expect("prepare pragma_table_info");
        stmt.query_map([], |row| row.get::<_, String>(0))
            .expect("query pragma_table_info")
            .collect::<Result<Vec<_>, _>>()
            .expect("collect pragma columns")
    }

    pub fn create_legacy_tracking_table(conn: &Connection, table: &str) {
        conn.execute(
            &format!(
                "CREATE TABLE \"{table}\" (id INTEGER PRIMARY KEY AUTOINCREMENT, hash text NOT NULL, created_at numeric)"
            ),
            [],
        )
        .expect("create legacy tracking table");
    }

    pub fn table_exists(conn: &Connection, table: &str) -> i64 {
        conn.query_row(
            "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name = ?1",
            [table],
            |row| row.get(0),
        )
        .expect("query sqlite_master")
    }

    pub fn setup_db<S: Default + drizzle::core::SQLSchemaImpl + Copy>() -> (TestDb<Drizzle<S>>, S) {
        let db_path = temp_db_path();
        let conn = Connection::open(&db_path).expect("Failed to create database");
        conn.execute_batch("PRAGMA foreign_keys = ON")
            .expect("Failed to enable foreign keys");
        let schema = S::default();
        let schema_ddl: Vec<_> = schema
            .create_statements()
            .expect("create statements")
            .collect();
        let (db, schema) = Drizzle::new(conn, schema);
        let migrations = vec![Migration::with_hash(
            "0000_schema_init",
            "schema_init",
            0,
            schema_ddl.clone(),
        )];

        if let Err(e) = db.migrate(&migrations, Tracking::SQLITE) {
            let test_db = TestDb::new(db, "rusqlite", schema_ddl).with_db_path(db_path);
            test_db.fail(
                "schema_creation",
                &e,
                Some("Schema created successfully"),
                None,
            );
        }

        let test_db = TestDb::new(db, "rusqlite", schema_ddl).with_db_path(db_path);
        (test_db, schema)
    }
}

#[cfg(feature = "libsql")]
pub mod libsql_setup {
    use super::temp_db_path;
    use super::test_db::TestDb;
    use drizzle::sqlite::libsql::Drizzle;
    use drizzle_migrations::{Migration, Tracking};
    use libsql::Builder;

    pub async fn setup_empty() -> TestDb<Drizzle<()>> {
        let db_path = temp_db_path();
        let db_path_str = db_path
            .to_str()
            .expect("temporary sqlite path must be valid UTF-8");
        let db = Builder::new_local(db_path_str)
            .build()
            .await
            .expect("build db");
        let conn = db.connect().expect("connect to db");
        conn.execute("PRAGMA foreign_keys = ON", libsql::params![])
            .await
            .expect("Failed to enable foreign keys");
        let (db, _) = Drizzle::new(conn, ());
        TestDb::new(db, "libsql", Vec::new()).with_db_path(db_path)
    }

    pub async fn setup_empty_db<S: Copy + drizzle::core::SQLSchemaImpl>(
        schema: S,
    ) -> (TestDb<Drizzle<S>>, S) {
        let db_path = temp_db_path();
        let db_path_str = db_path
            .to_str()
            .expect("temporary sqlite path must be valid UTF-8");
        let db = Builder::new_local(db_path_str)
            .build()
            .await
            .expect("build db");
        let conn = db.connect().expect("connect to db");
        conn.execute("PRAGMA foreign_keys = ON", libsql::params![])
            .await
            .expect("Failed to enable foreign keys");
        let schema_ddl: Vec<_> = schema
            .create_statements()
            .expect("create statements")
            .collect();
        let (db, schema) = Drizzle::new(conn, schema);
        let test_db = TestDb::new(db, "libsql", schema_ddl).with_db_path(db_path);
        (test_db, schema)
    }

    pub async fn legacy_tracking_columns(conn: &libsql::Connection, table: &str) -> Vec<String> {
        let pragma = format!("SELECT name FROM pragma_table_info('{table}') ORDER BY cid");
        let mut rows = conn
            .query(&pragma, ())
            .await
            .expect("query pragma_table_info");
        let mut columns = Vec::new();
        while let Some(row) = rows.next().await.expect("next pragma row") {
            columns.push(row.get::<String>(0).expect("pragma column name"));
        }
        columns
    }

    pub async fn create_legacy_tracking_table(conn: &libsql::Connection, table: &str) {
        conn.execute(
            &format!(
                "CREATE TABLE \"{table}\" (id INTEGER PRIMARY KEY AUTOINCREMENT, hash text NOT NULL, created_at numeric)"
            ),
            (),
        )
        .await
        .expect("create legacy tracking table");
    }

    pub async fn table_exists(conn: &libsql::Connection, table: &str) -> i64 {
        let mut rows = conn
            .query(
                "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name = ?1",
                libsql::params![table],
            )
            .await
            .expect("query sqlite_master");
        let row = rows
            .next()
            .await
            .expect("next sqlite_master row")
            .expect("sqlite_master row");
        row.get::<i64>(0).expect("sqlite_master count")
    }

    pub async fn setup_db<S: Default + drizzle::core::SQLSchemaImpl + Copy>()
    -> (TestDb<Drizzle<S>>, S) {
        let db_path = temp_db_path();
        let db_path_str = db_path
            .to_str()
            .expect("temporary sqlite path must be valid UTF-8");
        let db = Builder::new_local(db_path_str)
            .build()
            .await
            .expect("build db");
        let conn = db.connect().expect("connect to db");
        conn.execute("PRAGMA foreign_keys = ON", libsql::params![])
            .await
            .expect("Failed to enable foreign keys");
        let schema = S::default();
        let schema_ddl: Vec<_> = schema
            .create_statements()
            .expect("create statements")
            .collect();
        let (db, schema) = Drizzle::new(conn, schema);
        let migrations = vec![Migration::with_hash(
            "0000_schema_init",
            "schema_init",
            0,
            schema_ddl.clone(),
        )];

        if let Err(e) = db.migrate(&migrations, Tracking::SQLITE).await {
            let test_db = TestDb::new(db, "libsql", schema_ddl).with_db_path(db_path);
            test_db.fail(
                "schema_creation",
                &e,
                Some("Schema created successfully"),
                None,
            );
        }

        let test_db = TestDb::new(db, "libsql", schema_ddl).with_db_path(db_path);
        (test_db, schema)
    }
}

#[cfg(feature = "turso")]
pub mod turso_setup {
    use super::temp_db_path;
    use super::test_db::TestDb;
    use drizzle::sqlite::turso::Drizzle;
    use drizzle_migrations::{Migration, Tracking};
    use turso::Builder;

    pub async fn setup_empty() -> TestDb<Drizzle<()>> {
        let db_path = temp_db_path();
        let db_path_str = db_path
            .to_str()
            .expect("temporary sqlite path must be valid UTF-8");
        let db = Builder::new_local(db_path_str)
            .build()
            .await
            .expect("build db");
        let conn = db.connect().expect("connect to db");
        conn.execute("PRAGMA foreign_keys = ON", turso::params![])
            .await
            .expect("Failed to enable foreign keys");
        let (db, _) = Drizzle::new(conn, ());
        TestDb::new(db, "turso", Vec::new()).with_db_path(db_path)
    }

    pub async fn setup_empty_db<S: Copy + drizzle::core::SQLSchemaImpl>(
        schema: S,
    ) -> (TestDb<Drizzle<S>>, S) {
        let db_path = temp_db_path();
        let db_path_str = db_path
            .to_str()
            .expect("temporary sqlite path must be valid UTF-8");
        let db = Builder::new_local(db_path_str)
            .build()
            .await
            .expect("build db");
        let conn = db.connect().expect("connect to db");
        conn.execute("PRAGMA foreign_keys = ON", turso::params![])
            .await
            .expect("Failed to enable foreign keys");
        let schema_ddl: Vec<_> = schema
            .create_statements()
            .expect("create statements")
            .collect();
        let (db, schema) = Drizzle::new(conn, schema);
        let test_db = TestDb::new(db, "turso", schema_ddl).with_db_path(db_path);
        (test_db, schema)
    }

    pub async fn legacy_tracking_columns(conn: &turso::Connection, table: &str) -> Vec<String> {
        let pragma = format!("SELECT name FROM pragma_table_info('{table}') ORDER BY cid");
        let mut rows = conn
            .query(&pragma, ())
            .await
            .expect("query pragma_table_info");
        let mut columns = Vec::new();
        while let Some(row) = rows.next().await.expect("next pragma row") {
            columns.push(row.get::<String>(0).expect("pragma column name"));
        }
        columns
    }

    pub async fn create_legacy_tracking_table(conn: &turso::Connection, table: &str) {
        conn.execute(
            &format!(
                "CREATE TABLE \"{table}\" (id INTEGER PRIMARY KEY AUTOINCREMENT, hash text NOT NULL, created_at numeric)"
            ),
            (),
        )
        .await
        .expect("create legacy tracking table");
    }

    pub async fn table_exists(conn: &turso::Connection, table: &str) -> i64 {
        let mut rows = conn
            .query(
                "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name = ?1",
                turso::params![table],
            )
            .await
            .expect("query sqlite_master");
        let row = rows
            .next()
            .await
            .expect("next sqlite_master row")
            .expect("sqlite_master row");
        row.get::<i64>(0).expect("sqlite_master count")
    }

    pub async fn setup_db<S: Default + drizzle::core::SQLSchemaImpl + Copy>()
    -> (TestDb<Drizzle<S>>, S) {
        let db_path = temp_db_path();
        let db_path_str = db_path
            .to_str()
            .expect("temporary sqlite path must be valid UTF-8");
        let db = Builder::new_local(db_path_str)
            .build()
            .await
            .expect("build db");
        let conn = db.connect().expect("connect to db");
        conn.execute("PRAGMA foreign_keys = ON", turso::params![])
            .await
            .expect("Failed to enable foreign keys");
        let schema = S::default();
        let schema_ddl: Vec<_> = schema
            .create_statements()
            .expect("create statements")
            .collect();
        let (mut db, schema) = Drizzle::new(conn, schema);
        let migrations = vec![Migration::with_hash(
            "0000_schema_init",
            "schema_init",
            0,
            schema_ddl.clone(),
        )];

        if let Err(e) = db.migrate(&migrations, Tracking::SQLITE).await {
            let test_db = TestDb::new(db, "turso", schema_ddl).with_db_path(db_path);
            test_db.fail(
                "schema_creation",
                &e,
                Some("Schema created successfully"),
                None,
            );
        }

        let test_db = TestDb::new(db, "turso", schema_ddl).with_db_path(db_path);
        (test_db, schema)
    }
}

#[cfg(feature = "postgres-sync")]
pub mod postgres_sync_setup {
    use super::{CapturedStatement, FailureContext, failure_report};
    use drizzle::postgres::sync::Drizzle;
    use drizzle_migrations::{Migration, Tracking};
    use postgres::{Client, NoTls};
    use std::ops::{Deref, DerefMut};
    use std::process::Command;
    use std::sync::Once;
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::sync::{Arc, Mutex};
    use std::thread;
    use std::time::Duration;

    static DOCKER_STARTED: Once = Once::new();
    static TEST_COUNTER: AtomicU64 = AtomicU64::new(0);

    fn get_database_url() -> String {
        std::env::var("DATABASE_URL").unwrap_or_else(|_| {
            "host=localhost user=postgres password=postgres dbname=drizzle_test".to_string()
        })
    }

    fn ensure_postgres_running() {
        DOCKER_STARTED.call_once(|| {
            let database_url = get_database_url();

            // Try to connect first
            if Client::connect(&database_url, NoTls).is_ok() {
                println!("PostgreSQL already running");
                return;
            }

            println!("Starting PostgreSQL via Docker Compose...");

            // Start docker compose
            let status = Command::new("docker")
                .args(["compose", "up", "-d", "postgres"])
                .status();

            match status {
                Ok(s) if s.success() => {
                    // Wait for PostgreSQL to be ready
                    println!("Waiting for PostgreSQL to be ready...");
                    for i in 0..30 {
                        thread::sleep(Duration::from_secs(1));
                        if Client::connect(&database_url, NoTls).is_ok() {
                            println!("PostgreSQL is ready! (took {}s)", i + 1);
                            return;
                        }
                    }
                    panic!("PostgreSQL failed to start within 30 seconds");
                }
                Ok(_) => {
                    eprintln!("Docker Compose failed. Make sure Docker is running.");
                    eprintln!("You can manually start with: docker compose up -d postgres");
                }
                Err(e) => {
                    eprintln!("Could not run docker compose: {}", e);
                    eprintln!("Make sure Docker is installed and running.");
                }
            }
        });
    }

    /// Generate a unique schema name for this test
    fn generate_schema_name() -> String {
        let counter = TEST_COUNTER.fetch_add(1, Ordering::SeqCst);
        let thread_id = format!("{:?}", thread::current().id());
        // Extract just the number from ThreadId(X)
        let thread_num: String = thread_id.chars().filter(|c| c.is_ascii_digit()).collect();
        format!("test_{}_{}", thread_num, counter)
    }

    /// Wrapper around Drizzle that automatically cleans up its schema on drop.
    pub struct TestDb<S> {
        pub db: Drizzle<S>,
        schema_name: String,
        schema_ddl: Vec<String>,
        // `Arc<Mutex<_>>` (not `RefCell`) so the statements trail can be shared
        // into the `set_hook` panic closure, which requires `Send + Sync`.
        pub statements: Arc<Mutex<Vec<CapturedStatement>>>,
    }

    impl<S> Deref for TestDb<S> {
        type Target = Drizzle<S>;
        fn deref(&self) -> &Self::Target {
            &self.db
        }
    }

    impl<S> DerefMut for TestDb<S> {
        fn deref_mut(&mut self) -> &mut Self::Target {
            &mut self.db
        }
    }

    impl<S> TestDb<S> {
        pub fn schema_name(&self) -> &str {
            &self.schema_name
        }

        pub fn record(&self, sql: impl Into<String>, error: Option<String>) {
            self.statements.lock().unwrap().push(CapturedStatement {
                sql: sql.into(),
                params: None,
                source: None,
                error,
            });
        }

        pub fn record_sql(&self, source: &str, sql: &str, params: &str, error: Option<String>) {
            self.statements.lock().unwrap().push(CapturedStatement {
                sql: sql.into(),
                params: Some(params.into()),
                source: Some(source.into()),
                error,
            });
        }

        pub fn report(
            &self,
            test_name: &str,
            error: &dyn std::fmt::Display,
            expected: Option<&str>,
            actual: Option<&str>,
            failed_operation: Option<&str>,
        ) -> String {
            let stmts = self.statements.lock().unwrap();
            failure_report(&FailureContext {
                driver_name: "postgres-sync",
                test_name,
                error,
                expected,
                actual,
                failed_operation,
                schema_ddl: &self.schema_ddl,
                statements: &stmts,
            })
        }

        pub fn fail(
            &self,
            test_name: &str,
            error: &dyn std::fmt::Display,
            expected: Option<&str>,
            actual: Option<&str>,
        ) -> ! {
            panic!("{}", self.report(test_name, error, expected, actual, None));
        }

        pub fn fail_with_op(
            &self,
            test_name: &str,
            error: &dyn std::fmt::Display,
            failed_operation: &str,
        ) -> ! {
            panic!(
                "{}",
                self.report(test_name, error, None, None, Some(failed_operation))
            );
        }
    }

    impl<S> Drop for TestDb<S> {
        fn drop(&mut self) {
            // Open a new connection to drop the schema (original is owned by Drizzle)
            if let Ok(mut client) = Client::connect(&get_database_url(), NoTls) {
                let drop_sql = format!("DROP SCHEMA IF EXISTS \"{}\" CASCADE", self.schema_name);
                if let Err(e) = client.batch_execute(&drop_sql) {
                    eprintln!("Failed to drop test schema {}: {}", self.schema_name, e);
                }
            }
        }
    }

    pub fn setup_empty_named(schema_name: impl Into<String>) -> TestDb<()> {
        ensure_postgres_running();

        let database_url = get_database_url();
        let schema_name = schema_name.into();

        let mut client =
            Client::connect(&database_url, NoTls).expect("Failed to connect to PostgreSQL");
        let setup_sql = format!(
            "DROP SCHEMA IF EXISTS \"{}\" CASCADE; CREATE SCHEMA \"{}\"",
            schema_name, schema_name
        );
        client
            .batch_execute(&setup_sql)
            .expect("Failed to create test schema");

        let (db, _) = Drizzle::new(client, ());
        TestDb {
            db,
            schema_name,
            schema_ddl: Vec::new(),
            statements: Arc::new(Mutex::new(Vec::new())),
        }
    }

    pub fn setup_empty_named_db<S: Copy + drizzle::core::SQLSchemaImpl>(
        schema_name: impl Into<String>,
        schema: S,
    ) -> (TestDb<S>, S) {
        ensure_postgres_running();

        let database_url = get_database_url();
        let schema_name = schema_name.into();

        let mut client =
            Client::connect(&database_url, NoTls).expect("Failed to connect to PostgreSQL");
        let setup_sql = format!(
            "DROP SCHEMA IF EXISTS \"{}\" CASCADE; CREATE SCHEMA \"{}\"",
            schema_name, schema_name
        );
        client
            .batch_execute(&setup_sql)
            .expect("Failed to create test schema");

        let schema_ddl: Vec<_> = schema
            .create_statements()
            .expect("create statements")
            .collect();
        let (db, schema) = Drizzle::new(client, schema);
        let test_db = TestDb {
            db,
            schema_name,
            schema_ddl,
            statements: Arc::new(Mutex::new(Vec::new())),
        };
        (test_db, schema)
    }

    pub fn legacy_tracking_columns(client: &mut Client, schema: &str, table: &str) -> Vec<String> {
        client
            .query(
                "SELECT column_name FROM information_schema.columns WHERE table_schema = $1 AND table_name = $2 ORDER BY ordinal_position",
                &[&schema, &table],
            )
            .expect("query information_schema.columns")
            .into_iter()
            .map(|row| row.get::<_, String>(0))
            .collect()
    }

    pub fn create_legacy_tracking_table(client: &mut Client, schema: &str, table: &str) {
        client
            .batch_execute(&format!(
                "CREATE TABLE \"{schema}\".\"{table}\" (id SERIAL PRIMARY KEY, hash TEXT NOT NULL, created_at BIGINT)"
            ))
            .expect("create legacy tracking table");
    }

    pub fn table_exists(client: &mut Client, schema: &str, table: &str) -> i64 {
        client
            .query_one(
                "SELECT COUNT(*)::bigint FROM information_schema.tables WHERE table_schema = $1 AND table_name = $2",
                &[&schema, &table],
            )
            .expect("query information_schema.tables")
            .get(0)
    }

    pub fn setup_db<S: Default + drizzle::core::SQLSchemaImpl + Copy>() -> (TestDb<S>, S) {
        // Ensure PostgreSQL is running (auto-starts via Docker if needed)
        ensure_postgres_running();

        let database_url = get_database_url();
        let schema_name = generate_schema_name();

        let mut client =
            Client::connect(&database_url, NoTls).expect("Failed to connect to PostgreSQL");

        // Create isolated schema for this test and set search_path
        let setup_sql = format!(
            "DROP SCHEMA IF EXISTS \"{}\" CASCADE; CREATE SCHEMA \"{}\"; SET search_path TO \"{}\"",
            schema_name, schema_name, schema_name
        );
        client
            .batch_execute(&setup_sql)
            .expect("Failed to create test schema");

        let schema = S::default();
        let schema_ddl: Vec<_> = schema
            .create_statements()
            .expect("create statements")
            .collect();
        let (mut db, schema) = Drizzle::new(client, schema);

        let migrations = vec![Migration::with_hash(
            "0000_schema_init",
            "schema_init",
            0,
            schema_ddl.clone(),
        )];
        let config = Tracking::POSTGRES.schema(schema_name.clone());

        if let Err(e) = db.migrate(&migrations, config) {
            let test_db = TestDb {
                db,
                schema_name,
                schema_ddl,
                statements: Arc::new(Mutex::new(Vec::new())),
            };
            test_db.fail(
                "schema_creation",
                &e,
                Some("Schema created successfully"),
                None,
            );
        }

        let test_db = TestDb {
            db,
            schema_name,
            schema_ddl,
            statements: Arc::new(Mutex::new(Vec::new())),
        };
        (test_db, schema)
    }
}

#[cfg(feature = "tokio-postgres")]
pub mod tokio_postgres_setup {
    use super::{CapturedStatement, FailureContext, failure_report};
    use drizzle::postgres::tokio::Drizzle;
    use drizzle_migrations::{Migration, Tracking};
    use std::ops::{Deref, DerefMut};
    use std::process::Command;
    use std::sync::Once;
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::sync::{Arc, Mutex};
    use std::thread;
    use std::time::Duration;
    use tokio_postgres::NoTls;

    static DOCKER_STARTED: Once = Once::new();
    static TEST_COUNTER: AtomicU64 = AtomicU64::new(0);

    fn get_database_url() -> String {
        std::env::var("DATABASE_URL").unwrap_or_else(|_| {
            "host=localhost user=postgres password=postgres dbname=drizzle_test".to_string()
        })
    }

    /// Check if postgres is reachable (runs on a separate thread with its own runtime)
    fn check_postgres_available(database_url: &str) -> bool {
        let url = database_url.to_string();
        thread::spawn(move || {
            let rt = match tokio::runtime::Runtime::new() {
                Ok(rt) => rt,
                Err(_) => return false,
            };
            rt.block_on(async move { tokio_postgres::connect(&url, NoTls).await.is_ok() })
        })
        .join()
        .unwrap_or(false)
    }

    fn ensure_postgres_running() {
        DOCKER_STARTED.call_once(|| {
            let database_url = get_database_url();

            // Try to connect using tokio-postgres on separate thread
            if check_postgres_available(&database_url) {
                println!("PostgreSQL already running");
                return;
            }

            println!("Starting PostgreSQL via Docker Compose...");

            let status = Command::new("docker")
                .args(["compose", "up", "-d", "postgres"])
                .status();

            match status {
                Ok(s) if s.success() => {
                    println!("Waiting for PostgreSQL to be ready...");
                    for i in 0..30 {
                        thread::sleep(Duration::from_secs(1));
                        if check_postgres_available(&database_url) {
                            println!("PostgreSQL is ready! (took {}s)", i + 1);
                            return;
                        }
                    }
                    panic!("PostgreSQL failed to start within 30 seconds");
                }
                Ok(_) => {
                    eprintln!("Docker Compose failed. Make sure Docker is running.");
                    eprintln!("You can manually start with: docker compose up -d postgres");
                }
                Err(e) => {
                    eprintln!("Could not run docker compose: {}", e);
                    eprintln!("Make sure Docker is installed and running.");
                }
            }
        });
    }

    fn generate_schema_name() -> String {
        let counter = TEST_COUNTER.fetch_add(1, Ordering::SeqCst);
        let thread_id = format!("{:?}", thread::current().id());
        let thread_num: String = thread_id.chars().filter(|c| c.is_ascii_digit()).collect();
        format!("test_async_{}_{}", thread_num, counter)
    }

    /// Wrapper around Drizzle that automatically cleans up its schema on drop.
    pub struct TestDb<S> {
        pub db: Drizzle<S>,
        schema_name: String,
        schema_ddl: Vec<String>,
        // `Arc<Mutex<_>>` (not `RefCell`) so the statements trail can be shared
        // into the `set_hook` panic closure, which requires `Send + Sync`.
        pub statements: Arc<Mutex<Vec<CapturedStatement>>>,
    }

    impl<S> Deref for TestDb<S> {
        type Target = Drizzle<S>;
        fn deref(&self) -> &Self::Target {
            &self.db
        }
    }

    impl<S> DerefMut for TestDb<S> {
        fn deref_mut(&mut self) -> &mut Self::Target {
            &mut self.db
        }
    }

    impl<S> TestDb<S> {
        pub fn schema_name(&self) -> &str {
            &self.schema_name
        }

        pub fn record(&self, sql: impl Into<String>, error: Option<String>) {
            self.statements.lock().unwrap().push(CapturedStatement {
                sql: sql.into(),
                params: None,
                source: None,
                error,
            });
        }

        pub fn record_sql(&self, source: &str, sql: &str, params: &str, error: Option<String>) {
            self.statements.lock().unwrap().push(CapturedStatement {
                sql: sql.into(),
                params: Some(params.into()),
                source: Some(source.into()),
                error,
            });
        }

        pub fn report(
            &self,
            test_name: &str,
            error: &dyn std::fmt::Display,
            expected: Option<&str>,
            actual: Option<&str>,
            failed_operation: Option<&str>,
        ) -> String {
            let stmts = self.statements.lock().unwrap();
            failure_report(&FailureContext {
                driver_name: "tokio-postgres",
                test_name,
                error,
                expected,
                actual,
                failed_operation,
                schema_ddl: &self.schema_ddl,
                statements: &stmts,
            })
        }

        pub fn fail(
            &self,
            test_name: &str,
            error: &dyn std::fmt::Display,
            expected: Option<&str>,
            actual: Option<&str>,
        ) -> ! {
            panic!("{}", self.report(test_name, error, expected, actual, None));
        }

        pub fn fail_with_op(
            &self,
            test_name: &str,
            error: &dyn std::fmt::Display,
            failed_operation: &str,
        ) -> ! {
            panic!(
                "{}",
                self.report(test_name, error, None, None, Some(failed_operation))
            );
        }
    }

    impl<S> Drop for TestDb<S> {
        fn drop(&mut self) {
            let schema_name = self.schema_name.clone();
            let database_url = get_database_url();

            // Spawn a thread with its own tokio runtime for async cleanup
            let _ = thread::spawn(move || {
                let rt = tokio::runtime::Runtime::new().expect("Failed to create cleanup runtime");
                rt.block_on(async move {
                    if let Ok((client, connection)) =
                        tokio_postgres::connect(&database_url, NoTls).await
                    {
                        // Spawn connection handler (fire and forget)
                        tokio::spawn(async move {
                            let _ = connection.await;
                        });

                        let drop_sql = format!("DROP SCHEMA IF EXISTS \"{}\" CASCADE", schema_name);
                        if let Err(e) = client.batch_execute(&drop_sql).await {
                            eprintln!("Failed to drop test schema {}: {}", schema_name, e);
                        }
                    }
                });
            })
            .join();
        }
    }

    pub async fn setup_empty_named(schema_name: impl Into<String>) -> TestDb<()> {
        ensure_postgres_running();

        let database_url = get_database_url();
        let schema_name = schema_name.into();

        let (client, connection) = tokio_postgres::connect(&database_url, NoTls)
            .await
            .expect("Failed to connect to PostgreSQL");

        tokio::spawn(async move {
            if let Err(e) = connection.await {
                eprintln!("PostgreSQL connection error: {}", e);
            }
        });

        let setup_sql = format!(
            "DROP SCHEMA IF EXISTS \"{}\" CASCADE; CREATE SCHEMA \"{}\"",
            schema_name, schema_name
        );
        client
            .batch_execute(&setup_sql)
            .await
            .expect("Failed to create test schema");

        let (db, _) = Drizzle::new(client, ());
        TestDb {
            db,
            schema_name,
            schema_ddl: Vec::new(),
            statements: Arc::new(Mutex::new(Vec::new())),
        }
    }

    pub async fn setup_empty_named_db<S: Copy + drizzle::core::SQLSchemaImpl>(
        schema_name: impl Into<String>,
        schema: S,
    ) -> (TestDb<S>, S) {
        ensure_postgres_running();

        let database_url = get_database_url();
        let schema_name = schema_name.into();

        let (client, connection) = tokio_postgres::connect(&database_url, NoTls)
            .await
            .expect("Failed to connect to PostgreSQL");

        tokio::spawn(async move {
            if let Err(e) = connection.await {
                eprintln!("PostgreSQL connection error: {}", e);
            }
        });

        let setup_sql = format!(
            "DROP SCHEMA IF EXISTS \"{}\" CASCADE; CREATE SCHEMA \"{}\"",
            schema_name, schema_name
        );
        client
            .batch_execute(&setup_sql)
            .await
            .expect("Failed to create test schema");

        let schema_ddl: Vec<_> = schema
            .create_statements()
            .expect("create statements")
            .collect();
        let (db, schema) = Drizzle::new(client, schema);
        let test_db = TestDb {
            db,
            schema_name,
            schema_ddl,
            statements: Arc::new(Mutex::new(Vec::new())),
        };
        (test_db, schema)
    }

    pub async fn legacy_tracking_columns(
        client: &tokio_postgres::Client,
        schema: &str,
        table: &str,
    ) -> Vec<String> {
        client
            .query(
                "SELECT column_name FROM information_schema.columns WHERE table_schema = $1 AND table_name = $2 ORDER BY ordinal_position",
                &[&schema, &table],
            )
            .await
            .expect("query information_schema.columns")
            .into_iter()
            .map(|row| row.get::<_, String>(0))
            .collect()
    }

    pub async fn create_legacy_tracking_table(
        client: &tokio_postgres::Client,
        schema: &str,
        table: &str,
    ) {
        client
            .batch_execute(&format!(
                "CREATE TABLE \"{schema}\".\"{table}\" (id SERIAL PRIMARY KEY, hash TEXT NOT NULL, created_at BIGINT)"
            ))
            .await
            .expect("create legacy tracking table");
    }

    pub async fn table_exists(client: &tokio_postgres::Client, schema: &str, table: &str) -> i64 {
        client
            .query_one(
                "SELECT COUNT(*)::bigint FROM information_schema.tables WHERE table_schema = $1 AND table_name = $2",
                &[&schema, &table],
            )
            .await
            .expect("query information_schema.tables")
            .get(0)
    }

    pub async fn setup_db<S: Default + drizzle::core::SQLSchemaImpl + Copy>() -> (TestDb<S>, S) {
        // Ensure PostgreSQL is running (auto-starts via Docker if needed)
        ensure_postgres_running();

        let database_url = get_database_url();
        let schema_name = generate_schema_name();

        // Connect using tokio-postgres
        let (client, connection) = tokio_postgres::connect(&database_url, NoTls)
            .await
            .expect("Failed to connect to PostgreSQL");

        // Spawn the connection handler
        tokio::spawn(async move {
            if let Err(e) = connection.await {
                eprintln!("PostgreSQL connection error: {}", e);
            }
        });

        // Create isolated schema for this test and set search_path
        let setup_sql = format!(
            "DROP SCHEMA IF EXISTS \"{}\" CASCADE; CREATE SCHEMA \"{}\"; SET search_path TO \"{}\"",
            schema_name, schema_name, schema_name
        );
        client
            .batch_execute(&setup_sql)
            .await
            .expect("Failed to create test schema");

        let schema = S::default();
        let schema_ddl: Vec<_> = schema
            .create_statements()
            .expect("create statements")
            .collect();
        let (mut db, schema) = Drizzle::new(client, schema);
        let migrations = vec![Migration::with_hash(
            "0000_schema_init",
            "schema_init",
            0,
            schema_ddl.clone(),
        )];
        let config = Tracking::POSTGRES.schema(schema_name.clone());

        if let Err(e) = db.migrate(&migrations, config).await {
            let test_db = TestDb {
                db,
                schema_name,
                schema_ddl,
                statements: Arc::new(Mutex::new(Vec::new())),
            };
            test_db.fail(
                "schema_creation",
                &e,
                Some("Schema created successfully"),
                None,
            );
        }

        let test_db = TestDb {
            db,
            schema_name,
            schema_ddl,
            statements: Arc::new(Mutex::new(Vec::new())),
        };
        (test_db, schema)
    }
}