rustio-core 1.10.0

RustIO runtime library: HTTP, router, Postgres ORM, admin, RBAC, search, migrations, AI planner.
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
//! Phase 14, commit 5 — bridge from `ModelSchema` to admin metadata.
//!
//! This module is the framework's first real consumer of the
//! Phase 14 schema contract. Given a `&ModelSchema` produced by
//! `#[derive(RustioModel)]`, it emits the per-column admin
//! metadata required by the existing admin UI without a hand-
//! written `AdminModel` impl.
//!
//! # What stays untouched
//!
//! Existing manual admin paths (the `#[derive(RustioAdmin)]`
//! macro and projects that hand-build an `AdminModel`) are not
//! affected. This module is **additive** — it produces values
//! that consumers can plug into the existing `AdminEntry`
//! constructor; it never modifies, replaces, or shadows any
//! existing admin type.
//!
//! # Mapping rules (Phase 14, commit 5 spec)
//!
//! For each `ModelColumn`:
//!
//! | Contract field      | Bridge output                              |
//! |---------------------|--------------------------------------------|
//! | `name`              | `AdminField.name` (verbatim)               |
//! | `admin_label`       | `AdminField.label` (fallback = `name`)     |
//! | `admin_widget`      | `BridgedField.widget` (preserved through)  |
//! | `flags.searchable`  | `BridgedField.searchable`                  |
//! | `flags.filterable`  | `BridgedField.filterable`                  |
//! | `flags.sortable`    | `BridgedField.sortable`                    |
//! | `flags.readonly`    | `BridgedField.readonly` + `editable=!ro`   |
//! | `primary_key`       | `BridgedField.primary_key`                 |
//!
//! `AdminField` (the existing type) only models `editable`. The
//! remaining flag bits and the widget hint live on
//! `BridgedField` — a side-channel struct so consumers (search
//! indexer, list/sort UI, future renderer changes) can read them
//! without breaking `AdminField`'s shape.
//!
//! # Static lifetimes via `Box::leak`
//!
//! `AdminField` requires `&'static str` and an `&'static
//! [AdminField]` slice (the existing macro emits compile-time
//! constants). When bridging at runtime, we promote owned data
//! to static via `Box::leak`. This is a one-time setup cost
//! equivalent to a `static`: schemas are registered at process
//! startup and live for the program's lifetime, so leaked memory
//! is never reclaimed but never grows either.
//!
//! # No DB, no reflection, no new deps
//!
//! Pure CPU. No async, no database access, no `unsafe`, no new
//! `Cargo.toml` entries.

use crate::admin::types::{AdminField, FieldType};
use crate::contract::{ModelColumn, ModelSchema, RustType};

// ---------------------------------------------------------------------------
// FieldType mapping
// ---------------------------------------------------------------------------

/// Map a contract column's `(RustType, nullable)` pair to the
/// admin's `FieldType` vocabulary.
///
/// Variants the admin layer doesn't model natively (`F64`,
/// `Decimal`, `JsonValue`, `Uuid`) fall through to
/// `String` / `OptionalString` — admin renders them as text
/// inputs, which preserves their values without inventing
/// widgets that don't exist yet. Future commits may extend
/// `FieldType` with dedicated variants; until then text input
/// is the safe minimum.
pub fn field_type_for(col: &ModelColumn) -> FieldType {
    // Match exhaustively — `RustType` is `#[non_exhaustive]` only
    // cross-crate, but inside `rustio-core` it's exhaustive. Keeping
    // the match tight means adding a future variant fails compilation
    // here until the bridge gets an explicit mapping; a wildcard
    // would silently fall back to text input and mask the gap.
    use RustType::*;
    match col.rust_type {
        // The admin's `FieldType` has no `OptionalI32` variant; a
        // nullable `i32` column collapses to `OptionalI64` since
        // both render as the same numeric input. Non-nullable
        // `i32` keeps its dedicated variant.
        I32 if col.nullable => FieldType::OptionalI64,
        I32 => FieldType::I32,
        I64 if col.nullable => FieldType::OptionalI64,
        I64 => FieldType::I64,
        // `Bool` has no nullable variant in the admin layer; a
        // tri-state checkbox isn't part of the existing UI, so
        // nullable bools render as the same checkbox (NULL is
        // treated as `false` at form-submission time).
        Bool => FieldType::Bool,
        String if col.nullable => FieldType::OptionalString,
        String => FieldType::String,
        DateTimeUtc if col.nullable => FieldType::OptionalDateTime,
        DateTimeUtc => FieldType::DateTime,
        // Variants the admin layer doesn't model natively — `F64`,
        // `Decimal`, `JsonValue`, `Uuid` — collapse to text inputs
        // (`String` / `OptionalString`). Documented behaviour;
        // a future commit may extend `FieldType` with dedicated
        // variants and tighten these.
        F64 | Decimal | JsonValue | Uuid if col.nullable => FieldType::OptionalString,
        F64 | Decimal | JsonValue | Uuid => FieldType::String,
    }
}

// ---------------------------------------------------------------------------
// Label resolution
// ---------------------------------------------------------------------------

/// Resolved admin label.
///
/// Phase 15 / commit 9 polish: when no explicit
/// `#[rustio(label = "...")]` is set, derive a friendly default
/// rather than echoing the raw column name:
///
/// 1. Strip a trailing `_id` foreign-key suffix when the
///    remainder is non-empty (`client_id` → `client` →
///    `Client`). The bare `id` PK column is left intact.
/// 2. Translate snake_case to Title Case
///    (`full_name` → `Full Name`).
///
/// Explicit overrides win — projects that want lowercase or
/// punctuated labels keep them by setting
/// `#[rustio(label = "...")]`.
///
/// The derived string is `Box::leak`'d so the result stays
/// `&'static str` for `AdminField.label`. One-time setup cost
/// equivalent to a `static`.
pub fn label_for(col: &ModelColumn) -> &'static str {
    if let Some(explicit) = col.admin_label {
        return explicit;
    }
    let stem = strip_id_suffix(col.name);
    let humanised = humanise_label(stem);
    Box::leak(humanised.into_boxed_str())
}

/// Strip a trailing `_id` suffix only when the remainder is
/// non-empty. The bare `id` PK column round-trips unchanged.
fn strip_id_suffix(name: &str) -> &str {
    name.strip_suffix("_id")
        .filter(|s| !s.is_empty())
        .unwrap_or(name)
}

/// snake_case → Title Case (every word capitalised). Mirrors
/// `humanise_table` but kept separate so the column-label and
/// table-name code paths can evolve independently.
fn humanise_label(name: &str) -> std::string::String {
    let mut out = std::string::String::with_capacity(name.len());
    let mut next_upper = true;
    for ch in name.chars() {
        if ch == '_' {
            out.push(' ');
            next_upper = true;
        } else if next_upper {
            out.extend(ch.to_uppercase());
            next_upper = false;
        } else {
            out.push(ch);
        }
    }
    out
}

