umbral-core 0.0.4

umbral internals: ORM, migrations, routing, DB backends, the Plugin trait. Do not depend on this directly; use the `umbral` facade.
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
//! Pre- and post-DB validation helpers used by
//! [`DynQuerySet::insert_json`] and [`DynQuerySet::update_json`].
//!
//! Three jobs:
//!
//! 1. **Required-field check.** Walks the model's columns and
//!    rejects any required column that's missing or blank in the
//!    body. Empty strings on Text columns count as blank
//!    (a non-blank text column); JSON `{}` does
//!    not (legitimate JSONB value). FK numeric `0` does NOT —
//!    that's the FK existence check's job, where the truthful
//!    message ("row not found") replaces a synthetic "required."
//!
//! 2. **Foreign-key existence check.** For every FK column in the
//!    body, queries the target table to verify the referenced row
//!    exists. Emits a [`WriteError::ForeignKeyNotFound`] per bad
//!    reference so the REST / admin layer can render an inline
//!    "Referenced X row with id=Y not found" message keyed under
//!    the FK column.
//!
//! 3. **SQL constraint classification.** After the INSERT /
//!    UPDATE runs, any [`sqlx::Error::Database`] gets walked
//!    through the SQLite / Postgres error-code tables and turned
//!    into one of `UniqueViolation` / `NotNullViolation` /
//!    `CheckViolation` / `ForeignKeyViolation`. The body-aware
//!    paths thread the original JSON value into the message so
//!    the response says "slug='widget'" rather than the generic
//!    "this value."
//!
//! The REST plugin used to own all of these; centralising them
//! here means the admin plugin and any third-party caller get the
//! same structured errors without re-implementing the wheel.

use serde_json::{Map, Value};

use crate::migrate::{Column, ModelMeta};
use crate::orm::model::SqlType;
use crate::orm::write::WriteError;

/// Run every pre-DB check the ORM owns for a create-shaped body.
/// Returns the merged list of errors so the caller's response can
/// surface required + FK problems in the same round-trip.
///
/// The FK check is async because it queries the target tables;
/// the required check is sync. Callers that want only one or the
/// other reach for the individual helpers.
pub async fn validate_on_create(meta: &ModelMeta, body: &Map<String, Value>) -> Vec<WriteError> {
    let mut errors = validate_required_create(meta, body);
    errors.extend(validate_choices(meta, body));
    errors.extend(validate_m2m_relations(meta, body).await);
    let mut fk_errors = validate_fk_references(meta, body).await;
    let fk_fields: std::collections::HashSet<String> = fk_errors
        .iter()
        .filter_map(|e| match e {
            WriteError::ForeignKeyNotFound { field, .. } => Some(field.clone()),
            _ => None,
        })
        .collect();
    // When a field has both a "required" and an "FK not found"
    // error, drop the "required" — the FK message is the more
    // specific failure mode. The client knew to send a value;
    // the value just doesn't reference a real row.
    errors.retain(|e| match e {
        WriteError::RequiredFieldMissing { field } => !fk_fields.contains(field),
        WriteError::BlankNotAllowed { field } => !fk_fields.contains(field),
        _ => true,
    });
    errors.append(&mut fk_errors);
    errors
}

/// Transaction-aware sibling of [`validate_on_create`]. Identical
/// except the FK-existence check runs on the passed transaction
/// instead of the ambient pool, so a nested create can validate a
/// child whose FK points at a parent that was inserted earlier on
/// the SAME (still-uncommitted) transaction. Reading on the pool
/// would not see the uncommitted parent and would reject the child
/// as a dangling reference.
///
/// The M2M shape/existence check stays on the ambient pool: M2M
/// targets are unrelated to the in-flight parent, so committed-read
/// visibility is the right semantics there.
pub async fn validate_on_create_in_tx(
    meta: &ModelMeta,
    body: &Map<String, Value>,
    tx: &mut crate::db::Transaction,
) -> Vec<WriteError> {
    let mut errors = validate_required_create(meta, body);
    errors.extend(validate_choices(meta, body));
    errors.extend(validate_m2m_relations(meta, body).await);
    let mut fk_errors = validate_fk_references_in_tx(meta, body, tx).await;
    let fk_fields: std::collections::HashSet<String> = fk_errors
        .iter()
        .filter_map(|e| match e {
            WriteError::ForeignKeyNotFound { field, .. } => Some(field.clone()),
            _ => None,
        })
        .collect();
    errors.retain(|e| match e {
        WriteError::RequiredFieldMissing { field } => !fk_fields.contains(field),
        WriteError::BlankNotAllowed { field } => !fk_fields.contains(field),
        _ => true,
    });
    errors.append(&mut fk_errors);
    errors
}

