dibs-db-schema 0.1.0

Database schema types for dibs
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
//! Database schema types for dibs.
//!
//! This crate contains the core schema types that are shared between
//! `dibs` (schema introspection) and `dibs-qgen` (query planning).

use dibs_sql::{check_constraint_name, index_name, trigger_check_name, unique_index_name};
use facet::{Facet, Shape, Type, UserType};
use indexmap::IndexMap;
use std::fmt;

// Define the dibs attribute grammar using facet's macro.
// This generates:
// - `Attr` enum with all attribute variants
// - `__attr!` macro for parsing attributes
// - Re-exports for use as `dibs::table`, `dibs::pk`, etc.
facet::define_attr_grammar! {
    ns "dibs";
    crate_path ::dibs;

    /// Dibs schema attribute types.
    pub enum Attr {
        /// Marks a struct as a database table.
        ///
        /// Usage: `#[facet(dibs::table = "table_name")]`
        Table(&'static str),

        /// Marks a field as the primary key.
        ///
        /// Usage: `#[facet(dibs::pk)]`
        Pk,

        /// Marks a field as having a unique constraint.
        ///
        /// Usage: `#[facet(dibs::unique)]`
        Unique,

        /// Marks a field as a foreign key reference.
        ///
        /// Usage: `#[facet(dibs::fk = "other_table.column")]`
        Fk(&'static str),

        /// Marks a field as not null (explicit, inferred for non-Option types).
        ///
        /// Usage: `#[facet(dibs::not_null)]`
        NotNull,

        /// Sets a default value expression for the column.
        ///
        /// Usage: `#[facet(dibs::default = "now()")]`
        Default(&'static str),

        /// Overrides the column name (default: snake_case of field name).
        ///
        /// Usage: `#[facet(dibs::column = "column_name")]`
        Column(&'static str),

        /// Creates an index on a single column (field-level).
        ///
        /// Usage: `#[facet(dibs::index)]` or `#[facet(dibs::index = "index_name")]`
        Index(Option<&'static str>),

        /// Creates an index on one or more columns (container-level).
        ///
        /// Usage:
        /// - `#[facet(dibs::index(columns = "col1,col2"))]` - auto-named composite index
        /// - `#[facet(dibs::index(name = "idx_foo", columns = "col1,col2"))]` - named composite index
        CompositeIndex(CompositeIndex),

        /// Creates a unique constraint on one or more columns (container-level).
        ///
        /// Usage:
        /// - `#[facet(dibs::composite_unique(columns = "col1,col2"))]` - auto-named unique constraint
        /// - `#[facet(dibs::composite_unique(name = "uq_foo", columns = "col1,col2"))]` - named constraint
        CompositeUnique(CompositeUnique),

        /// Creates a CHECK constraint (container-level).
        ///
        /// Usage:
        /// - `#[facet(dibs::check(expr = "foo IS NOT NULL"))]` - auto-named constraint
        /// - `#[facet(dibs::check(name = "ck_foo", expr = "foo IS NOT NULL"))]` - named constraint
        Check(Check),

        /// Creates a trigger-enforced invariant check (container-level).
        ///
        /// This is for cross-row or cross-table invariants that cannot be expressed as
        /// a SQL CHECK constraint (which is limited to the current row).
        ///
        /// Usage:
        /// - `#[facet(dibs::trigger_check(name = "trg_my_check", expr = "NEW.foo IS NULL OR EXISTS (...)"))]`
        TriggerCheck(TriggerCheck),

        /// Marks a field as auto-generated (e.g., SERIAL, sequences).
        ///
        /// Usage: `#[facet(dibs::auto)]`
        Auto,

        /// Marks a text field as "long" (renders as textarea in admin UI).
        ///
        /// Usage: `#[facet(dibs::long)]`
        Long,

        /// Marks a field as the display label for the row (used in FK references).
        ///
        /// Usage: `#[facet(dibs::label)]`
        Label,

        /// Specifies the language/format of a text field (e.g., "markdown", "json").
        /// Implies `long` - will render with a code editor in admin UI.
        ///
        /// Usage: `#[facet(dibs::lang = "markdown")]`
        Lang(&'static str),

        /// Specifies a Lucide icon name for display in the admin UI.
        /// Can be used on fields or containers (tables).
        ///
        /// Usage: `#[facet(dibs::icon = "user")]`
        Icon(&'static str),

        /// Specifies the semantic subtype of a column.
        /// Sets a default icon (can be overridden with explicit `dibs::icon`).
        ///
        /// Supported subtypes:
        /// - Contact: `email`, `phone`, `url`, `website`, `username`
        /// - Media: `image`, `avatar`, `file`, `video`
        /// - Money: `currency`, `money`, `price`, `percent`
        /// - Security: `password`, `secret`, `token`
        /// - Code: `code`, `json`, `markdown`, `html`
        /// - Location: `address`, `country`, `ip`
        /// - Content: `slug`, `color`, `tag`
        ///
        /// Usage: `#[facet(dibs::subtype = "email")]`
        Subtype(&'static str),
    }

    /// Composite index definition for multi-column indices.
    pub struct CompositeIndex {
        /// Optional index name (auto-generated if not provided)
        pub name: Option<&'static str>,
        /// Comma-separated column names
        pub columns: &'static str,
        /// Optional WHERE clause for partial index (PostgreSQL-specific)
        ///
        /// Example: `filter = "is_active = true"` creates `CREATE INDEX ... WHERE is_active = true`
        pub filter: Option<&'static str>,
    }

    /// Composite unique constraint for multi-column uniqueness.
    ///
    /// Usage:
    /// - `#[facet(dibs::composite_unique(columns = "col1,col2"))]` - auto-named unique constraint
    /// - `#[facet(dibs::composite_unique(name = "uq_foo", columns = "col1,col2"))]` - named constraint
    /// - `#[facet(dibs::composite_unique(columns = "col", filter = "is_primary = true"))]` - partial unique
    pub struct CompositeUnique {
        /// Optional constraint name (auto-generated if not provided)
        pub name: Option<&'static str>,
        /// Comma-separated column names
        pub columns: &'static str,
        /// Optional WHERE clause for partial unique index (PostgreSQL-specific)
        ///
        /// Example: `filter = "is_active = true"` creates `CREATE UNIQUE INDEX ... WHERE is_active = true`
        pub filter: Option<&'static str>,
    }

    /// CHECK constraint definition.
    pub struct Check {
        /// Optional constraint name (auto-generated if not provided)
        pub name: Option<&'static str>,
        /// SQL expression for CHECK(...)
        pub expr: &'static str,
    }

    /// Trigger-enforced check definition.
    pub struct TriggerCheck {
        /// Optional trigger name (auto-generated if not provided)
        pub name: Option<&'static str>,
        /// Boolean SQL expression evaluated in a `BEFORE INSERT OR UPDATE` trigger.
        ///
        /// Use `NEW.<column>` to reference the new row, and `OLD.<column>` for updates.
        pub expr: &'static str,
        /// Optional error message raised when the expression evaluates to false.
        pub message: Option<&'static str>,
    }
}

/// Postgres column types.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PgType {
    /// SMALLINT (2 bytes)
    SmallInt,
    /// INTEGER (4 bytes)
    Integer,
    /// BIGINT (8 bytes)
    BigInt,
    /// REAL (4 bytes floating point)
    Real,
    /// DOUBLE PRECISION (8 bytes floating point)
    DoublePrecision,
    /// NUMERIC (arbitrary precision)
    Numeric,
    /// BOOLEAN
    Boolean,
    /// TEXT
    Text,
    /// BYTEA (binary)
    Bytea,
    /// TIMESTAMPTZ
    Timestamptz,
    /// DATE
    Date,
    /// TIME
    Time,
    /// UUID
    Uuid,
    /// JSONB
    Jsonb,
    /// TEXT[] (array of text)
    TextArray,
    /// BIGINT[] (array of bigint)
    BigIntArray,
    /// INTEGER[] (array of integer)
    IntegerArray,
}

impl PgType {
    /// Map this Postgres type to a Rust type string.
    ///
    /// These names match what's exported in `dibs_runtime::prelude`.
    pub fn to_rust_type(&self) -> &'static str {
        match self {
            PgType::SmallInt => "i16",
            PgType::Integer => "i32",
            PgType::BigInt => "i64",
            PgType::Real => "f32",
            PgType::DoublePrecision => "f64",
            PgType::Numeric => "Decimal",
            PgType::Boolean => "bool",
            PgType::Text => "String",
            PgType::Bytea => "Vec<u8>",
            PgType::Timestamptz => "Timestamp",
            PgType::Date => "Date",
            PgType::Time => "Time",
            PgType::Uuid => "Uuid",
            PgType::Jsonb => "Jsonb<facet_value::Value>",
            PgType::TextArray => "Vec<String>",
            PgType::BigIntArray => "Vec<i64>",
            PgType::IntegerArray => "Vec<i32>",
        }
    }

    /// True for the integer types that can back a `GENERATED AS IDENTITY` column.
    pub fn is_integer(&self) -> bool {
        matches!(self, PgType::SmallInt | PgType::Integer | PgType::BigInt)
    }
}

impl fmt::Display for PgType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PgType::SmallInt => write!(f, "SMALLINT"),
            PgType::Integer => write!(f, "INTEGER"),
            PgType::BigInt => write!(f, "BIGINT"),
            PgType::Real => write!(f, "REAL"),
            PgType::DoublePrecision => write!(f, "DOUBLE PRECISION"),
            PgType::Numeric => write!(f, "NUMERIC"),
            PgType::Boolean => write!(f, "BOOLEAN"),
            PgType::Text => write!(f, "TEXT"),
            PgType::Bytea => write!(f, "BYTEA"),
            PgType::Timestamptz => write!(f, "TIMESTAMPTZ"),
            PgType::Date => write!(f, "DATE"),
            PgType::Time => write!(f, "TIME"),
            PgType::Uuid => write!(f, "UUID"),
            PgType::Jsonb => write!(f, "JSONB"),
            PgType::TextArray => write!(f, "TEXT[]"),
            PgType::BigIntArray => write!(f, "BIGINT[]"),
            PgType::IntegerArray => write!(f, "INTEGER[]"),
        }
    }
}

/// A database column definition.
#[derive(Debug, Clone, PartialEq)]
pub struct Column {
    /// Column name
    pub name: String,
    /// Postgres type
    pub pg_type: PgType,
    /// Rust type name (if known, e.g., from reflection)
    pub rust_type: Option<String>,
    /// Whether the column allows NULL
    pub nullable: bool,
    /// Default value expression (if any)
    pub default: Option<String>,
    /// Whether this is a primary key
    pub primary_key: bool,
    /// Whether this has a unique constraint
    pub unique: bool,
    /// Whether this column is auto-generated (serial, identity, uuid default, etc.)
    pub auto_generated: bool,
    /// Whether this is a long text field (use textarea)
    pub long: bool,
    /// Whether this column should be used as the display label
    pub label: bool,
    /// Enum variants (if this is an enum type)
    pub enum_variants: Vec<String>,
    /// Doc comment (if any)
    pub doc: Option<String>,
    /// Language/format for code editor (e.g., "markdown", "json")
    pub lang: Option<String>,
    /// Lucide icon name for display in admin UI (explicit or derived from subtype)
    pub icon: Option<String>,
    /// Semantic subtype of the column (e.g., "email", "url", "password")
    pub subtype: Option<String>,
}

impl Column {
    /// True when this column should be emitted as a `GENERATED BY DEFAULT AS
    /// IDENTITY` column in DDL.
    ///
    /// `auto_generated` is overloaded — it's also set for columns whose values
    /// the database supplies via a `DEFAULT` (e.g. `now()`, `gen_random_uuid()`).
    /// Those keep their `DEFAULT` clause; only an auto-generated *integer* column
    /// with no explicit default becomes an identity column.
    pub fn is_identity(&self) -> bool {
        self.auto_generated && self.default.is_none() && self.pg_type.is_integer()
    }
}

/// A foreign key constraint.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ForeignKey {
    /// Column(s) in this table
    pub columns: Vec<String>,
    /// Referenced table
    pub references_table: String,
    /// Referenced column(s)
    pub references_columns: Vec<String>,
}

/// Sort order for index columns.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SortOrder {
    /// Ascending order (default)
    #[default]
    Asc,
    /// Descending order
    Desc,
}

impl SortOrder {
    /// Returns the SQL keyword for this sort order, or empty string for ASC (default).
    pub fn to_sql(&self) -> &'static str {
        match self {
            SortOrder::Asc => "",
            SortOrder::Desc => " DESC",
        }
    }
}