// ---------------------------------------------------------------------------
// BridgedField
// ---------------------------------------------------------------------------

/// One column in its bridge form: the existing `AdminField`
/// (consumed verbatim by the admin UI) plus the column-level
/// flags `AdminField` doesn't model.
///
/// Consumers:
/// - The admin renderer plucks `.field` out for `AdminEntry`.
/// - A search-index sync layer (commit 6) reads `.searchable`.
/// - Future filter/sort UI reads `.filterable` / `.sortable`.
/// - The `.primary_key` bit identifies the row-id column for
///   any code that needs it without re-scanning the schema.
#[derive(Debug, Clone)]
pub struct BridgedField {
    /// The existing-shape admin field. Plug this directly into
    /// `AdminEntry.fields` (after `Box::leak`-ing the slice).
    pub field: AdminField,
    /// `true` when the source column has `primary_key = true`.
    /// Mirrors `ModelColumn.primary_key`.
    pub primary_key: bool,
    /// `flags.searchable` from the source column.
    pub searchable: bool,
    /// `flags.filterable` from the source column.
    pub filterable: bool,
    /// `flags.sortable` from the source column.
    pub sortable: bool,
    /// `flags.readonly` from the source column. Also drives
    /// `field.editable = !readonly`.
    pub readonly: bool,
    /// `admin_widget` from the source column, preserved
    /// verbatim. `AdminField` doesn't carry a widget override
    /// today; the existing renderer derives the widget from
    /// `FieldType.widget()`. Holding the override here lets
    /// future renderer code consult it without altering
    /// `AdminField`'s shape.
    pub widget: Option<&'static str>,
}

impl BridgedField {
    /// Phase 15 / commit 9 polish — effective form widget.
    ///
    /// Resolves to the first available answer:
    /// 1. Explicit `admin_widget` from the source column.
    /// 2. Name-based inference: `email` / `*_email` →
    ///    `"email"`; `phone` / `tel` / `*_phone` / `*_tel` →
    ///    `"tel"`; `url` / `*_url` / `*_uri` → `"url"`;
    ///    `password` / `passwd` / `*_password` →
    ///    `"password"`.
    /// 3. `None` — the renderer falls back to
    ///    `FieldType.widget()` (the existing default).
    ///
    /// Inference is intentionally conservative: only column
    /// names that are *unambiguous* matches return a hint,
    /// to avoid e.g. a column called `description` getting
    /// "url" because someone embedded a URL in their schema
    /// docs.
    pub fn effective_widget(&self) -> Option<&'static str> {
        if let Some(explicit) = self.widget {
            return Some(explicit);
        }
        let name = self.field.name;
        if name == "email" || name.ends_with("_email") {
            return Some("email");
        }
        if name == "phone"
            || name == "tel"
            || name.ends_with("_phone")
            || name.ends_with("_tel")
        {
            return Some("tel");
        }
        if name == "url" || name.ends_with("_url") || name.ends_with("_uri") {
            return Some("url");
        }
        if name == "password" || name == "passwd" || name.ends_with("_password") {
            return Some("password");
        }
        None
    }
}

// ---------------------------------------------------------------------------
// Public bridge API
// ---------------------------------------------------------------------------

/// Bridge every column in declaration order. Order is
/// preserved 1:1 with `schema.columns` — the admin UI lists
/// columns in the order the model declared them, and skipping
/// or reordering would silently change rendered forms.
pub fn bridged_fields_from_schema(schema: &ModelSchema) -> Vec<BridgedField> {
    schema
        .columns
        .iter()
        .map(|col| BridgedField {
            field: AdminField {
                name: col.name,
                label: label_for(col),
                field_type: field_type_for(col),
                editable: !col.flags.readonly,
                relation: None,
                choices: None,
            },
            primary_key: col.primary_key,
            searchable: col.flags.searchable,
            filterable: col.flags.filterable,
            sortable: col.flags.sortable,
            readonly: col.flags.readonly,
            widget: col.admin_widget,
        })
        .collect()
}

/// Static-leaked `&'static [AdminField]` for direct use as
/// `AdminEntry.fields`. Equivalent to a `static` array — the
/// memory is allocated once and lives the program's lifetime.
pub fn admin_fields_from_schema(schema: &ModelSchema) -> &'static [AdminField] {
    let fields: Vec<AdminField> = bridged_fields_from_schema(schema)
        .into_iter()
        .map(|b| b.field)
        .collect();
    Box::leak(fields.into_boxed_slice())
}

/// The schema's primary-key column, located by the
/// `primary_key = true` flag. Returns `None` when no column
/// is flagged (a malformed schema; the validator in commit 3
/// surfaces this as `WrongPrimaryKey`).
pub fn primary_key_column(schema: &ModelSchema) -> Option<&ModelColumn> {
    schema.columns.iter().find(|c| c.primary_key)
}

// ---------------------------------------------------------------------------
// SchemaOps — Phase 14, commit 8
// ---------------------------------------------------------------------------
//
// `SchemaOps` is a generic `AdminOps` implementation that drives
// CRUD using only a `ModelSchema` — no `AdminModel` impl, no
// `Model` impl, no per-type code. The admin runtime registers
// schema-driven entries via `Admin::from_schema::<T>()`, and the
// resulting `AdminEntry` ferries CRUD through this type.
//
// SQL is built dynamically from the schema's column list. Type
// dispatch is via `ModelColumn::rust_type` — every supported
// `RustType` variant maps to one read path
// (`format_pg_value_for_column`) and one write path
// (`bind_form_value`). Variants the framework doesn't yet model
// natively for the admin path return a clear validation error
// rather than silently coercing to text.
//
// Constraint envelope:
// - No new dependencies (sqlx, chrono, uuid, serde_json are
//   already pulled in via rustio-core's Cargo.toml).
// - Read-only against schema metadata; write paths only modify
//   rows in the model's own table.
// - The SQL strings are built from `ModelSchema`'s `&'static
//   str` column / table names — there is no path for a request
//   to inject arbitrary identifiers (the column name list is
//   defined at compile time by `#[derive(RustioModel)]`).

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use chrono::{DateTime, Utc};
use sqlx::Row as SqlxRow;

use crate::admin::types::{AdminEntry, AdminOps, EditRow, ListRow};
use crate::contract::HasSchema;
use crate::error::{Error, Result};
use crate::http::FormData;
use crate::orm::Db;