/// Update-shaped equivalent. Required-field check only fires on
/// fields the client EXPLICITLY sent as blank — missing keys are
/// fine per the partial-update contract.
/// Typed-create equivalent of [`validate_on_create`]. Skips the
/// blank-string check (a Rust `String` field set to `""` is the
/// caller's deliberate choice on this path, not a form-default
/// leak), but still runs choices + FK existence + M2M shape —
/// the things a compile-time type can't catch.
pub async fn validate_on_typed_create(
    meta: &ModelMeta,
    body: &Map<String, Value>,
) -> Vec<WriteError> {
    let mut errors = Vec::new();
    errors.extend(validate_choices(meta, body));
    errors.extend(validate_m2m_relations(meta, body).await);
    let mut fk_errors = validate_fk_references(meta, body).await;
    let fk_fields: std::collections::HashSet<String> = fk_errors
        .iter()
        .filter_map(|e| match e {
            WriteError::ForeignKeyNotFound { field, .. } => Some(field.clone()),
            _ => None,
        })
        .collect();
    errors.retain(|e| match e {
        WriteError::Validator { field, .. } => !fk_fields.contains(field),
        _ => true,
    });
    errors.append(&mut fk_errors);
    errors
}

pub async fn validate_on_update(meta: &ModelMeta, body: &Map<String, Value>) -> Vec<WriteError> {
    let mut errors = validate_required_update(meta, body);
    errors.extend(validate_choices(meta, body));
    errors.extend(validate_m2m_relations(meta, body).await);
    let mut fk_errors = validate_fk_references(meta, body).await;
    let fk_fields: std::collections::HashSet<String> = fk_errors
        .iter()
        .filter_map(|e| match e {
            WriteError::ForeignKeyNotFound { field, .. } => Some(field.clone()),
            _ => None,
        })
        .collect();
    errors.retain(|e| match e {
        WriteError::RequiredFieldMissing { field } | WriteError::BlankNotAllowed { field } => {
            !fk_fields.contains(field)
        }
        _ => true,
    });
    errors.append(&mut fk_errors);
    errors
}

/// Transaction-aware sibling of [`validate_on_update`]. Identical
/// except the FK-existence check runs on the passed transaction, so a
/// bulk update inside one tx validates an FK against rows the same
/// (uncommitted) tx may have just written.
pub async fn validate_on_update_in_tx(
    meta: &ModelMeta,
    body: &Map<String, Value>,
    tx: &mut crate::db::Transaction,
) -> Vec<WriteError> {
    let mut errors = validate_required_update(meta, body);
    errors.extend(validate_choices(meta, body));
    errors.extend(validate_m2m_relations(meta, body).await);
    let mut fk_errors = validate_fk_references_in_tx(meta, body, tx).await;
    let fk_fields: std::collections::HashSet<String> = fk_errors
        .iter()
        .filter_map(|e| match e {
            WriteError::ForeignKeyNotFound { field, .. } => Some(field.clone()),
            _ => None,
        })
        .collect();
    errors.retain(|e| match e {
        WriteError::RequiredFieldMissing { field } | WriteError::BlankNotAllowed { field } => {
            !fk_fields.contains(field)
        }
        _ => true,
    });
    errors.append(&mut fk_errors);
    errors
}