/// Nulls ordering for index columns.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum NullsOrder {
    /// Use database default (NULLS LAST for ASC, NULLS FIRST for DESC)
    #[default]
    Default,
    /// Sort nulls before non-null values
    First,
    /// Sort nulls after non-null values
    Last,
}

impl NullsOrder {
    /// Returns the SQL clause for this nulls ordering, or empty string for default.
    pub fn to_sql(&self) -> &'static str {
        match self {
            NullsOrder::Default => "",
            NullsOrder::First => " NULLS FIRST",
            NullsOrder::Last => " NULLS LAST",
        }
    }
}

/// A column in an index with optional sort order and nulls ordering.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IndexColumn {
    /// Column name
    pub name: String,
    /// Sort order (ASC or DESC)
    pub order: SortOrder,
    /// Nulls ordering (NULLS FIRST, NULLS LAST, or default)
    pub nulls: NullsOrder,
}

impl IndexColumn {
    /// Create a new index column with default (ASC) ordering and default nulls.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            order: SortOrder::Asc,
            nulls: NullsOrder::Default,
        }
    }

    /// Create a new index column with DESC ordering and default nulls.
    pub fn desc(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            order: SortOrder::Desc,
            nulls: NullsOrder::Default,
        }
    }

    /// Create a new index column with NULLS FIRST ordering.
    pub fn nulls_first(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            order: SortOrder::Asc,
            nulls: NullsOrder::First,
        }
    }

    /// Returns the SQL fragment for this column (name + order + nulls).
    pub fn to_sql(&self, quote_ident: impl Fn(&str) -> String) -> String {
        format!(
            "{}{}{}",
            quote_ident(&self.name),
            self.order.to_sql(),
            self.nulls.to_sql()
        )
    }

    /// Parse a column specification like "col_name", "col_name DESC", or "col_name DESC NULLS FIRST".
    pub fn parse(spec: &str) -> Self {
        let spec = spec.trim();
        let upper = spec.to_uppercase();

        // Parse nulls ordering first (it comes at the end)
        let (spec_without_nulls, nulls) = if upper.ends_with(" NULLS FIRST") {
            (&spec[..spec.len() - 12], NullsOrder::First)
        } else if upper.ends_with(" NULLS LAST") {
            (&spec[..spec.len() - 11], NullsOrder::Last)
        } else {
            (spec, NullsOrder::Default)
        };

        let trimmed = spec_without_nulls.trim();
        let upper_trimmed = trimmed.to_uppercase();

        // Parse sort order
        let (name, order) = if upper_trimmed.ends_with(" DESC") {
            (
                trimmed[..trimmed.len() - 5].trim().to_string(),
                SortOrder::Desc,
            )
        } else if upper_trimmed.ends_with(" ASC") {
            (
                trimmed[..trimmed.len() - 4].trim().to_string(),
                SortOrder::Asc,
            )
        } else {
            (trimmed.to_string(), SortOrder::Asc)
        };

        fn unquote_pg_ident_if_quoted(s: &str) -> String {
            let s = s.trim();
            if s.len() >= 2 && s.starts_with('"') && s.ends_with('"') {
                let inner = &s[1..s.len() - 1];
                return inner.replace("\"\"", "\"");
            }
            s.to_string()
        }

        Self {
            name: unquote_pg_ident_if_quoted(&name),
            order,
            nulls,
        }
    }
}