/// Static-leaked `ModelSchema`. Required because `AdminEntry`
/// stores `&'static str` for table / admin_name / etc., and the
/// schema needs to outlive every async future spawned from
/// `SchemaOps`. Schemas are registered at startup and live for
/// the program's lifetime, so the leak is a one-time setup cost
/// equivalent to a `static`.
fn leak_schema(schema: ModelSchema) -> &'static ModelSchema {
    Box::leak(Box::new(schema))
}

/// `AdminOps` driven entirely by a `ModelSchema`.
///
/// Holds a static-leaked schema so each async `AdminOps` method
/// can borrow the column list across `await` points without
/// lifetime issues — `'a` references the captured `&'a self`,
/// but the underlying schema reference is `'static`.
pub(crate) struct SchemaOps {
    schema: &'static ModelSchema,
}

impl SchemaOps {
    fn new(schema: &'static ModelSchema) -> Self {
        Self { schema }
    }

    fn pk_col(&self) -> &'static crate::contract::ModelColumn {
        // The schema's `primary_key` field names the PK column;
        // primary_key_column finds the entry flagged
        // `primary_key = true`. We trust both agree (the
        // validator surfaces drift) and prefer the latter.
        primary_key_column(self.schema).unwrap_or_else(|| {
            // Defensive: a schema without any flagged PK column
            // is a contract bug. Returning the first column
            // makes the code defensible without panicking; the
            // validator's `WrongPrimaryKey` issue catches it
            // separately.
            &self.schema.columns[0]
        })
    }

    /// Columns the create/update path writes. Excludes the
    /// primary key (assumed BIGSERIAL — auto-assigned by PG)
    /// and any column flagged `readonly` (e.g. `created_at
    /// DEFAULT NOW()`). Returns the column references in
    /// declaration order.
    fn writable_columns(&self) -> Vec<&'static crate::contract::ModelColumn> {
        self.schema
            .columns
            .iter()
            .filter(|c| !c.primary_key && !c.flags.readonly)
            .collect()
    }
}

// ---------------------------------------------------------------------------
// Per-RustType read formatting — turns a sqlx row column into a
// String suitable for `ListRow.cells` / `EditRow.values`.
// ---------------------------------------------------------------------------

fn format_pg_value_for_column(
    row: &sqlx::postgres::PgRow,
    col: &crate::contract::ModelColumn,
) -> String {
    // Centralised null handling: any column read that errors out
    // OR returns NULL maps to the empty string. The render layer
    // displays empty strings as "—" already.
    use crate::contract::RustType::*;
    match (col.rust_type, col.nullable) {
        (I32, false) => row.try_get::<i32, _>(col.name).map(|v| v.to_string()).unwrap_or_default(),
        (I32, true) => row
            .try_get::<Option<i32>, _>(col.name)
            .ok()
            .flatten()
            .map(|v| v.to_string())
            .unwrap_or_default(),
        (I64, false) => row.try_get::<i64, _>(col.name).map(|v| v.to_string()).unwrap_or_default(),
        (I64, true) => row
            .try_get::<Option<i64>, _>(col.name)
            .ok()
            .flatten()
            .map(|v| v.to_string())
            .unwrap_or_default(),
        (Bool, false) => row.try_get::<bool, _>(col.name).map(|b| b.to_string()).unwrap_or_default(),
        (Bool, true) => row
            .try_get::<Option<bool>, _>(col.name)
            .ok()
            .flatten()
            .map(|b| b.to_string())
            .unwrap_or_default(),
        (String, false) => row.try_get::<std::string::String, _>(col.name).unwrap_or_default(),
        (String, true) => row
            .try_get::<Option<std::string::String>, _>(col.name)
            .ok()
            .flatten()
            .unwrap_or_default(),
        (DateTimeUtc, false) => row
            .try_get::<DateTime<Utc>, _>(col.name)
            .map(|d| d.to_rfc3339())
            .unwrap_or_default(),
        (DateTimeUtc, true) => row
            .try_get::<Option<DateTime<Utc>>, _>(col.name)
            .ok()
            .flatten()
            .map(|d| d.to_rfc3339())
            .unwrap_or_default(),
        (F64, false) => row.try_get::<f64, _>(col.name).map(|v| v.to_string()).unwrap_or_default(),
        (F64, true) => row
            .try_get::<Option<f64>, _>(col.name)
            .ok()
            .flatten()
            .map(|v| v.to_string())
            .unwrap_or_default(),
        (Uuid, false) => row
            .try_get::<uuid::Uuid, _>(col.name)
            .map(|u| u.to_string())
            .unwrap_or_default(),
        (Uuid, true) => row
            .try_get::<Option<uuid::Uuid>, _>(col.name)
            .ok()
            .flatten()
            .map(|u| u.to_string())
            .unwrap_or_default(),
        // Decimal and JsonValue: render the raw text the DB
        // returns rather than parsing into a typed value the
        // admin layer can't carry without an extra dep. PG
        // exposes both as text-coercible — `::text` cast in the
        // query would be cleaner, but reading as String works
        // for the common shapes.
        (Decimal, _) | (JsonValue, _) => row
            .try_get::<std::string::String, _>(col.name)
            .unwrap_or_default(),
    }
}

// ---------------------------------------------------------------------------
// Per-RustType write parsing — turns a form value string into a
// SQL bind argument; emits a clear validation error on parse
// failure rather than panicking.
// ---------------------------------------------------------------------------