/// Classify a `sqlx::Error::Database` constraint failure into a
/// structured `WriteError`. The original body is used to lift the
/// offending value into the response message. Returns `None`
/// when the error doesn't match a known constraint code; the
/// caller's `WriteError::Sqlx(e)` fallback handles that case
/// (and surfaces as a 500 at the REST boundary).
pub fn classify_sql_error(e: &sqlx::Error, body: &Map<String, Value>) -> Option<WriteError> {
    let db_err = e.as_database_error()?;
    let sql_code = db_err.code()?;
    let sql_code = sql_code.as_ref();
    let message = db_err.message();
    let pg_column = db_err
        .constraint()
        .and_then(parse_pg_column_from_constraint);

    match sql_code {
        // ---- SQLite ----
        "787" => Some(WriteError::ForeignKeyViolation { field: None }),
        "2067" => {
            // "UNIQUE constraint failed: tbl.col[, tbl.col]"
            let cols = sqlite_columns_from_message(message, "UNIQUE constraint failed:");
            // For a single-column UNIQUE we can name a value; for
            // composite uniques we report the first column with
            // no value (multiple ambiguity).
            if cols.len() == 1 {
                let col = cols.into_iter().next().unwrap();
                let value = body.get(&col).cloned();
                Some(WriteError::UniqueViolation {
                    field: Some(col),
                    value,
                })
            } else if !cols.is_empty() {
                Some(WriteError::UniqueViolation {
                    field: Some(cols.into_iter().next().unwrap()),
                    value: None,
                })
            } else {
                Some(WriteError::UniqueViolation {
                    field: None,
                    value: None,
                })
            }
        }
        "1299" => {
            let cols = sqlite_columns_from_message(message, "NOT NULL constraint failed:");
            Some(WriteError::NotNullViolation {
                field: cols.into_iter().next(),
            })
        }
        "275" => Some(WriteError::CheckViolation { constraint: None }),

        // ---- Postgres ----
        "23503" => Some(WriteError::ForeignKeyViolation { field: pg_column }),
        "23505" => {
            let value = pg_column.as_ref().and_then(|c| body.get(c)).cloned();
            Some(WriteError::UniqueViolation {
                field: pg_column,
                value,
            })
        }
        "23502" => Some(WriteError::NotNullViolation { field: pg_column }),
        "23514" => Some(WriteError::CheckViolation {
            constraint: db_err.constraint().map(String::from),
        }),
        _ => None,
    }
}

// =========================================================================
// Internals.
// =========================================================================

fn validate_required_create(meta: &ModelMeta, body: &Map<String, Value>) -> Vec<WriteError> {
    let mut out = Vec::new();
    for col in &meta.fields {
        if !column_is_required(col) {
            continue;
        }
        match body.get(&col.name) {
            None | Some(Value::Null) => {
                out.push(WriteError::RequiredFieldMissing {
                    field: col.name.clone(),
                });
            }
            Some(Value::String(s)) if value_is_blank_for_type(s, col.ty) => {
                if matches!(col.ty, SqlType::Text) {
                    out.push(WriteError::BlankNotAllowed {
                        field: col.name.clone(),
                    });
                } else {
                    // Empty-string placeholder where a typed value
                    // belongs — caller didn't fill the form in.
                    out.push(WriteError::RequiredFieldMissing {
                        field: col.name.clone(),
                    });
                }
            }
            _ => {}
        }
    }
    out
}

fn validate_required_update(meta: &ModelMeta, body: &Map<String, Value>) -> Vec<WriteError> {
    let mut out = Vec::new();
    for col in &meta.fields {
        if !column_is_required(col) {
            continue;
        }
        // Update: only complain when the client EXPLICITLY sent a
        // blank value. Missing keys preserve the existing row.
        let Some(value) = body.get(&col.name) else {
            continue;
        };
        match value {
            Value::Null => {
                out.push(WriteError::RequiredFieldMissing {
                    field: col.name.clone(),
                });
            }
            Value::String(s) if value_is_blank_for_type(s, col.ty) => {
                if matches!(col.ty, SqlType::Text) {
                    out.push(WriteError::BlankNotAllowed {
                        field: col.name.clone(),
                    });
                } else {
                    out.push(WriteError::RequiredFieldMissing {
                        field: col.name.clone(),
                    });
                }
            }
            _ => {}
        }
    }
    out
}