/// A database index.
#[derive(Debug, Clone, PartialEq)]
pub struct Index {
    /// Index name
    pub name: String,
    /// Column(s) in the index with sort order
    pub columns: Vec<IndexColumn>,
    /// Whether this is a unique index
    pub unique: bool,
    /// Optional WHERE clause for partial indexes (PostgreSQL-specific)
    pub where_clause: Option<String>,
}

/// Source location of a schema element.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct SourceLocation {
    /// Source file path
    pub file: Option<String>,
    /// Line number (1-indexed)
    pub line: Option<u32>,
    /// Column number (1-indexed)
    pub column: Option<u32>,
}

impl SourceLocation {
    /// Check if we have any source location info.
    pub fn is_known(&self) -> bool {
        self.file.is_some()
    }

    /// Format as "file:line" or "file:line:column"
    pub fn to_string_short(&self) -> Option<String> {
        let file = self.file.as_ref()?;
        match (self.line, self.column) {
            (Some(line), Some(col)) => Some(format!("{}:{}:{}", file, line, col)),
            (Some(line), None) => Some(format!("{}:{}", file, line)),
            _ => Some(file.clone()),
        }
    }
}

impl fmt::Display for SourceLocation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.to_string_short() {
            Some(s) => write!(f, "{}", s),
            None => write!(f, "<unknown>"),
        }
    }
}