/// Bind one form value onto a `sqlx::query` builder, dispatched
/// by `RustType` + nullability. Returns the updated builder on
/// success, or a string error suitable for the `Err(Vec<String>)`
/// validation channel of `AdminOps::create` / `update`.
///
/// Empty form input on a nullable column binds `NULL`. Empty
/// form input on a non-nullable column binds the empty string
/// (for `String`) or returns a "required" error (for typed
/// columns).
fn bind_form_value<'a>(
    q: sqlx::query::Query<'a, sqlx::Postgres, sqlx::postgres::PgArguments>,
    col: &crate::contract::ModelColumn,
    raw: Option<&str>,
) -> std::result::Result<sqlx::query::Query<'a, sqlx::Postgres, sqlx::postgres::PgArguments>, std::string::String> {
    use crate::contract::RustType::*;
    let raw = raw.unwrap_or("").trim();

    // Empty input + nullable column = NULL. Empty input +
    // String column = empty string (the DB constraint catches
    // NOT NULL TEXT fields when they should have content).
    if raw.is_empty() && col.nullable {
        return Ok(match col.rust_type {
            I32 => q.bind(None::<i32>),
            I64 => q.bind(None::<i64>),
            F64 => q.bind(None::<f64>),
            Bool => q.bind(None::<bool>),
            String => q.bind(None::<std::string::String>),
            DateTimeUtc => q.bind(None::<DateTime<Utc>>),
            Uuid => q.bind(None::<uuid::Uuid>),
            // Decimal / JsonValue null-binding goes through the
            // text path; PG accepts NULL casts at the protocol
            // level for any column.
            Decimal | JsonValue => q.bind(None::<std::string::String>),
        });
    }

    let parsed: std::result::Result<sqlx::query::Query<'a, sqlx::Postgres, sqlx::postgres::PgArguments>, std::string::String> = match col.rust_type {
        I32 => raw
            .parse::<i32>()
            .map(|v| q.bind(v))
            .map_err(|e| format!("`{}`: {}", col.name, e)),
        I64 => raw
            .parse::<i64>()
            .map(|v| q.bind(v))
            .map_err(|e| format!("`{}`: {}", col.name, e)),
        F64 => raw
            .parse::<f64>()
            .map(|v| q.bind(v))
            .map_err(|e| format!("`{}`: {}", col.name, e)),
        Bool => Ok({
            // HTML form checkboxes send "on" / "true" / "1" when
            // checked, nothing when unchecked. The form layer
            // normalises absent fields to None — by the time we
            // see a string here it's almost always "on" for
            // truthy. Unknown tokens default to false rather
            // than rejecting outright; the column's `NOT NULL
            // DEFAULT FALSE` semantics match.
            let truthy = matches!(
                raw.to_ascii_lowercase().as_str(),
                "on" | "true" | "1" | "yes"
            );
            q.bind(truthy)
        }),
        String => Ok(q.bind(raw.to_string())),
        DateTimeUtc => DateTime::parse_from_rfc3339(raw)
            .map(|dt| q.bind(dt.with_timezone(&Utc)))
            .map_err(|e| format!("`{}`: expected RFC3339 timestamp ({})", col.name, e)),
        Uuid => uuid::Uuid::parse_str(raw)
            .map(|u| q.bind(u))
            .map_err(|e| format!("`{}`: {}", col.name, e)),
        Decimal | JsonValue => Ok(q.bind(raw.to_string())),
    };

    parsed
}

// ---------------------------------------------------------------------------
// AdminOps — the read + write surface
// ---------------------------------------------------------------------------

type CreateFut<'a> = Pin<Box<dyn Future<Output = Result<std::result::Result<i64, Vec<std::string::String>>>> + Send + 'a>>;
type UpdateFut<'a> = Pin<Box<dyn Future<Output = Result<std::result::Result<(), Vec<std::string::String>>>> + Send + 'a>>;

impl AdminOps for SchemaOps {
    fn list<'a>(
        &'a self,
        db: &'a Db,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<ListRow>>> + Send + 'a>> {
        Box::pin(async move {
            let pk = self.pk_col();
            let cols = self
                .schema
                .columns
                .iter()
                .map(|c| c.name)
                .collect::<Vec<_>>()
                .join(", ");
            let sql = format!(
                "SELECT {cols} FROM {} ORDER BY {} DESC LIMIT 200",
                self.schema.table, pk.name
            );
            let rows = sqlx::query(&sql)
                .fetch_all(db.pool())
                .await
                .map_err(|e| Error::Internal(format!("schema-list({}): {e}", self.schema.table)))?;

            let out = rows
                .into_iter()
                .map(|row| {
                    // ID column comes back as i64 (BIGSERIAL); fall
                    // back to 0 if the column is shaped differently.
                    let id = row.try_get::<i64, _>(pk.name).unwrap_or(0);
                    let cells = self
                        .schema
                        .columns
                        .iter()
                        .map(|c| format_pg_value_for_column(&row, c))
                        .collect();
                    ListRow { id, cells }
                })
                .collect();
            Ok(out)
        })
    }

    fn find_row<'a>(
        &'a self,
        db: &'a Db,
        id: i64,
    ) -> Pin<Box<dyn Future<Output = Result<Option<EditRow>>> + Send + 'a>> {
        Box::pin(async move {
            let pk = self.pk_col();
            let cols = self
                .schema
                .columns
                .iter()
                .map(|c| c.name)
                .collect::<Vec<_>>()
                .join(", ");
            let sql = format!(
                "SELECT {cols} FROM {} WHERE {} = $1",
                self.schema.table, pk.name
            );
            let maybe_row = sqlx::query(&sql)
                .bind(id)
                .fetch_optional(db.pool())
                .await
                .map_err(|e| Error::Internal(format!("schema-find({}): {e}", self.schema.table)))?;
            Ok(maybe_row.map(|row| {
                let values = self
                    .schema
                    .columns
                    .iter()
                    .map(|c| (c.name.to_string(), format_pg_value_for_column(&row, c)))
                    .collect();
                EditRow { id, values }
            }))
        })
    }

    fn create<'a>(&'a self, db: &'a Db, form: &'a FormData) -> CreateFut<'a> {
        Box::pin(async move {
            let pk = self.pk_col();
            let writables = self.writable_columns();
            let col_names: Vec<&str> = writables.iter().map(|c| c.name).collect();
            let placeholders: Vec<std::string::String> =
                (1..=writables.len()).map(|i| format!("${i}")).collect();
            let sql = format!(
                "INSERT INTO {} ({}) VALUES ({}) RETURNING {}",
                self.schema.table,
                col_names.join(", "),
                placeholders.join(", "),
                pk.name
            );

            let mut q = sqlx::query(&sql);
            let mut errors: Vec<std::string::String> = Vec::new();
            for col in &writables {
                match bind_form_value(q, col, form.get(col.name)) {
                    Ok(next) => q = next,
                    Err(msg) => {
                        errors.push(msg);
                        // Bind a placeholder so subsequent
                        // bindings stay aligned with placeholders;
                        // the query won't run if errors is
                        // non-empty.
                        q = sqlx::query(&sql); // reset; we won't execute
                        break;
                    }
                }
            }
            if !errors.is_empty() {
                return Ok(Err(errors));
            }

            let row = q
                .fetch_one(db.pool())
                .await
                .map_err(|e| Error::Internal(format!("schema-create({}): {e}", self.schema.table)))?;
            let id: i64 = row
                .try_get(pk.name)
                .map_err(|e| Error::Internal(format!("returning {}: {e}", pk.name)))?;
            db.invalidate(self.schema.table);
            Ok(Ok(id))
        })
    }

    fn update<'a>(&'a self, db: &'a Db, id: i64, form: &'a FormData) -> UpdateFut<'a> {
        Box::pin(async move {
            let pk = self.pk_col();
            let writables = self.writable_columns();
            let sets: Vec<std::string::String> = writables
                .iter()
                .enumerate()
                .map(|(i, c)| format!("{} = ${}", c.name, i + 1))
                .collect();
            let sql = format!(
                "UPDATE {} SET {} WHERE {} = ${}",
                self.schema.table,
                sets.join(", "),
                pk.name,
                writables.len() + 1
            );

            let mut q = sqlx::query(&sql);
            let mut errors: Vec<std::string::String> = Vec::new();
            for col in &writables {
                match bind_form_value(q, col, form.get(col.name)) {
                    Ok(next) => q = next,
                    Err(msg) => {
                        errors.push(msg);
                        q = sqlx::query(&sql);
                        break;
                    }
                }
            }
            if !errors.is_empty() {
                return Ok(Err(errors));
            }
            q = q.bind(id);
            q.execute(db.pool())
                .await
                .map_err(|e| Error::Internal(format!("schema-update({}): {e}", self.schema.table)))?;
            db.invalidate(self.schema.table);
            Ok(Ok(()))
        })
    }

    fn delete<'a>(
        &'a self,
        db: &'a Db,
        id: i64,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>> {
        Box::pin(async move {
            let pk = self.pk_col();
            let sql = format!(
                "DELETE FROM {} WHERE {} = $1",
                self.schema.table, pk.name
            );
            sqlx::query(&sql)
                .bind(id)
                .execute(db.pool())
                .await
                .map_err(|e| Error::Internal(format!("schema-delete({}): {e}", self.schema.table)))?;
            db.invalidate(self.schema.table);
            Ok(())
        })
    }

    fn object_label<'a>(
        &'a self,
        db: &'a Db,
        id: i64,
    ) -> Pin<Box<dyn Future<Output = Result<Option<std::string::String>>> + Send + 'a>> {
        Box::pin(async move {
            // Pick the first non-PK String column as the label
            // source; fall back to "{table} #{id}" when there's
            // none. Mirrors the heuristic the AdminModel-driven
            // path uses for object_label.
            let label_col = self.schema.columns.iter().find(|c| {
                !c.primary_key
                    && matches!(c.rust_type, crate::contract::RustType::String)
            });
            let pk = self.pk_col();
            match label_col {
                Some(col) => {
                    let sql = format!(
                        "SELECT {} FROM {} WHERE {} = $1",
                        col.name, self.schema.table, pk.name
                    );
                    let row = sqlx::query(&sql)
                        .bind(id)
                        .fetch_optional(db.pool())
                        .await
                        .map_err(|e| {
                            Error::Internal(format!(
                                "schema-object-label({}): {e}",
                                self.schema.table
                            ))
                        })?;
                    Ok(row.and_then(|r| {
                        let v = if col.nullable {
                            r.try_get::<Option<std::string::String>, _>(col.name)
                                .ok()
                                .flatten()
                        } else {
                            r.try_get::<std::string::String, _>(col.name).ok()
                        };
                        v.filter(|s| !s.is_empty())
                    }))
                }
                None => Ok(Some(format!("{} #{}", self.schema.table, id))),
            }
        })
    }
}