/// Reject body values that don't match a column's declared
/// `choices` set. Catches the typo case (`"usdd"` for a column
/// constrained to `["usd","eur","gbp",...]`) before the row
/// reaches the DB's CHECK constraint — the CHECK would still
/// catch it, but with a generic message; here we emit
/// `WriteError::Validator { field, message }` with the offending
/// value and the allowed set spelled out.
///
/// Blank / null / missing values are skipped — those are the
/// required-field check's job. Columns with an empty `choices`
/// list are unrestricted.
/// Stringify a JSON number for choices comparison. An integer-valued
/// float (`2.0`, which serde parses as a `Number` with a fractional
/// representation) renders as `"2"` so it matches a choice declared
/// `"2"`; a genuine fractional value (`2.5`) keeps its decimal form and
/// will correctly fail the membership test against integer choices.
fn normalize_number_repr(n: &serde_json::Number) -> String {
    if let Some(i) = n.as_i64() {
        return i.to_string();
    }
    if let Some(u) = n.as_u64() {
        return u.to_string();
    }
    if let Some(f) = n.as_f64() {
        if f.is_finite() && f.fract() == 0.0 && f.abs() < i64::MAX as f64 {
            return (f as i64).to_string();
        }
        return f.to_string();
    }
    n.to_string()
}

fn validate_choices(meta: &ModelMeta, body: &Map<String, Value>) -> Vec<WriteError> {
    let mut out = Vec::new();
    for col in &meta.fields {
        if col.choices.is_empty() {
            continue;
        }
        let Some(value) = body.get(&col.name) else {
            continue;
        };
        if value.is_null() {
            continue;
        }
        let value_repr = match value {
            Value::String(s) if s.is_empty() => continue,
            Value::String(s) => s.clone(),
            Value::Number(n) => normalize_number_repr(n),
            Value::Bool(b) => b.to_string(),
            _ => continue, // odd shape — let the DB sort it out
        };
        if col.choices.iter().any(|c| c == &value_repr) {
            continue;
        }
        out.push(WriteError::Validator {
            field: col.name.clone(),
            message: format!(
                "'{value_repr}' is not a valid choice. Allowed: {}.",
                col.choices.join(", "),
            ),
        });
    }
    out
}

/// Validate every M2M relation on the parent.
///
/// `Post.tags: M2M<Tag>` doesn't live on `model.fields` (it has
/// no column on `post`); it lives on `model.m2m_relations`. Two
/// failure modes:
///
/// - **Shape**: the body value must be an array (or null /
///   missing). `tags: 1` is wrong — caught as a structured type
///   error keyed under the M2M field name.
/// - **Existence**: every id in the array must reference a real
///   row in the target table. Missing rows surface keyed under
///   the M2M field with the full list of bad ids.
///
/// Both messages name the offending value so the client knows
/// exactly what to fix.
async fn validate_m2m_relations(meta: &ModelMeta, body: &Map<String, Value>) -> Vec<WriteError> {
    let mut out = Vec::new();
    for rel in &meta.m2m_relations {
        let Some(value) = body.get(&rel.field_name) else {
            continue;
        };
        if value.is_null() {
            continue;
        }
        // Shape: must be an array.
        let Some(items) = value.as_array() else {
            out.push(WriteError::Validator {
                field: rel.field_name.clone(),
                message: format!(
                    "Expected an array of `{}` ids, got {}.",
                    rel.target_name,
                    json_kind(value),
                ),
            });
            continue;
        };
        // Skip the registry lookup when there's nothing to check
        // — also avoids touching the registry in unit tests that
        // exercise the shape branch without booting an App.
        let to_check: Vec<&Value> = items.iter().filter(|v| !v.is_null()).collect();
        if to_check.is_empty() {
            continue;
        }
        // Existence: each id in the array must reference a real
        // row in the target table.
        let Some(target_meta) = model_meta_by_table(&rel.target_table) else {
            // Target not registered; fall back to silent skip —
            // the migration engine would have caught a real
            // typo at boot.
            continue;
        };
        let mut missing: Vec<Value> = Vec::new();
        for item in to_check {
            match check_fk_row_exists(&target_meta, item).await {
                Ok(true) => {}
                Ok(false) => missing.push(item.clone()),
                Err(e) => {
                    out.push(e);
                    missing.clear();
                    break;
                }
            }
        }
        if !missing.is_empty() {
            let listed = missing
                .iter()
                .map(repr_json_value_local)
                .collect::<Vec<_>>()
                .join(", ");
            out.push(WriteError::Validator {
                field: rel.field_name.clone(),
                message: format!(
                    "Some referenced `{}` rows do not exist: {listed}.",
                    rel.target_name,
                ),
            });
        }
    }
    out
}