/// A table CHECK constraint.
#[derive(Debug, Clone, PartialEq)]
pub struct CheckConstraint {
    pub name: String,
    pub expr: String,
}

/// A trigger-enforced invariant check (BEFORE INSERT OR UPDATE).
#[derive(Debug, Clone, PartialEq)]
pub struct TriggerCheckConstraint {
    pub name: String,
    pub expr: String,
    pub message: Option<String>,
}

/// A database table definition.
#[derive(Debug, Clone, PartialEq)]
pub struct Table {
    /// Table name
    pub name: String,
    /// Columns
    pub columns: Vec<Column>,
    /// CHECK constraints
    pub check_constraints: Vec<CheckConstraint>,
    /// Trigger-enforced checks
    pub trigger_checks: Vec<TriggerCheckConstraint>,
    /// Foreign keys
    pub foreign_keys: Vec<ForeignKey>,
    /// Indices
    pub indices: Vec<Index>,
    /// Source location of the Rust struct
    pub source: SourceLocation,
    /// Doc comment from the Rust struct
    pub doc: Option<String>,
    /// Lucide icon name for display in admin UI
    pub icon: Option<String>,
}

/// A complete database schema.
#[derive(Debug, Clone, Default)]
pub struct Schema {
    /// Tables in the schema, indexed by name
    pub tables: IndexMap<String, Table>,
}