// ---------------------------------------------------------------------------
// AdminEntry construction from a ModelSchema
// ---------------------------------------------------------------------------

/// Build a fully-configured `AdminEntry` from a `ModelSchema`,
/// without requiring an `AdminModel` impl. The resulting entry's
/// CRUD goes through `SchemaOps`; the field metadata comes from
/// `admin_fields_from_schema`.
///
/// `admin_name`, `display_name`, and `singular_name` are derived
/// from `schema.table`:
///
/// - `admin_name` = `schema.table` verbatim (route prefix)
/// - `display_name` = humanised + Title Case (`"projects"` →
///   `"Projects"`)
/// - `singular_name` = humanised + naive singular (strip a
///   trailing `s`; `"projects"` → `"Project"`)
///
/// Naive singularisation is fine for the common-case English
/// plural; project models with irregular plurals can extend the
/// macro layer with a `#[rustio(singular = "...")]` attribute in
/// a future commit.
pub fn admin_entry_from_schema(schema: ModelSchema) -> AdminEntry {
    let static_schema = leak_schema(schema);
    let admin_name: &'static str = static_schema.table;
    let display_name: &'static str =
        Box::leak(humanise_table(static_schema.table).into_boxed_str());
    let singular_name: &'static str =
        Box::leak(singularise(static_schema.table).into_boxed_str());

    AdminEntry {
        admin_name,
        display_name,
        singular_name,
        table: static_schema.table,
        fields: admin_fields_from_schema(static_schema),
        core: false,
        ops: Arc::new(SchemaOps::new(static_schema)),
        search_hook: None,
    }
}

/// Same as `admin_entry_from_schema` but takes the model type
/// rather than a schema value. Convenience wrapper around
/// `T::SCHEMA`.
pub fn admin_entry_from_type<T: HasSchema>() -> AdminEntry {
    admin_entry_from_schema(T::SCHEMA)
}

/// `"projects"` → `"Projects"`. ASCII Title Case of the first
/// character; rest unchanged. Underscores → spaces.
fn humanise_table(name: &str) -> std::string::String {
    let mut out = std::string::String::with_capacity(name.len());
    let mut next_upper = true;
    for ch in name.chars() {
        if ch == '_' {
            out.push(' ');
            next_upper = true;
        } else if next_upper {
            out.extend(ch.to_uppercase());
            next_upper = false;
        } else {
            out.push(ch);
        }
    }
    out
}