/// Lightweight string label for the JSON value's kind. Used in
/// shape-mismatch messages so the response reads
/// "got number" / "got object" instead of leaking the full
/// rendered value.
fn json_kind(v: &Value) -> &'static str {
    match v {
        Value::Null => "null",
        Value::Bool(_) => "boolean",
        Value::Number(_) => "number",
        Value::String(_) => "string",
        Value::Array(_) => "array",
        Value::Object(_) => "object",
    }
}

/// Same shape as the `repr_json_value` helper in `write.rs` but
/// usable inside this module without an extra pub. Strings get
/// quoted; numbers / bools / null bare; arrays / objects fall
/// back to compact JSON.
fn repr_json_value_local(v: &Value) -> String {
    match v {
        Value::String(s) => format!("'{s}'"),
        Value::Number(n) => n.to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Null => "null".to_string(),
        _ => serde_json::to_string(v).unwrap_or_else(|_| "(?)".to_string()),
    }
}

async fn validate_fk_references(meta: &ModelMeta, body: &Map<String, Value>) -> Vec<WriteError> {
    let mut out = Vec::new();
    for col in &meta.fields {
        let Some(target_table) = col.fk_target.as_deref() else {
            continue;
        };
        let Some(value) = body.get(&col.name) else {
            continue;
        };
        if value.is_null() {
            continue;
        }
        let Some(target_meta) = model_meta_by_table(target_table) else {
            // Target not registered with the migration engine;
            // fall back to DB-side enforcement.
            continue;
        };
        match check_fk_row_exists(&target_meta, value).await {
            Ok(true) => {}
            Ok(false) => {
                out.push(WriteError::ForeignKeyNotFound {
                    field: col.name.clone(),
                    target_table: target_table.to_string(),
                    value: value.clone(),
                });
            }
            Err(e) => out.push(e),
        }
    }
    out
}

/// Transaction-aware sibling of [`validate_fk_references`]. The only
/// difference is the existence check runs through the open
/// transaction so an FK at an uncommitted parent resolves.
async fn validate_fk_references_in_tx(
    meta: &ModelMeta,
    body: &Map<String, Value>,
    tx: &mut crate::db::Transaction,
) -> Vec<WriteError> {
    let mut out = Vec::new();
    for col in &meta.fields {
        let Some(target_table) = col.fk_target.as_deref() else {
            continue;
        };
        let Some(value) = body.get(&col.name) else {
            continue;
        };
        if value.is_null() {
            continue;
        }
        let Some(target_meta) = model_meta_by_table(target_table) else {
            continue;
        };
        match check_fk_row_exists_in_tx(&target_meta, value, tx).await {
            Ok(true) => {}
            Ok(false) => {
                out.push(WriteError::ForeignKeyNotFound {
                    field: col.name.clone(),
                    target_table: target_table.to_string(),
                    value: value.clone(),
                });
            }
            Err(e) => out.push(e),
        }
    }
    out
}

fn column_is_required(col: &Column) -> bool {
    !col.primary_key
        && !col.noform
        && !col.nullable
        && col.default.is_empty()
        && !col.auto_now
        && !col.auto_now_add
}

/// `true` when the JSON string is "blank" in the sense of "the
/// caller sent a placeholder where a value should be." Empty
/// strings on Text columns count; whitespace-only on typed
/// columns counts; everything else is a real value.
fn value_is_blank_for_type(s: &str, ty: SqlType) -> bool {
    if s.is_empty() {
        return true;
    }
    matches!(
        ty,
        SqlType::SmallInt
            | SqlType::Integer
            | SqlType::BigInt
            | SqlType::Real
            | SqlType::Double
            | SqlType::Boolean
            | SqlType::Date
            | SqlType::Time
            | SqlType::Timestamptz
            | SqlType::Uuid
            | SqlType::ForeignKey,
    ) && s.trim().is_empty()
}