impl Schema {
    /// Create a new empty schema.
    pub fn new() -> Self {
        Self::default()
    }

    /// Get a table by name.
    pub fn get_table(&self, name: &str) -> Option<&Table> {
        self.tables.get(name)
    }

    /// Iterate over all tables.
    pub fn iter_tables(&self) -> impl Iterator<Item = &Table> {
        self.tables.values()
    }
}

// =============================================================================
// Table definition registration
// =============================================================================

/// A registered table definition.
///
/// This is submitted to inventory by types marked with `#[facet(dibs::table)]`.
pub struct TableDef {
    /// The facet shape of the table struct.
    pub shape: &'static Shape,
}

impl TableDef {
    /// Create a new table definition from a Facet type.
    pub const fn new<T: Facet<'static>>() -> Self {
        Self { shape: T::SHAPE }
    }

    /// Get the table name from the `dibs::table` attribute.
    pub fn table_name(&self) -> Option<&'static str> {
        shape_get_dibs_attr_str(self.shape, "table")
    }

    /// Convert this definition to a Table struct.
    pub fn to_table(&self) -> Option<Table> {
        let table_name = self.table_name()?.to_string();

        // Get the struct type to access fields
        let struct_type = match &self.shape.ty {
            Type::User(UserType::Struct(s)) => s,
            _ => return None,
        };

        let mut columns = Vec::new();
        let mut check_constraints = Vec::new();
        let mut trigger_checks = Vec::new();
        let mut foreign_keys = Vec::new();
        let mut indices = Vec::new();

        // Collect container-level composite indices
        for attr in self.shape.attributes.iter() {
            if attr.ns == Some("dibs")
                && attr.key == "composite_index"
                && let Some(Attr::CompositeIndex(composite)) = attr.get_as::<Attr>()
            {
                let cols: Vec<IndexColumn> = composite
                    .columns
                    .split(',')
                    .map(IndexColumn::parse)
                    .collect();
                let col_names: Vec<&str> = cols.iter().map(|c| c.name.as_str()).collect();
                let idx_name = composite
                    .name
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| index_name(&table_name, &col_names));
                indices.push(Index {
                    name: idx_name,
                    columns: cols,
                    unique: false,
                    where_clause: composite.filter.map(|s| s.to_string()),
                });
            }
            // Collect container-level composite unique constraints
            if attr.ns == Some("dibs")
                && attr.key == "composite_unique"
                && let Some(Attr::CompositeUnique(composite)) = attr.get_as::<Attr>()
            {
                let cols: Vec<IndexColumn> = composite
                    .columns
                    .split(',')
                    .map(IndexColumn::parse)
                    .collect();
                let col_names: Vec<&str> = cols.iter().map(|c| c.name.as_str()).collect();
                let idx_name = composite
                    .name
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| unique_index_name(&table_name, &col_names));
                indices.push(Index {
                    name: idx_name,
                    columns: cols,
                    unique: true,
                    where_clause: composite.filter.map(|s| s.to_string()),
                });
            }

            // Collect container-level CHECK constraints
            if attr.ns == Some("dibs")
                && attr.key == "check"
                && let Some(Attr::Check(check)) = attr.get_as::<Attr>()
            {
                let expr = unescape_rust_string_escapes(check.expr);
                let name = check
                    .name
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| check_constraint_name(&table_name, &expr));
                check_constraints.push(CheckConstraint { name, expr });
            }

            // Collect container-level trigger-enforced checks
            if attr.ns == Some("dibs")
                && attr.key == "trigger_check"
                && let Some(Attr::TriggerCheck(trig)) = attr.get_as::<Attr>()
            {
                let expr = unescape_rust_string_escapes(trig.expr);
                let name = trig
                    .name
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| trigger_check_name(&table_name, &expr));
                trigger_checks.push(TriggerCheckConstraint {
                    name,
                    expr,
                    message: trig.message.map(unescape_rust_string_escapes),
                });
            }
        }

        for field in struct_type.fields {
            let field_shape = field.shape.get();

            // Determine column name
            let col_name = field_get_dibs_attr_str(field, "column")
                .map(|s| s.to_string())
                .unwrap_or_else(|| field.name.to_string());

            // Determine if nullable (Option<T> types)
            let (inner_shape, nullable) = unwrap_option(field_shape);

            // Map type to Postgres
            let pg_type = match shape_to_pg_type(inner_shape) {
                Some(pg_type) => pg_type,
                None => {
                    eprintln!(
                        "dibs: unsupported type '{}' for column '{}' in table '{}' ({})",
                        inner_shape,
                        field.name,
                        table_name,
                        self.shape.source_file.unwrap_or("<unknown>")
                    );
                    return None;
                }
            };

            // Check for primary key
            let primary_key = field_has_dibs_attr(field, "pk");

            // Check for unique
            let unique = field_has_dibs_attr(field, "unique");

            // Check for default
            let default = field_get_dibs_attr_str(field, "default").map(|s| s.to_string());

            // Extract doc comment from field
            let doc = if field.doc.is_empty() {
                None
            } else {
                Some(field.doc.join("\n"))
            };

            // Detect auto-generated columns from default or annotation
            let auto_generated =
                is_auto_generated_default(&default) || field_has_dibs_attr(field, "auto");

            // Check for lang annotation (implies long)
            let lang = field_get_dibs_attr_str(field, "lang").map(|s| s.to_string());

            // Check for long text annotation (or implied by lang)
            let long = field_has_dibs_attr(field, "long") || lang.is_some();

            // Check for label annotation
            let label = field_has_dibs_attr(field, "label");

            // Check for subtype annotation
            let subtype = field_get_dibs_attr_str(field, "subtype").map(|s| s.to_string());

            // Check for explicit icon annotation, or derive from subtype
            let explicit_icon = field_get_dibs_attr_str(field, "icon").map(|s| s.to_string());
            let icon = explicit_icon.or_else(|| {
                subtype
                    .as_ref()
                    .and_then(|st| subtype_default_icon(st).map(|s| s.to_string()))
            });

            // Check for enum variants
            let enum_variants = extract_enum_variants(inner_shape);

            // Use pg_type's rust representation for consistency
            let rust_type = pg_type.to_rust_type().to_string();

            columns.push(Column {
                name: col_name.clone(),
                pg_type,
                rust_type: Some(rust_type),
                nullable,
                default,
                primary_key,
                unique,
                auto_generated,
                long,
                label,
                enum_variants,
                doc,
                lang,
                icon,
                subtype,
            });

            // Check for foreign key
            if let Some(fk_ref) = field_get_dibs_attr_str(field, "fk") {
                // Parse FK reference - supports both "table.column" and "table(column)" formats
                let parsed = parse_fk_reference(fk_ref);
                match parsed {
                    Some((ref_table, ref_col)) => {
                        foreign_keys.push(ForeignKey {
                            columns: vec![field.name.to_string()],
                            references_table: ref_table.to_string(),
                            references_columns: vec![ref_col.to_string()],
                        });
                    }
                    None => {
                        // FIXME: ... nice error handling you've got there
                        eprintln!(
                            "dibs: invalid FK format '{}' for field '{}' in table '{}' - expected 'table.column' or 'table(column)' ({})",
                            fk_ref,
                            field.name,
                            table_name,
                            self.shape.source_file.unwrap_or("<unknown>")
                        );
                    }
                }
            }

            // Check for field-level index
            if field_has_dibs_attr(field, "index") {
                let idx_name = field_get_dibs_attr_str(field, "index")
                    .filter(|s| !s.is_empty())
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| crate::index_name(&table_name, &[&col_name]));
                indices.push(Index {
                    name: idx_name,
                    columns: vec![IndexColumn::new(col_name.clone())],
                    unique: false,
                    where_clause: None, // Field-level indexes don't support WHERE clause
                });
            }
        }

        // Extract source location from Shape
        let source = SourceLocation {
            file: self.shape.source_file.map(|s| s.to_string()),
            line: self.shape.source_line,
            column: self.shape.source_column,
        };

        // Extract doc comment from Shape
        let doc = if self.shape.doc.is_empty() {
            None
        } else {
            Some(self.shape.doc.join("\n"))
        };

        // Extract container-level icon
        let icon = shape_get_dibs_attr_str(self.shape, "icon").map(|s| s.to_string());

        Some(Table {
            name: table_name,
            columns,
            check_constraints,
            trigger_checks,
            foreign_keys,
            indices,
            source,
            doc,
            icon,
        })
    }
}