/// `"projects"` → `"Project"`. Phase 15 / commit 9 — handles
/// the common English-plural endings:
///
/// - `-ies` → `-y`   (`companies` → `Company`)
/// - `-s`   → strip  (`projects` → `Project`)
///
/// Irregular plurals (people, children, indices) round-trip
/// wrongly; words that aren't actually plurals but happen to
/// end in `s` (status, virus, news) come out shortened. A
/// future `#[rustio(singular = "...")]` attribute is the
/// planned override path; until then projects with awkward
/// names should set the attribute manually.
fn singularise(name: &str) -> std::string::String {
    let h = humanise_table(name);
    if let Some(stripped) = h.strip_suffix("ies") {
        if !stripped.is_empty() {
            return format!("{stripped}y");
        }
    }
    if let Some(stripped) = h.strip_suffix('s') {
        if !stripped.is_empty() {
            return stripped.to_string();
        }
    }
    h
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::contract::SchemaFlags;

    // ----- Test fixture -----------------------------------------------------

    /// A schema covering every mapping rule the bridge must
    /// honour: primary key, label override, widget override,
    /// every flag bit, every commonly-used `RustType`, both
    /// nullable and non-nullable. One static fixture so the
    /// individual tests don't drift from each other.
    fn fixture_schema() -> ModelSchema {
        static COLS: &[ModelColumn] = &[
            // Primary key, readonly (auto-managed).
            ModelColumn {
                name: "id",
                sql_decl: "BIGSERIAL PRIMARY KEY",
                rust_type: RustType::I64,
                nullable: false,
                primary_key: true,
                flags: SchemaFlags {
                    searchable: false,
                    filterable: false,
                    sortable: true,
                    readonly: true,
                },
                admin_label: None,
                admin_widget: None,
            },
            // Searchable + filterable + explicit label.
            ModelColumn {
                name: "title",
                sql_decl: "TEXT NOT NULL",
                rust_type: RustType::String,
                nullable: false,
                primary_key: false,
                flags: SchemaFlags {
                    searchable: true,
                    filterable: true,
                    sortable: false,
                    readonly: false,
                },
                admin_label: Some("Headline"),
                admin_widget: None,
            },
            // Nullable string + widget override.
            ModelColumn {
                name: "body",
                sql_decl: "TEXT",
                rust_type: RustType::String,
                nullable: true,
                primary_key: false,
                flags: SchemaFlags {
                    searchable: true,
                    filterable: false,
                    sortable: false,
                    readonly: false,
                },
                admin_label: None,
                admin_widget: Some("textarea"),
            },
            // Nullable timestamp + sortable.
            ModelColumn {
                name: "published_at",
                sql_decl: "TIMESTAMPTZ",
                rust_type: RustType::DateTimeUtc,
                nullable: true,
                primary_key: false,
                flags: SchemaFlags {
                    searchable: false,
                    filterable: true,
                    sortable: true,
                    readonly: false,
                },
                admin_label: None,
                admin_widget: None,
            },
            // Bool, no flags set.
            ModelColumn {
                name: "is_pinned",
                sql_decl: "BOOLEAN NOT NULL",
                rust_type: RustType::Bool,
                nullable: false,
                primary_key: false,
                flags: SchemaFlags::empty(),
                admin_label: None,
                admin_widget: None,
            },
        ];
        ModelSchema {
            table: "posts",
            columns: COLS,
            primary_key: "id",
            search_index: Some("posts"),
        }
    }

    // ----- Required by spec -------------------------------------------------

    /// Spec gate: "fields generated from schema". One
    /// `BridgedField` per column, none dropped, none added.
    #[test]
    fn fields_generated_from_schema_one_per_column() {
        let schema = fixture_schema();
        let bridged = bridged_fields_from_schema(&schema);
        assert_eq!(
            bridged.len(),
            schema.columns.len(),
            "every ModelColumn must produce exactly one BridgedField"
        );
    }

    /// Spec gate: "ordering preserved". Bridge output order
    /// matches the schema's declaration order column-for-column.
    /// Reordering would silently re-arrange admin forms.
    #[test]
    fn ordering_preserved_matches_schema_columns() {
        let schema = fixture_schema();
        let bridged = bridged_fields_from_schema(&schema);
        let bridged_names: Vec<&str> = bridged.iter().map(|b| b.field.name).collect();
        let schema_names: Vec<&str> = schema.columns.iter().map(|c| c.name).collect();
        assert_eq!(
            bridged_names, schema_names,
            "BridgedField order must mirror ModelSchema.columns order"
        );
    }

    /// Spec gate: "flags correctly mapped". Every flag bit
    /// flows through to the matching `BridgedField` field.
    #[test]
    fn flags_correctly_mapped_per_column() {
        let schema = fixture_schema();
        let bridged = bridged_fields_from_schema(&schema);

        // `id`: sortable + readonly only.
        let id = &bridged[0];
        assert!(!id.searchable);
        assert!(!id.filterable);
        assert!(id.sortable);
        assert!(id.readonly);
        assert!(!id.field.editable, "readonly => editable=false");

        // `title`: searchable + filterable.
        let title = &bridged[1];
        assert!(title.searchable);
        assert!(title.filterable);
        assert!(!title.sortable);
        assert!(!title.readonly);
        assert!(title.field.editable);

        // `body`: searchable only.
        let body = &bridged[2];
        assert!(body.searchable);
        assert!(!body.filterable);
        assert!(!body.sortable);
        assert!(!body.readonly);

        // `published_at`: filterable + sortable.
        let pa = &bridged[3];
        assert!(!pa.searchable);
        assert!(pa.filterable);
        assert!(pa.sortable);

        // `is_pinned`: all flags off.
        let pin = &bridged[4];
        assert!(!pin.searchable);
        assert!(!pin.filterable);
        assert!(!pin.sortable);
        assert!(!pin.readonly);
    }

    /// Spec gate: "label fallback works". When `admin_label`
    /// is set, the bridge uses it verbatim; when `None`,
    /// Phase 15 / commit 9 derives a friendly default
    /// (humanise + strip `_id` suffix).
    #[test]
    fn label_fallback_humanises_column_name_when_no_override() {
        let schema = fixture_schema();
        let bridged = bridged_fields_from_schema(&schema);

        // Override case: `title` had `admin_label = Some("Headline")`.
        assert_eq!(bridged[1].field.label, "Headline");

        // Fallback case (commit 9 polish): humanised Title Case.
        assert_eq!(bridged[0].field.label, "Id");
        assert_eq!(bridged[2].field.label, "Body");
        assert_eq!(bridged[3].field.label, "Published At");
        assert_eq!(bridged[4].field.label, "Is Pinned");
    }

    /// Phase 15 / commit 9 — `_id` foreign-key suffix is
    /// stripped during label derivation so `client_id` reads
    /// as "Client" in the admin UI rather than "Client Id".
    /// The bare `id` PK column round-trips unchanged
    /// (`"id"` → `"Id"`).
    #[test]
    fn label_fallback_strips_id_suffix_for_foreign_keys() {
        static COLS: &[ModelColumn] = &[
            ModelColumn {
                name: "id",
                sql_decl: "BIGSERIAL PRIMARY KEY",
                rust_type: RustType::I64,
                nullable: false,
                primary_key: true,
                flags: SchemaFlags::empty(),
                admin_label: None,
                admin_widget: None,
            },
            ModelColumn {
                name: "client_id",
                sql_decl: "BIGINT NOT NULL",
                rust_type: RustType::I64,
                nullable: false,
                primary_key: false,
                flags: SchemaFlags::empty(),
                admin_label: None,
                admin_widget: None,
            },
            ModelColumn {
                name: "primary_address_id",
                sql_decl: "BIGINT",
                rust_type: RustType::I64,
                nullable: true,
                primary_key: false,
                flags: SchemaFlags::empty(),
                admin_label: None,
                admin_widget: None,
            },
        ];
        let schema = ModelSchema {
            table: "scratch",
            columns: COLS,
            primary_key: "id",
            search_index: None,
        };
        let bridged = bridged_fields_from_schema(&schema);
        assert_eq!(bridged[0].field.label, "Id"); // bare id intact
        assert_eq!(bridged[1].field.label, "Client"); // _id stripped
        assert_eq!(bridged[2].field.label, "Primary Address"); // _id stripped + humanised
    }

    /// Spec gate: "widget override works". `admin_widget`
    /// from the source column is preserved on `BridgedField.widget`
    /// verbatim. `None` stays `None`.
    #[test]
    fn widget_override_preserved_through_bridge() {
        let schema = fixture_schema();
        let bridged = bridged_fields_from_schema(&schema);

        assert_eq!(bridged[2].widget, Some("textarea"), "body's textarea override must survive");
        assert!(bridged[0].widget.is_none(), "id had no widget override");
        assert!(bridged[1].widget.is_none(), "title had no widget override");
        assert!(bridged[3].widget.is_none(), "published_at had no widget override");
        assert!(bridged[4].widget.is_none(), "is_pinned had no widget override");
    }

    /// Spec gate: "primary key detected". The bridge surfaces
    /// the same column flagged in the contract; helper picks
    /// it out by reference.
    #[test]
    fn primary_key_detected_from_schema() {
        let schema = fixture_schema();
        let bridged = bridged_fields_from_schema(&schema);

        // Exactly one column flagged primary_key.
        let pk_count = bridged.iter().filter(|b| b.primary_key).count();
        assert_eq!(pk_count, 1, "fixture has exactly one primary-key column");
        assert!(bridged[0].primary_key, "the `id` column is the PK");
        assert!(!bridged[1].primary_key);

        // Helper resolves the same column.
        let pk = primary_key_column(&schema).expect("PK exists in fixture");
        assert_eq!(pk.name, "id");
    }

    /// `primary_key_column` returns `None` when no column is
    /// flagged. The validator in commit 3 surfaces this as a
    /// `WrongPrimaryKey` issue; the bridge just reports honestly.
    #[test]
    fn primary_key_column_returns_none_when_unflagged() {
        static COLS: &[ModelColumn] = &[ModelColumn {
            name: "value",
            sql_decl: "TEXT NOT NULL",
            rust_type: RustType::String,
            nullable: false,
            primary_key: false,
            flags: SchemaFlags::empty(),
            admin_label: None,
            admin_widget: None,
        }];
        let schema = ModelSchema {
            table: "scratch",
            columns: COLS,
            primary_key: "value",
            search_index: None,
        };
        assert!(primary_key_column(&schema).is_none());
    }

    // ----- FieldType mapping -----------------------------------------------

    /// Every `RustType` variant the admin natively models has
    /// the documented `(nullable, non-nullable)` pair.
    #[test]
    fn field_type_mapping_covers_native_variants() {
        // Helper: build a stub column for type-mapping checks.
        fn col(rust_type: RustType, nullable: bool) -> ModelColumn {
            ModelColumn {
                name: "f",
                sql_decl: "",
                rust_type,
                nullable,
                primary_key: false,
                flags: SchemaFlags::empty(),
                admin_label: None,
                admin_widget: None,
            }
        }

        assert_eq!(field_type_for(&col(RustType::I32, false)), FieldType::I32);
        // No OptionalI32 variant — nullable I32 collapses into OptionalI64.
        assert_eq!(field_type_for(&col(RustType::I32, true)), FieldType::OptionalI64);

        assert_eq!(field_type_for(&col(RustType::I64, false)), FieldType::I64);
        assert_eq!(field_type_for(&col(RustType::I64, true)), FieldType::OptionalI64);

        assert_eq!(field_type_for(&col(RustType::Bool, false)), FieldType::Bool);
        assert_eq!(field_type_for(&col(RustType::Bool, true)), FieldType::Bool);

        assert_eq!(field_type_for(&col(RustType::String, false)), FieldType::String);
        assert_eq!(field_type_for(&col(RustType::String, true)), FieldType::OptionalString);

        assert_eq!(field_type_for(&col(RustType::DateTimeUtc, false)), FieldType::DateTime);
        assert_eq!(field_type_for(&col(RustType::DateTimeUtc, true)), FieldType::OptionalDateTime);
    }

    /// Variants the admin doesn't natively model (`F64`,
    /// `Decimal`, `JsonValue`, `Uuid`) collapse to text inputs.
    /// Documented behaviour; a future commit may extend
    /// `FieldType` and tighten these.
    #[test]
    fn field_type_mapping_falls_back_to_string_for_unmodelled_variants() {
        fn col(rust_type: RustType, nullable: bool) -> ModelColumn {
            ModelColumn {
                name: "f",
                sql_decl: "",
                rust_type,
                nullable,
                primary_key: false,
                flags: SchemaFlags::empty(),
                admin_label: None,
                admin_widget: None,
            }
        }

        for rt in [RustType::F64, RustType::Decimal, RustType::JsonValue, RustType::Uuid] {
            assert_eq!(field_type_for(&col(rt, false)), FieldType::String, "{:?} -> String", rt);
            assert_eq!(field_type_for(&col(rt, true)), FieldType::OptionalString, "{:?} -> OptionalString", rt);
        }
    }

    // ----- AdminField slice helper -----------------------------------------

    /// `admin_fields_from_schema` returns a slice the same
    /// length and order as `bridged_fields_from_schema`, with
    /// each `AdminField` matching the bridge output verbatim.
    #[test]
    fn admin_fields_slice_matches_bridge_output() {
        let schema = fixture_schema();
        let bridged = bridged_fields_from_schema(&schema);
        let slice = admin_fields_from_schema(&schema);

        assert_eq!(slice.len(), bridged.len());
        for (i, f) in slice.iter().enumerate() {
            assert_eq!(f.name, bridged[i].field.name, "name @{}", i);
            assert_eq!(f.label, bridged[i].field.label, "label @{}", i);
            assert_eq!(f.field_type, bridged[i].field.field_type, "field_type @{}", i);
            assert_eq!(f.editable, bridged[i].field.editable, "editable @{}", i);
        }
    }

    /// The slice satisfies the `&'static [AdminField]` shape
    /// `AdminEntry.fields` requires — it can be used in places
    /// where a `'static` lifetime is mandatory. Compile-time
    /// gate: this won't compile if the helper returns a non-
    /// static reference.
    #[test]
    fn admin_fields_slice_is_static_lifetime() {
        fn assert_static(_x: &'static [AdminField]) {}
        let schema = fixture_schema();
        let slice = admin_fields_from_schema(&schema);
        assert_static(slice);
    }

    /// A column with `flags.readonly = true` produces
    /// `AdminField.editable = false`. The inverse
    /// (readonly = false → editable = true) is also covered.
    #[test]
    fn editable_is_inverse_of_readonly() {
        let schema = fixture_schema();
        let bridged = bridged_fields_from_schema(&schema);
        for b in &bridged {
            assert_eq!(
                b.field.editable, !b.readonly,
                "editable must always equal !readonly for `{}`",
                b.field.name
            );
        }
    }

    /// Empty schema → empty bridge output. A schema with zero
    /// columns is malformed but the bridge shouldn't panic.
    #[test]
    fn empty_schema_produces_empty_bridge_output() {
        static COLS: &[ModelColumn] = &[];
        let schema = ModelSchema {
            table: "empty",
            columns: COLS,
            primary_key: "id",
            search_index: None,
        };
        assert_eq!(bridged_fields_from_schema(&schema).len(), 0);
        assert_eq!(admin_fields_from_schema(&schema).len(), 0);
        assert!(primary_key_column(&schema).is_none());
    }

    // ----- Phase 14, commit 8 — name derivation for AdminEntry -----------

    /// Plain plural `"projects"` humanises + singularises to
    /// `"Projects"` / `"Project"`.
    #[test]
    fn humanise_table_capitalises_first_letter() {
        assert_eq!(super::humanise_table("projects"), "Projects");
        assert_eq!(super::humanise_table("clients"), "Clients");
        assert_eq!(super::humanise_table("invoices"), "Invoices");
    }

    /// Underscore tables humanise as Title Case (every
    /// underscore-separated word capitalised).
    #[test]
    fn humanise_table_translates_underscores_to_spaces() {
        assert_eq!(super::humanise_table("audit_logs"), "Audit Logs");
        assert_eq!(super::humanise_table("user_profiles"), "User Profiles");
    }

    /// Phase 15 / commit 9 singular rules: handles `-ies` →
    /// `-y` and trailing `-s`. Words that aren't actually
    /// plural but happen to end in `s` (status, virus) round-
    /// trip wrongly; these need an explicit override.
    #[test]
    fn singularise_handles_common_plural_endings() {
        assert_eq!(super::singularise("projects"), "Project");
        assert_eq!(super::singularise("clients"), "Client");
        assert_eq!(super::singularise("invoices"), "Invoice");
        // -ies → -y (companies → Company).
        assert_eq!(super::singularise("companies"), "Company");
        assert_eq!(super::singularise("categories"), "Category");
        // Single-word non-plural ending in `s` gets shortened —
        // documents the known limitation.
        assert_eq!(super::singularise("status"), "Statu");
    }

    /// Phase 15 / commit 9 — `effective_widget` resolution.
    #[test]
    fn effective_widget_returns_explicit_override_when_present() {
        let schema = fixture_schema();
        let bridged = bridged_fields_from_schema(&schema);
        // `body` has `admin_widget = Some("textarea")`.
        let body = bridged.iter().find(|b| b.field.name == "body").unwrap();
        assert_eq!(body.effective_widget(), Some("textarea"));
    }

    /// Phase 15 / commit 9 — when no explicit widget, name-
    /// based inference kicks in. Conservative: only column
    /// names that unambiguously match a recognised pattern
    /// produce a hint.
    #[test]
    fn effective_widget_infers_from_recognised_column_names() {
        fn col(name: &'static str) -> ModelColumn {
            ModelColumn {
                name,
                sql_decl: "TEXT NOT NULL",
                rust_type: RustType::String,
                nullable: false,
                primary_key: false,
                flags: SchemaFlags::empty(),
                admin_label: None,
                admin_widget: None,
            }
        }
        let cases = [
            ("email", Some("email")),
            ("contact_email", Some("email")),
            ("phone", Some("tel")),
            ("home_phone", Some("tel")),
            ("tel", Some("tel")),
            ("url", Some("url")),
            ("homepage_url", Some("url")),
            ("api_uri", Some("url")),
            ("password", Some("password")),
            ("admin_password", Some("password")),
            // Negatives — ambiguous names don't infer.
            ("description", None),
            ("notes", None),
            ("title", None),
        ];
        for (name, expected) in cases {
            let bf = BridgedField {
                field: AdminField {
                    name,
                    label: name,
                    field_type: FieldType::String,
                    editable: true,
                    relation: None,
                    choices: None,
                },
                primary_key: false,
                searchable: false,
                filterable: false,
                sortable: false,
                readonly: false,
                widget: None,
            };
            assert_eq!(
                bf.effective_widget(),
                expected,
                "name-based inference for `{name}`"
            );
            let _ = col(name); // suppress unused warning if cases shrink
        }
    }

    /// `admin_entry_from_schema` builds an entry with derived
    /// names and the bridge's field list. Integration test that
    /// exercises every commit-5 + commit-8 admin surface
    /// without a DB.
    #[test]
    fn admin_entry_from_schema_packages_metadata_correctly() {
        let schema = fixture_schema();
        let entry = super::admin_entry_from_schema(schema);

        assert_eq!(entry.admin_name, "posts");
        assert_eq!(entry.display_name, "Posts");
        assert_eq!(entry.singular_name, "Post");
        assert_eq!(entry.table, "posts");
        assert!(!entry.core, "schema-derived entries are never `core`");

        // Field list matches the bridge output column-for-column.
        let names: Vec<&str> = entry.fields.iter().map(|f| f.name).collect();
        assert_eq!(
            names,
            vec!["id", "title", "body", "published_at", "is_pinned"]
        );

        // No search hook attached — search wiring is a separate
        // step (Indexer::from_schema in commit 8).
        assert!(entry.search_hook.is_none());
    }

    /// `Admin::from_schemas` registers one entry per supplied
    /// schema and preserves the input order (the existing
    /// `core` user entry is pre-seeded; new entries appear after).
    #[test]
    fn admin_from_schemas_registers_each_schema_in_order() {
        use crate::admin::types::Admin;

        let schemas = vec![
            ModelSchema {
                table: "alpha",
                columns: fixture_schema().columns,
                primary_key: "id",
                search_index: None,
            },
            ModelSchema {
                table: "beta",
                columns: fixture_schema().columns,
                primary_key: "id",
                search_index: None,
            },
        ];

        let admin = Admin::new().from_schemas(&schemas);
        let entry_tables: Vec<&str> =
            admin.entries().iter().map(|e| e.table).collect();

        // Core user entry at index 0; the two schema entries
        // follow in declaration order.
        assert!(entry_tables.contains(&"alpha"));
        assert!(entry_tables.contains(&"beta"));
        let alpha_pos = entry_tables.iter().position(|t| *t == "alpha").unwrap();
        let beta_pos = entry_tables.iter().position(|t| *t == "beta").unwrap();
        assert!(alpha_pos < beta_pos, "from_schemas preserves slice order");
    }
}