/// Look up a [`ModelMeta`] by SQL table name. Walks the migration
/// registry — same source the REST plugin's allow/deny check uses.
fn model_meta_by_table(table: &str) -> Option<ModelMeta> {
    for plugin in crate::migrate::registered_plugins() {
        for meta in crate::migrate::models_for_plugin(&plugin) {
            if meta.table == table {
                return Some(meta);
            }
        }
    }
    None
}

/// Single-row existence check against the FK target table. Uses
/// `DynQuerySet::count` so both SQLite and Postgres work without
/// raw SQL.
async fn check_fk_row_exists(target: &ModelMeta, value: &Value) -> Result<bool, WriteError> {
    let Some(pk) = target.fields.iter().find(|c| c.primary_key) else {
        return Ok(true);
    };
    let pk_repr = match value {
        Value::Number(n) => n.to_string(),
        Value::String(s) => s.clone(),
        Value::Bool(b) => b.to_string(),
        _ => return Ok(true),
    };
    let count = crate::orm::dynamic::DynQuerySet::for_meta(target)
        .filter_eq_string(&pk.name, &pk_repr)
        .count()
        .await
        .map_err(|e| match e {
            crate::orm::dynamic::DynError::Write(e) => e,
            crate::orm::dynamic::DynError::Sqlx(e) => WriteError::Sqlx(e),
        })?;
    Ok(count > 0)
}

/// Transaction-aware existence check. Mirrors [`check_fk_row_exists`]
/// but the COUNT runs on the open transaction so an uncommitted
/// parent inserted earlier on the same tx is visible. Built with
/// sea-query so SQLite and Postgres share one code path; dispatch is
/// on the transaction's backend name.
async fn check_fk_row_exists_in_tx(
    target: &ModelMeta,
    value: &Value,
    tx: &mut crate::db::Transaction,
) -> Result<bool, WriteError> {
    use sea_query::{Alias, Expr, Func, PostgresQueryBuilder, Query, SqliteQueryBuilder};
    use sea_query_binder::SqlxBinder;

    let Some(pk) = target.fields.iter().find(|c| c.primary_key) else {
        return Ok(true);
    };
    // Build the PK predicate as a typed sea-query value so binding
    // works on both backends (a string PK binds as TEXT, an integer
    // PK as the right integer width).
    let pk_value = match crate::orm::write::json_to_sea_value(pk.ty, value, false, &pk.name, None) {
        Ok(v) => v,
        // A value that won't coerce to the PK type can't match a real
        // row; treat as "not found" so the FK error surfaces rather
        // than a panic.
        Err(_) => return Ok(false),
    };
    let mut q = Query::select();
    q.from(crate::db::router::schema_qualified_table(&target.table))
        .expr(Func::count(Expr::col(Alias::new(&pk.name))))
        .and_where(Expr::col(Alias::new(&pk.name)).eq(pk_value));

    match tx.backend_name() {
        "sqlite" => {
            let Some(inner) = tx.as_sqlite_mut() else {
                return Ok(true);
            };
            let (sql, values) = q.build_sqlx(SqliteQueryBuilder);
            match sqlx::query_scalar_with::<_, i64, _>(&sql, values)
                .fetch_one(&mut **inner)
                .await
            {
                Ok(n) => Ok(n > 0),
                Err(e) => Err(WriteError::Sqlx(e)),
            }
        }
        _ => {
            let Some(inner) = tx.as_pg_mut() else {
                return Ok(true);
            };
            let (sql, values) = q.build_sqlx(PostgresQueryBuilder);
            match sqlx::query_scalar_with::<_, i64, _>(&sql, values)
                .fetch_one(&mut **inner)
                .await
            {
                Ok(n) => Ok(n > 0),
                Err(e) => Err(WriteError::Sqlx(e)),
            }
        }
    }
}

/// Parse SQLite constraint messages of the form
/// `<prefix> tbl.col1[, tbl.col2 ...]` into a `Vec<col>`.
fn sqlite_columns_from_message(message: &str, prefix: &str) -> Vec<String> {
    let trimmed_prefix = prefix.trim();
    let Some(suffix) = message
        .strip_prefix(trimmed_prefix)
        .or_else(|| message.strip_prefix(prefix))
    else {
        return Vec::new();
    };
    suffix
        .split(',')
        .map(str::trim)
        .filter_map(|seg| seg.split('.').nth(1))
        .map(str::to_string)
        .collect()
}