/// Unwrap Option<T> to get the inner type and nullability.
fn unwrap_option(lhs: &'static Shape) -> (&'static Shape, bool) {
    let rhs = Option::<()>::SHAPE;

    if lhs.decl_id == rhs.decl_id {
        // Get the inner shape from the Option's inner field
        if let Some(inner) = lhs.inner {
            return (inner, true);
        }
    }
    (lhs, false)
}

#[test]
fn test_unwrap_option() {
    let (inner, success) = unwrap_option(Option::<dibs_jsonb::Jsonb<facet_value::Value>>::SHAPE);
    assert!(success);
    assert_eq!(inner, dibs_jsonb::Jsonb::<facet_value::Value>::SHAPE);
}

/// Get the default Lucide icon name for a subtype.
fn subtype_default_icon(subtype: &str) -> Option<&'static str> {
    match subtype {
        // Contact/Identity
        "email" => Some("mail"),
        "phone" => Some("phone"),
        "url" | "website" => Some("link"),
        "username" => Some("at-sign"),

        // Media
        "image" | "avatar" | "photo" => Some("image"),
        "file" => Some("file"),
        "video" => Some("video"),
        "audio" => Some("music"),

        // Money
        "currency" | "money" | "price" => Some("coins"),
        "percent" | "percentage" => Some("percent"),

        // Security
        "password" => Some("lock"),
        "secret" | "token" | "api_key" => Some("key"),

        // Code/Technical
        "code" => Some("code"),
        "json" => Some("braces"),
        "markdown" | "md" => Some("file-text"),
        "html" => Some("code"),
        "regex" => Some("asterisk"),

        // Location
        "address" => Some("map-pin"),
        "city" => Some("building-2"),
        "country" => Some("flag"),
        "zip" | "postal_code" => Some("hash"),
        "ip" | "ip_address" => Some("globe"),
        "coordinates" | "geo" => Some("map"),

        // Content
        "slug" => Some("link-2"),
        "color" | "hex_color" => Some("palette"),
        "tag" | "tags" => Some("tag"),

        // Identifiers
        "uuid" => Some("fingerprint"),
        "sku" | "barcode" => Some("scan-barcode"),
        "version" => Some("git-branch"),

        // Time
        "duration" => Some("timer"),

        _ => None,
    }
}

// =============================================================================
// Attribute helpers
// =============================================================================

/// Get a string value from a dibs attribute on a shape.
fn shape_get_dibs_attr_str(shape: &Shape, key: &str) -> Option<&'static str> {
    shape.attributes.iter().find_map(|attr| {
        if attr.ns == Some("dibs") && attr.key == key {
            attr.get_as::<&str>().copied()
        } else {
            None
        }
    })
}

/// Check if a field has a dibs attribute.
fn field_has_dibs_attr(field: &facet::Field, key: &str) -> bool {
    field
        .attributes
        .iter()
        .any(|attr| attr.ns == Some("dibs") && attr.key == key)
}

/// Get a string value from a dibs attribute on a field.
fn field_get_dibs_attr_str(field: &facet::Field, key: &str) -> Option<&'static str> {
    field.attributes.iter().find_map(|attr| {
        if attr.ns == Some("dibs") && attr.key == key {
            attr.get_as::<&str>().copied()
        } else {
            None
        }
    })
}

/// Check if a default value indicates an auto-generated column.
fn is_auto_generated_default(default: &Option<String>) -> bool {
    // FIXME: this isn't rigorous at all

    let Some(def) = default else {
        return false;
    };

    let lower = def.to_lowercase();

    // Serial/identity columns use nextval
    if lower.contains("nextval(") {
        return true;
    }

    // UUID generation functions
    if lower.contains("gen_random_uuid()") || lower.contains("uuid_generate_v") {
        return true;
    }

    // Timestamp defaults
    if lower.contains("now()") || lower.contains("current_timestamp") {
        return true;
    }

    false
}

/// Extract enum variants from a shape if it's an enum type.
fn extract_enum_variants(shape: &'static Shape) -> Vec<String> {
    if let Type::User(UserType::Enum(enum_type)) = shape.ty {
        enum_type
            .variants
            .iter()
            .map(|v| v.name.to_string())
            .collect()
    } else {
        vec![]
    }
}

fn unescape_rust_string_escapes(value: &str) -> String {
    if !value.contains('\\') {
        return value.to_string();
    }

    let mut out = String::with_capacity(value.len());
    let mut chars = value.chars();
    while let Some(ch) = chars.next() {
        if ch != '\\' {
            out.push(ch);
            continue;
        }

        match chars.next() {
            Some('\\') => out.push('\\'),
            Some('"') => out.push('"'),
            Some('\'') => out.push('\''),
            Some('n') => out.push('\n'),
            Some('r') => out.push('\r'),
            Some('t') => out.push('\t'),
            Some('0') => out.push('\0'),
            Some(other) => {
                // Unknown escape - keep it as-is.
                out.push('\\');
                out.push(other);
            }
            None => out.push('\\'),
        }
    }

    out
}