/// Pull the column name out of a Postgres constraint identifier
/// shaped like `<table>_<col>_<kind>` where `<kind>` is one of
/// `fkey` / `key` (unique) / `check`. Returns `None` when the
/// shape doesn't match.
fn parse_pg_column_from_constraint(constraint: &str) -> Option<String> {
    for suffix in ["_fkey", "_key", "_check"] {
        if let Some(rest) = constraint.strip_suffix(suffix) {
            return rest.split_once('_').map(|(_, col)| col.to_string());
        }
    }
    None
}

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

    fn col(name: &str, choices: &[&str]) -> Column {
        Column {
            name: name.to_string(),
            ty: SqlType::Text,
            primary_key: false,
            nullable: false,
            noform: false,
            db_constraint: true,
            noedit: false,
            is_string_repr: false,
            max_length: 0,
            fk_target: None,
            on_delete: crate::orm::model::FkAction::NoAction,
            on_update: crate::orm::model::FkAction::NoAction,
            unique: false,
            default: String::new(),
            choices: choices.iter().map(|s| s.to_string()).collect(),
            choice_labels: Vec::new(),
            is_multichoice: false,
            min: None,
            max: None,
            text_format: None,
            slug_from: None,
            auto_now: false,
            auto_now_add: false,
            help: String::new(),
            example: String::new(),
            widget: None,
            index: false,
            supported_backends: Vec::new(),
        }
    }

    fn meta_with(cols: Vec<Column>) -> ModelMeta {
        ModelMeta {
            name: "Test".into(),
            table: "test".into(),
            fields: cols,
            display: "Test".into(),
            icon: "database".into(),
            database: None,
            singleton: false,
            unique_together: Vec::new(),
            indexes: Vec::new(),
            ordering: Vec::new(),
            m2m_relations: Vec::new(),
            soft_delete: false,
            app_label: "app".into(),
        }
    }

    #[test]
    fn choices_validator_catches_typo_against_allowed_set() {
        let meta = meta_with(vec![col("currency", &["usd", "eur", "gbp"])]);
        let mut body = serde_json::Map::new();
        body.insert("currency".into(), serde_json::Value::String("usdd".into()));
        let errors = validate_choices(&meta, &body);
        assert_eq!(errors.len(), 1, "expected one error, got {errors:?}");
        match &errors[0] {
            WriteError::Validator { field, message } => {
                assert_eq!(field, "currency");
                assert!(
                    message.contains("'usdd'"),
                    "message should name the offending value; got {message:?}",
                );
                assert!(
                    message.contains("usd, eur, gbp"),
                    "message should list the allowed set; got {message:?}",
                );
            }
            other => panic!("expected Validator, got {other:?}"),
        }
    }

    #[test]
    fn choices_validator_accepts_a_known_value() {
        let meta = meta_with(vec![col("status", &["draft", "active", "archived"])]);
        let mut body = serde_json::Map::new();
        body.insert("status".into(), serde_json::Value::String("active".into()));
        assert!(validate_choices(&meta, &body).is_empty());
    }

    #[test]
    fn choices_validator_skips_blank_and_missing() {
        let meta = meta_with(vec![col("status", &["draft", "active"])]);
        // Missing key — required-field check handles it; choices
        // shouldn't double-report.
        assert!(validate_choices(&meta, &serde_json::Map::new()).is_empty());
        // Explicit null — same.
        let mut body = serde_json::Map::new();
        body.insert("status".into(), serde_json::Value::Null);
        assert!(validate_choices(&meta, &body).is_empty());
        // Empty string — required-field check's territory.
        let mut body = serde_json::Map::new();
        body.insert("status".into(), serde_json::Value::String(String::new()));
        assert!(validate_choices(&meta, &body).is_empty());
    }

    #[test]
    fn choices_validator_accepts_integer_valued_float() {
        // A column with numeric-looking string choices, fed a JSON number.
        let meta = meta_with(vec![col("level", &["1", "2", "3"])]);
        // serde parses `2` as an integer Number, `2.0` as a float Number —
        // both must normalise to "2" and pass against choice "2".
        let mut body = serde_json::Map::new();
        body.insert("level".into(), serde_json::json!(2));
        assert!(
            validate_choices(&meta, &body).is_empty(),
            "integer 2 should match choice \"2\"",
        );
        let mut body = serde_json::Map::new();
        body.insert("level".into(), serde_json::json!(2.0));
        assert!(
            validate_choices(&meta, &body).is_empty(),
            "float 2.0 should normalise to \"2\" and match",
        );
    }

    #[test]
    fn choices_validator_rejects_fractional_value() {
        let meta = meta_with(vec![col("level", &["1", "2", "3"])]);
        let mut body = serde_json::Map::new();
        body.insert("level".into(), serde_json::json!(2.5));
        let errors = validate_choices(&meta, &body);
        assert_eq!(errors.len(), 1, "2.5 is not a valid choice; got {errors:?}");
    }

    #[test]
    fn choices_validator_skips_columns_without_choices() {
        let meta = meta_with(vec![col("name", &[])]);
        let mut body = serde_json::Map::new();
        body.insert("name".into(), serde_json::Value::String("anything".into()));
        assert!(validate_choices(&meta, &body).is_empty());
    }

    // -------------------------------------------------------------
    // M2M shape validation. The existence check needs a registered
    // ModelMeta on the target table — not feasible here without
    // booting an App, so we exercise the shape branch only. The
    // happy-path FK-existence behaviour is covered by the live
    // integration tests in the REST plugin.
    // -------------------------------------------------------------

    fn meta_with_m2m(field_name: &str, target_table: &str, target_name: &str) -> ModelMeta {
        let mut meta = meta_with(vec![]);
        meta.m2m_relations.push(crate::migrate::M2MRelation {
            field_name: field_name.to_string(),
            target_table: target_table.to_string(),
            target_name: target_name.to_string(),
        });
        meta
    }

    #[tokio::test]
    async fn m2m_rejects_a_scalar_where_an_array_was_expected() {
        let meta = meta_with_m2m("tags", "tag", "Tag");
        let mut body = serde_json::Map::new();
        // `tags: 1` is the bug — a scalar where an array of ids
        // belongs. The framework should call this out, not let
        // the value silently disappear.
        body.insert("tags".into(), serde_json::Value::Number(1.into()));
        let errors = validate_m2m_relations(&meta, &body).await;
        assert_eq!(errors.len(), 1, "expected one shape error, got {errors:?}");
        match &errors[0] {
            WriteError::Validator { field, message } => {
                assert_eq!(field, "tags");
                assert!(
                    message.contains("array")
                        && message.contains("Tag")
                        && message.contains("number"),
                    "message should name the expected shape, the target, and \
                     the kind of the bad value; got {message:?}",
                );
            }
            other => panic!("expected Validator, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn m2m_accepts_an_empty_array() {
        let meta = meta_with_m2m("tags", "tag", "Tag");
        let mut body = serde_json::Map::new();
        body.insert("tags".into(), serde_json::Value::Array(Vec::new()));
        // Empty array is the "no children selected" shape — must
        // not produce an error; the framework just won't write any
        // junction rows.
        assert!(validate_m2m_relations(&meta, &body).await.is_empty());
    }

    #[tokio::test]
    async fn m2m_skips_null_and_missing_values() {
        let meta = meta_with_m2m("tags", "tag", "Tag");
        // Missing key — required-field path is the right home for
        // this (and M2M slots aren't required). Skipped here.
        assert!(
            validate_m2m_relations(&meta, &serde_json::Map::new())
                .await
                .is_empty()
        );
        // Explicit null — same.
        let mut body = serde_json::Map::new();
        body.insert("tags".into(), serde_json::Value::Null);
        assert!(validate_m2m_relations(&meta, &body).await.is_empty());
    }

    #[tokio::test]
    async fn m2m_rejects_an_object_too() {
        let meta = meta_with_m2m("tags", "tag", "Tag");
        let mut body = serde_json::Map::new();
        body.insert("tags".into(), serde_json::json!({ "id": 1 }));
        let errors = validate_m2m_relations(&meta, &body).await;
        assert_eq!(errors.len(), 1);
        match &errors[0] {
            WriteError::Validator { field, message } => {
                assert_eq!(field, "tags");
                assert!(message.contains("object"));
            }
            other => panic!("expected Validator, got {other:?}"),
        }
    }
}