/// Parse a foreign key reference string.
///
/// Supports two formats:
/// - `table.column` (dot-separated)
/// - `table(column)` (parentheses)
///
/// Returns `Some((table, column))` on success, `None` on parse failure.
pub fn parse_fk_reference(fk_ref: &str) -> Option<(&str, &str)> {
    // Try "table.column" format first
    if let Some((table, col)) = fk_ref.split_once('.')
        && !table.is_empty()
        && !col.is_empty()
    {
        return Some((table, col));
    }

    // Try "table(column)" format
    if let Some(paren_idx) = fk_ref.find('(')
        && fk_ref.ends_with(')')
    {
        let table = &fk_ref[..paren_idx];
        let col = &fk_ref[paren_idx + 1..fk_ref.len() - 1];
        if !table.is_empty() && !col.is_empty() {
            return Some((table, col));
        }
    }

    None
}

/// Map a Rust type to a Postgres type.
///
/// Takes a Shape to properly handle generic types like `Vec<u8>` and `Jsonb<T>`.
pub fn shape_to_pg_type(shape: &Shape) -> Option<PgType> {
    if shape.decl_id == dibs_jsonb::Jsonb::<()>::SHAPE.decl_id {
        return Some(PgType::Jsonb);
    }

    // Check for Vec<T> types - shape.def is List
    if matches!(&shape.def, facet::Def::List(_)) {
        if let Some(inner) = shape.inner {
            if inner == u8::SHAPE {
                return Some(PgType::Bytea);
            } else if inner == String::SHAPE {
                return Some(PgType::TextArray);
            } else if inner == i64::SHAPE {
                return Some(PgType::BigIntArray);
            } else if inner == i32::SHAPE {
                return Some(PgType::IntegerArray);
            }
        }
        return None;
    }

    // Check for slice &[u8] (bytea)
    if matches!(&shape.def, facet::Def::Slice(_)) {
        if let Some(inner) = shape.inner
            && inner == u8::SHAPE
        {
            return Some(PgType::Bytea);
        }
        return None;
    }

    // Fall back to type matching
    rust_type_to_pg(shape)
}

/// Map a Rust type name to a Postgres type.
pub fn rust_type_to_pg(shape: &Shape) -> Option<PgType> {
    // Integers: SmallInt (2 bytes)
    if shape == i8::SHAPE || shape == u8::SHAPE || shape == i16::SHAPE {
        Some(PgType::SmallInt)
    // Integers: Integer (4 bytes)
    } else if shape == u16::SHAPE || shape == i32::SHAPE {
        Some(PgType::Integer)
    // Integers: BigInt (8 bytes)
    } else if shape == u32::SHAPE
        || shape == i64::SHAPE
        || shape == u64::SHAPE
        || shape == isize::SHAPE
        || shape == usize::SHAPE
    {
        Some(PgType::BigInt)
    // Floats
    } else if shape == f32::SHAPE {
        Some(PgType::Real)
    } else if shape == f64::SHAPE {
        Some(PgType::DoublePrecision)
    } else if shape == bool::SHAPE {
        Some(PgType::Boolean)
    } else if shape == String::SHAPE {
        Some(PgType::Text)
    } else if shape == rust_decimal::Decimal::SHAPE {
        Some(PgType::Numeric)
    } else if shape == jiff::Timestamp::SHAPE || shape == jiff::Zoned::SHAPE {
        Some(PgType::Timestamptz)
    } else if shape == jiff::civil::Date::SHAPE {
        Some(PgType::Date)
    } else if shape == jiff::civil::Time::SHAPE {
        Some(PgType::Time)
    } else if shape == chrono::DateTime::<chrono::Utc>::SHAPE
        || shape == chrono::DateTime::<chrono::Local>::SHAPE
        || shape == chrono::NaiveDateTime::SHAPE
    {
        Some(PgType::Timestamptz)
    } else if shape == chrono::NaiveDate::SHAPE {
        Some(PgType::Date)
    } else if shape == chrono::NaiveTime::SHAPE {
        Some(PgType::Time)
    } else if shape == uuid::Uuid::SHAPE {
        Some(PgType::Uuid)
    } else {
        None
    }
}

// Register TableDef with inventory so it can be collected across crates
inventory::collect!(TableDef);

#[cfg(test)]
mod tests;