seedkit-core 2.1.1

Core library for SeedKit — realistic database seed data generation
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
//! # Schema From a DDL File
//!
//! `--schema-file schema.sql --dialect postgres|mysql|sqlite` builds the
//! schema from `CREATE TABLE`, `CREATE TYPE … AS ENUM`, `CREATE UNIQUE INDEX`,
//! and `ALTER TABLE … ADD CONSTRAINT` / `SET DEFAULT nextval(…)` statements,
//! so seed data can be generated without a running database. Everything else,
//! including a whole `pg_dump --schema-only` preamble, is skipped.
//!
//! The result mirrors what live introspection reports for the same DDL in
//! everything generation depends on: types, nullability, identity columns,
//! keys, uniqueness, enum labels, and CHECK constraints.

use indexmap::IndexMap;
use sqlparser::ast::{
    AlterColumnOperation, AlterTableOperation, ColumnDef, ColumnOption, CreateIndex, CreateTable,
    DataType as SqlType, EnumMember, Expr, ObjectName, ReferentialAction, Statement,
    TableConstraint, UserDefinedTypeRepresentation,
};
use sqlparser::dialect::{Dialect, MySqlDialect, PostgreSqlDialect, SQLiteDialect};
use sqlparser::parser::Parser;
use sqlparser::tokenizer::{Token, Tokenizer};

use crate::error::{Result, SeedKitError};
use crate::schema::types::*;

/// Parse a DDL script written for `database_type`. `namespace` is the
/// PostgreSQL schema the tables belong to (usually `public`).
pub fn parse_schema(
    sql: &str,
    database_type: DatabaseType,
    database_name: &str,
    namespace: &str,
) -> Result<DatabaseSchema> {
    let dialect: Box<dyn Dialect> = match database_type {
        DatabaseType::PostgreSQL => Box::new(PostgreSqlDialect {}),
        DatabaseType::MySQL => Box::new(MySqlDialect {}),
        DatabaseType::SQLite => Box::new(SQLiteDialect {}),
    };
    let mut builder = Builder {
        schema: DatabaseSchema::new(database_type, database_name.to_owned()),
        namespace: namespace.to_owned(),
        deferred: Vec::new(),
    };
    for statement in statements(&strip_client_commands(sql), dialect.as_ref())? {
        builder.apply(statement);
    }
    builder.finish()
}

/// Remove psql meta-commands (`\connect`, `\restrict`) and `COPY … FROM stdin`
/// data blocks, which are not SQL.
fn strip_client_commands(sql: &str) -> String {
    let mut out = String::with_capacity(sql.len());
    let mut in_copy_data = false;
    for line in sql.lines() {
        if in_copy_data {
            // COPY data escapes backslashes, so a line holding only `\.`
            // can only be the end marker.
            in_copy_data = line.trim() != "\\.";
            continue;
        }
        if line.trim_start().starts_with('\\') {
            continue;
        }
        let upper = line.trim_start().to_ascii_uppercase();
        if upper.starts_with("COPY ") && upper.trim_end().ends_with("FROM STDIN;") {
            in_copy_data = true;
            continue;
        }
        out.push_str(line);
        out.push('\n');
    }
    out
}

/// Split the script into statements and parse each one. Statements SeedKit
/// does not need may fail to parse; a `CREATE TABLE` that fails is an error.
fn statements(sql: &str, dialect: &dyn Dialect) -> Result<Vec<Statement>> {
    let tokens = Tokenizer::new(dialect, sql)
        .tokenize()
        .map_err(|e| config_error(format!("could not read the schema file: {e}")))?;
    let mut parsed = Vec::new();
    for chunk in tokens.split(|t| matches!(t, Token::SemiColon)) {
        let text: String = chunk.iter().map(|t| t.to_string()).collect();
        if text.trim().is_empty() {
            continue;
        }
        match Parser::new(dialect)
            .with_tokens(chunk.to_vec())
            .parse_statement()
        {
            Ok(statement) => parsed.push(statement),
            Err(err) if is_create_table(&text) => {
                let preview: String = text.trim().chars().take(120).collect();
                return Err(config_error(format!(
                    "could not parse a CREATE TABLE statement ({err}): {preview}…"
                )));
            }
            Err(_) => {}
        }
    }
    Ok(parsed)
}

fn is_create_table(text: &str) -> bool {
    let words: Vec<String> = text
        .split_whitespace()
        .take(4)
        .map(|w| w.to_ascii_uppercase())
        .collect();
    words.first().is_some_and(|w| w == "CREATE") && words.iter().any(|w| w == "TABLE")
}

fn config_error(message: String) -> SeedKitError {
    SeedKitError::Config { message }
}

/// Changes that name a table, applied once every table is known.
enum Deferred {
    Constraint(String, Box<TableConstraint>),
    UniqueIndex(String, Vec<String>, Option<String>),
    NextvalDefault(String, String),
}

struct Builder {
    schema: DatabaseSchema,
    namespace: String,
    deferred: Vec<Deferred>,
}

impl Builder {
    fn apply(&mut self, statement: Statement) {
        match statement {
            Statement::CreateType {
                name,
                representation: Some(UserDefinedTypeRepresentation::Enum { labels }),
            } => {
                let labels = labels.into_iter().map(|l| l.value).collect();
                self.schema.enums.insert(last_part(&name), labels);
            }
            Statement::CreateTable(table) => self.create_table(table),
            Statement::CreateIndex(index) => self.create_index(index),
            Statement::AlterTable(alter) => {
                let table = last_part(&alter.name);
                for operation in alter.operations {
                    match operation {
                        AlterTableOperation::AddConstraint { constraint, .. } => self
                            .deferred
                            .push(Deferred::Constraint(table.clone(), Box::new(constraint))),
                        AlterTableOperation::AlterColumn {
                            column_name,
                            op: AlterColumnOperation::SetDefault { value },
                        } if value.to_string().to_ascii_lowercase().contains("nextval(") => self
                            .deferred
                            .push(Deferred::NextvalDefault(table.clone(), column_name.value)),
                        _ => {}
                    }
                }
            }
            _ => {}
        }
    }

    fn create_table(&mut self, create: CreateTable) {
        let name = last_part(&create.name);
        if self.schema.database_type == DatabaseType::SQLite
            && super::sqlite::is_internal_table(&name)
        {
            return;
        }
        let mut table = Table::new(name.clone());
        if self.schema.database_type == DatabaseType::PostgreSQL {
            table.schema_name = Some(self.namespace.clone());
        }
        for (index, def) in create.columns.iter().enumerate() {
            let column = self.column(def, index);
            for option in &def.options {
                if matches!(option.option, ColumnOption::PrimaryKey(_)) {
                    table.primary_key = Some(PrimaryKey {
                        columns: vec![def.name.value.clone()],
                        name: None,
                    });
                }
                match &option.option {
                    ColumnOption::Unique(_) => table.unique_constraints.push(UniqueConstraint {
                        name: option.name.as_ref().map(|n| n.value.clone()),
                        columns: vec![def.name.value.clone()],
                    }),
                    ColumnOption::ForeignKey(fk) => table.foreign_keys.push(
                        self.foreign_key(
                            option
                                .name
                                .as_ref()
                                .or(fk.name.as_ref())
                                .map(|n| n.value.clone()),
                            vec![def.name.value.clone()],
                            &fk.foreign_table,
                            fk.referred_columns
                                .iter()
                                .map(|c| c.value.clone())
                                .collect(),
                            fk.on_delete,
                            fk.on_update,
                            fk.characteristics.as_ref().and_then(|c| c.deferrable),
                        ),
                    ),
                    ColumnOption::Check(check) => table.check_constraints.push(check_constraint(
                        option
                            .name
                            .as_ref()
                            .or(check.name.as_ref())
                            .map(|n| n.value.clone()),
                        &check.expr,
                    )),
                    _ => {}
                }
            }
            table.columns.insert(column.name.clone(), column);
        }
        for constraint in create.constraints {
            self.table_constraint(&mut table, constraint);
        }
        self.schema.tables.insert(name, table);
    }

    fn column(&self, def: &ColumnDef, index: usize) -> Column {
        let db = self.schema.database_type;
        let declared = def.data_type.to_string();
        let lower = declared.to_ascii_lowercase();
        let is_array = lower.ends_with("[]");
        let base = base_type(lower.trim_end_matches("[]"));
        let mut auto_increment = false;
        let mut enum_values = None;

        let data_type = match (db, base.as_str()) {
            (DatabaseType::PostgreSQL, "serial" | "serial4") => {
                auto_increment = true;
                DataType::Integer
            }
            (DatabaseType::PostgreSQL, "bigserial" | "serial8") => {
                auto_increment = true;
                DataType::BigInt
            }
            (DatabaseType::PostgreSQL, "smallserial" | "serial2") => {
                auto_increment = true;
                DataType::SmallInt
            }
            // MySQL stores BOOLEAN as TINYINT(1) and reports it that way.
            (DatabaseType::MySQL, "boolean" | "bool") => DataType::SmallInt,
            (DatabaseType::MySQL, "enum" | "set") => {
                enum_values = match &def.data_type {
                    SqlType::Enum(members, _) => Some(enum_labels(members)),
                    SqlType::Set(labels) => Some(labels.clone()),
                    _ => None,
                };
                DataType::Enum(def.name.value.clone())
            }
            (_, name) => match self.enum_type(name) {
                Some((type_name, labels)) if !is_array => {
                    enum_values = Some(labels);
                    DataType::Enum(type_name)
                }
                _ if is_array => DataType::Array(Box::new(DataType::from_raw(name))),
                _ => DataType::from_raw(name),
            },
        };

        let raw_type = match db {
            DatabaseType::PostgreSQL => postgres_type_name(&data_type),
            DatabaseType::MySQL => mysql_type_name(&base),
            DatabaseType::SQLite => declared.clone(),
        };
        let mut column = Column::new(def.name.value.clone(), data_type.clone(), raw_type);
        column.enum_values = enum_values;
        column.ordinal_position = match db {
            DatabaseType::SQLite => index as u32,
            _ => index as u32 + 1,
        };
        let (length, precision, scale) = type_arguments(&lower);
        if db != DatabaseType::SQLite && matches!(data_type, DataType::VarChar | DataType::Char) {
            column.max_length = length.or((data_type == DataType::Char).then_some(1));
        }
        if db == DatabaseType::MySQL {
            // MySQL reports a character length for these types too.
            column.max_length = match base.as_str() {
                "tinytext" => Some(255),
                "text" => Some(65_535),
                "mediumtext" => Some(16_777_215),
                "longtext" => Some(4_294_967_295),
                "enum" => column
                    .enum_values
                    .as_ref()
                    .and_then(|labels| labels.iter().map(|l| l.chars().count() as u32).max()),
                "set" => column.enum_values.as_ref().map(|labels| {
                    labels.iter().map(|l| l.chars().count() as u32).sum::<u32>()
                        + labels.len().saturating_sub(1) as u32
                }),
                _ => column.max_length,
            };
        }
        if data_type == DataType::Numeric {
            column.numeric_precision = precision;
            column.numeric_scale = precision.map(|_| scale.unwrap_or(0));
        }

        for option in &def.options {
            match &option.option {
                ColumnOption::NotNull => column.nullable = false,
                ColumnOption::Null => column.nullable = true,
                ColumnOption::Default(_) => column.has_default = true,
                // SQLite reports a primary key column as nullable unless the
                // DDL says NOT NULL, so only the other databases imply it.
                ColumnOption::PrimaryKey(_) if db != DatabaseType::SQLite => {
                    column.nullable = false
                }
                ColumnOption::Generated {
                    generation_expr, ..
                } => {
                    if generation_expr.is_some() {
                        column.is_generated = true;
                    } else {
                        // GENERATED … AS IDENTITY
                        auto_increment = true;
                        column.has_default = db == DatabaseType::PostgreSQL;
                        column.nullable = false;
                    }
                }
                other => {
                    let text = other.to_string().to_ascii_uppercase();
                    if text.contains("AUTO_INCREMENT") || text.contains("AUTOINCREMENT") {
                        auto_increment = true;
                    }
                }
            }
        }
        if auto_increment && db == DatabaseType::PostgreSQL {
            // A serial column defaults to nextval(…) and is NOT NULL.
            column.has_default = true;
            column.nullable = false;
        }
        if auto_increment && db == DatabaseType::MySQL {
            column.nullable = false;
        }
        column.is_auto_increment = auto_increment;
        column
    }

    fn enum_type(&self, name: &str) -> Option<(String, Vec<String>)> {
        let unqualified = name.rsplit('.').next().unwrap_or(name).trim_matches('"');
        self.schema
            .enums
            .iter()
            .find(|(type_name, _)| type_name.eq_ignore_ascii_case(unqualified))
            .map(|(type_name, labels)| (type_name.clone(), labels.clone()))
    }

    fn table_constraint(&self, table: &mut Table, constraint: TableConstraint) {
        match constraint {
            TableConstraint::PrimaryKey(pk) => {
                let columns = index_columns(&pk.columns);
                if self.schema.database_type != DatabaseType::SQLite {
                    for name in &columns {
                        if let Some(column) = table.columns.get_mut(name) {
                            column.nullable = false;
                        }
                    }
                }
                table.primary_key = Some(PrimaryKey {
                    columns,
                    name: pk.name.map(|n| n.value),
                });
            }
            TableConstraint::Unique(unique) => table.unique_constraints.push(UniqueConstraint {
                name: unique.name.map(|n| n.value),
                columns: index_columns(&unique.columns),
            }),
            TableConstraint::ForeignKey(fk) => table.foreign_keys.push(
                self.foreign_key(
                    fk.name.map(|n| n.value),
                    fk.columns.iter().map(|c| c.value.clone()).collect(),
                    &fk.foreign_table,
                    fk.referred_columns
                        .iter()
                        .map(|c| c.value.clone())
                        .collect(),
                    fk.on_delete,
                    fk.on_update,
                    fk.characteristics.as_ref().and_then(|c| c.deferrable),
                ),
            ),
            TableConstraint::Check(check) => table
                .check_constraints
                .push(check_constraint(check.name.map(|n| n.value), &check.expr)),
            _ => {}
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn foreign_key(
        &self,
        name: Option<String>,
        source_columns: Vec<String>,
        target: &ObjectName,
        referenced_columns: Vec<String>,
        on_delete: Option<ReferentialAction>,
        on_update: Option<ReferentialAction>,
        deferrable: Option<bool>,
    ) -> ForeignKey {
        let parts: Vec<String> = target.0.iter().map(|p| p.to_string()).collect();
        let referenced_schema = match parts.as_slice() {
            [qualifier, _] if self.schema.database_type == DatabaseType::PostgreSQL => {
                let qualifier = qualifier.trim_matches('"');
                (qualifier != self.namespace).then(|| qualifier.to_owned())
            }
            _ => None,
        };
        ForeignKey {
            name,
            source_columns,
            referenced_schema,
            referenced_table: last_part(target),
            referenced_columns,
            on_delete: action(on_delete),
            on_update: action(on_update),
            is_deferrable: deferrable.unwrap_or(false),
        }
    }

    fn create_index(&mut self, index: CreateIndex) {
        if !index.unique || index.predicate.is_some() {
            return;
        }
        let columns: Option<Vec<String>> = index
            .columns
            .iter()
            .map(|c| match &c.column.expr {
                Expr::Identifier(ident) => Some(ident.value.clone()),
                _ => None,
            })
            .collect();
        // Expression indexes are skipped, as with live introspection.
        if let Some(columns) = columns {
            self.deferred.push(Deferred::UniqueIndex(
                last_part(&index.table_name),
                columns,
                index.name.as_ref().map(last_part),
            ));
        }
    }

    fn finish(mut self) -> Result<DatabaseSchema> {
        for change in std::mem::take(&mut self.deferred) {
            match change {
                Deferred::Constraint(table_name, constraint) => {
                    if let Some(mut table) = self.schema.tables.shift_remove(&table_name) {
                        self.table_constraint(&mut table, *constraint);
                        self.schema.tables.insert(table_name, table);
                    }
                }
                Deferred::UniqueIndex(table_name, columns, name) => {
                    if let Some(table) = self.schema.tables.get_mut(&table_name) {
                        table
                            .unique_constraints
                            .push(UniqueConstraint { name, columns });
                    }
                }
                Deferred::NextvalDefault(table_name, column_name) => {
                    if let Some(column) = self
                        .schema
                        .tables
                        .get_mut(&table_name)
                        .and_then(|t| t.columns.get_mut(&column_name))
                    {
                        column.is_auto_increment = true;
                        column.has_default = true;
                    }
                }
            }
        }
        self.restore_table_order();
        let schema = &mut self.schema;
        // REFERENCES parent without a column list targets the parent's key.
        let primary_keys: IndexMap<String, Vec<String>> = schema
            .tables
            .iter()
            .filter_map(|(name, t)| Some((name.clone(), t.primary_key.as_ref()?.columns.clone())))
            .collect();
        for table in schema.tables.values_mut() {
            for fk in &mut table.foreign_keys {
                if fk.referenced_columns.is_empty() {
                    fk.referenced_columns = primary_keys
                        .get(&fk.referenced_table)
                        .cloned()
                        .ok_or_else(|| {
                            config_error(format!(
                                "{}.{} references {} without naming columns, and {} has no primary key",
                                table.name,
                                fk.source_columns.join(", "),
                                fk.referenced_table,
                                fk.referenced_table
                            ))
                        })?;
                }
            }
        }
        if schema.database_type == DatabaseType::SQLite {
            for table in schema.tables.values_mut() {
                let Some(pk) = table.primary_key.clone() else {
                    continue;
                };
                let rowid_alias = match pk.columns.as_slice() {
                    [key] => table
                        .columns
                        .get(key)
                        .is_some_and(|c| c.raw_type.eq_ignore_ascii_case("integer")),
                    _ => false,
                };
                if rowid_alias {
                    // An INTEGER PRIMARY KEY aliases the rowid, so SQLite assigns it.
                    if let Some(column) = table.columns.get_mut(&pk.columns[0]) {
                        column.is_auto_increment = true;
                    }
                } else {
                    // Any other key is backed by a unique index, which
                    // introspection reports as a unique constraint.
                    table.unique_constraints.push(UniqueConstraint {
                        name: None,
                        columns: pk.columns,
                    });
                }
            }
        }
        if self.schema.tables.is_empty() {
            return Err(config_error(
                "the schema file contains no CREATE TABLE statements".into(),
            ));
        }
        Ok(self.schema)
    }

    /// Live introspection lists tables alphabetically.
    fn restore_table_order(&mut self) {
        self.schema.tables.sort_keys();
    }
}

fn last_part(name: &ObjectName) -> String {
    name.0
        .last()
        .map(|part| {
            part.as_ident()
                .map(|ident| ident.value.clone())
                .unwrap_or_else(|| part.to_string())
        })
        .unwrap_or_default()
}

fn index_columns(columns: &[sqlparser::ast::IndexColumn]) -> Vec<String> {
    columns
        .iter()
        .map(|c| match &c.column.expr {
            Expr::Identifier(ident) => ident.value.clone(),
            other => other.to_string(),
        })
        .collect()
}

fn enum_labels(members: &[EnumMember]) -> Vec<String> {
    members
        .iter()
        .map(|member| match member {
            EnumMember::Name(name) | EnumMember::NamedValue(name, _) => name.clone(),
        })
        .collect()
}

fn check_constraint(name: Option<String>, expr: &Expr) -> CheckConstraint {
    let expression = expr.to_string();
    CheckConstraint {
        name,
        parsed: super::postgres::parse_check_constraint(&expression),
        expression,
    }
}

fn action(action: Option<ReferentialAction>) -> ForeignKeyAction {
    match action {
        Some(ReferentialAction::Cascade) => ForeignKeyAction::Cascade,
        Some(ReferentialAction::SetNull) => ForeignKeyAction::SetNull,
        Some(ReferentialAction::SetDefault) => ForeignKeyAction::SetDefault,
        Some(ReferentialAction::Restrict) => ForeignKeyAction::Restrict,
        _ => ForeignKeyAction::NoAction,
    }
}

/// The type name without arguments or sign modifiers: `varchar(255)` ->
/// `varchar`, `timestamp(3) with time zone` -> `timestamp with time zone`,
/// `int(11) unsigned` -> `int`.
fn base_type(declared: &str) -> String {
    let mut base = String::new();
    let mut depth = 0;
    for c in declared.chars() {
        match c {
            '(' => depth += 1,
            ')' => depth -= 1,
            _ if depth == 0 => base.push(c),
            _ => {}
        }
    }
    let words: Vec<&str> = base
        .split_whitespace()
        .filter(|w| !matches!(*w, "unsigned" | "signed" | "zerofill"))
        .collect();
    words.join(" ")
}

/// `(n)` or `(p, s)` from a declared type.
fn type_arguments(declared: &str) -> (Option<u32>, Option<u32>, Option<u32>) {
    let Some(args) = declared
        .split_once('(')
        .and_then(|(_, rest)| rest.split_once(')'))
        .map(|(args, _)| args)
    else {
        return (None, None, None);
    };
    let numbers: Vec<u32> = args
        .split(',')
        .filter_map(|n| n.trim().parse().ok())
        .collect();
    (
        numbers.first().copied(),
        numbers.first().copied(),
        numbers.get(1).copied(),
    )
}

/// The `information_schema.columns.data_type` PostgreSQL reports.
fn postgres_type_name(data_type: &DataType) -> String {
    match data_type {
        DataType::SmallInt => "smallint",
        DataType::Integer | DataType::Serial => "integer",
        DataType::BigInt | DataType::BigSerial => "bigint",
        DataType::Float => "real",
        DataType::Double => "double precision",
        DataType::Numeric => "numeric",
        DataType::Char => "character",
        DataType::VarChar => "character varying",
        DataType::Text => "text",
        DataType::Boolean => "boolean",
        DataType::Date => "date",
        DataType::Time => "time without time zone",
        DataType::Timestamp => "timestamp without time zone",
        DataType::TimestampTz => "timestamp with time zone",
        DataType::Uuid => "uuid",
        DataType::Json => "json",
        DataType::Jsonb => "jsonb",
        DataType::Binary => "bytea",
        DataType::Array(_) => "ARRAY",
        DataType::Enum(_) => "USER-DEFINED",
        DataType::Inet => "inet",
        DataType::MacAddr => "macaddr",
        DataType::Xml => "xml",
        DataType::Money => "money",
        DataType::Interval => "interval",
        DataType::Unknown(name) => return name.clone(),
    }
    .to_owned()
}

/// The `information_schema.columns.data_type` MySQL reports.
fn mysql_type_name(base: &str) -> String {
    match base {
        "boolean" | "bool" => "tinyint".into(),
        "integer" => "int".into(),
        other => other.split_whitespace().next().unwrap_or(other).into(),
    }
}

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

    fn parse(sql: &str, db: DatabaseType) -> DatabaseSchema {
        parse_schema(sql, db, "app", "public").unwrap()
    }

    #[test]
    fn postgres_tables_keys_enums_and_checks() {
        let schema = parse(
            r#"
            CREATE TYPE mood AS ENUM ('calm', 'busy');
            CREATE TABLE teams (
                id SERIAL PRIMARY KEY,
                code CHAR(3) NOT NULL UNIQUE,
                name VARCHAR(80) NOT NULL,
                budget NUMERIC(10, 2) CHECK (budget >= 0),
                vibe mood DEFAULT 'calm',
                tags TEXT[],
                slug TEXT GENERATED ALWAYS AS (lower(name)) STORED
            );
            CREATE TABLE players (
                id BIGINT GENERATED ALWAYS AS IDENTITY,
                team_id INTEGER NOT NULL REFERENCES teams ON DELETE CASCADE,
                captain_of INTEGER,
                email TEXT NOT NULL,
                PRIMARY KEY (id),
                CONSTRAINT players_captain FOREIGN KEY (captain_of) REFERENCES public.teams (id),
                UNIQUE (team_id, email)
            );
            CREATE UNIQUE INDEX players_email ON players (email);
            CREATE UNIQUE INDEX players_lower ON players (lower(email));
            CREATE UNIQUE INDEX players_live ON players (team_id) WHERE captain_of IS NULL;
            "#,
            DatabaseType::PostgreSQL,
        );
        assert_eq!(schema.enums["mood"], ["calm", "busy"]);
        let teams = &schema.tables["teams"];
        assert_eq!(teams.schema_name.as_deref(), Some("public"));
        let id = &teams.columns["id"];
        assert_eq!(id.data_type, DataType::Integer);
        assert!(id.is_auto_increment && id.has_default && !id.nullable);
        assert_eq!(id.raw_type, "integer");
        assert_eq!(teams.columns["code"].max_length, Some(3));
        assert_eq!(teams.columns["name"].raw_type, "character varying");
        let budget = &teams.columns["budget"];
        assert_eq!(
            (budget.numeric_precision, budget.numeric_scale),
            (Some(10), Some(2))
        );
        assert!(matches!(
            teams.check_constraints[0].parsed,
            Some(ParsedCheck::GreaterThanOrEqual { ref column, value }) if column == "budget" && value == 0.0
        ));
        assert_eq!(
            teams.columns["vibe"].data_type,
            DataType::Enum("mood".into())
        );
        assert_eq!(
            teams.columns["vibe"].enum_values.as_deref(),
            Some(&["calm".to_string(), "busy".to_string()][..])
        );
        assert_eq!(
            teams.columns["tags"].data_type,
            DataType::Array(Box::new(DataType::Text))
        );
        assert!(teams.columns["slug"].is_generated);
        assert_eq!(teams.unique_constraints[0].columns, ["code"]);

        let players = &schema.tables["players"];
        assert!(players.columns["id"].is_auto_increment);
        assert_eq!(players.primary_key.as_ref().unwrap().columns, ["id"]);
        let team_fk = &players.foreign_keys[0];
        assert_eq!(
            team_fk.referenced_columns,
            ["id"],
            "REFERENCES teams uses its key"
        );
        assert_eq!(team_fk.on_delete, ForeignKeyAction::Cascade);
        assert_eq!(players.foreign_keys[1].referenced_schema, None);
        let unique: Vec<_> = players
            .unique_constraints
            .iter()
            .map(|u| u.columns.join(","))
            .collect();
        assert_eq!(
            unique,
            ["team_id,email", "email"],
            "expression and partial indexes skipped"
        );
    }

    #[test]
    fn pg_dump_output_is_understood() {
        let schema = parse(
            r#"
            \restrict abc123
            SET statement_timeout = 0;
            SELECT pg_catalog.set_config('search_path', '', false);
            CREATE FUNCTION public.touch() RETURNS trigger LANGUAGE plpgsql AS $$
            BEGIN NEW.updated_at := now(); RETURN NEW; END; $$;
            CREATE TABLE public.users (id integer NOT NULL, email character varying(255) NOT NULL);
            ALTER TABLE public.users OWNER TO app;
            CREATE SEQUENCE public.users_id_seq AS integer START WITH 1;
            ALTER SEQUENCE public.users_id_seq OWNED BY public.users.id;
            CREATE TABLE public.orders (id integer NOT NULL, user_id integer NOT NULL);
            ALTER TABLE ONLY public.users ALTER COLUMN id SET DEFAULT nextval('public.users_id_seq'::regclass);
            COPY public.users (id, email) FROM stdin;
            1	a@b.test
            \.
            ALTER TABLE ONLY public.users ADD CONSTRAINT users_pkey PRIMARY KEY (id);
            ALTER TABLE ONLY public.users ADD CONSTRAINT users_email_key UNIQUE (email);
            ALTER TABLE ONLY public.orders
                ADD CONSTRAINT orders_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id);
            COMMENT ON TABLE public.users IS 'people; with a semicolon';
            \unrestrict abc123
            "#,
            DatabaseType::PostgreSQL,
        );
        let users = &schema.tables["users"];
        assert!(
            users.columns["id"].is_auto_increment,
            "SET DEFAULT nextval marks identity"
        );
        assert_eq!(users.primary_key.as_ref().unwrap().columns, ["id"]);
        assert_eq!(users.unique_constraints[0].columns, ["email"]);
        assert_eq!(users.columns["email"].max_length, Some(255));
        assert_eq!(
            schema.tables["orders"].foreign_keys[0].referenced_table,
            "users"
        );
        assert_eq!(
            schema.tables.keys().collect::<Vec<_>>(),
            ["orders", "users"]
        );
    }

    #[test]
    fn mysql_backticks_auto_increment_enums_and_booleans() {
        let schema = parse(
            "CREATE TABLE `orders` (
                `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
                `status` ENUM('new', 'paid') NOT NULL DEFAULT 'new',
                `is_gift` BOOLEAN NOT NULL DEFAULT FALSE,
                `note` VARCHAR(40),
                PRIMARY KEY (`id`),
                KEY `by_status` (`status`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            DatabaseType::MySQL,
        );
        let orders = &schema.tables["orders"];
        let id = &orders.columns["id"];
        assert!(id.is_auto_increment && !id.has_default);
        assert_eq!(
            (id.data_type.clone(), id.raw_type.as_str()),
            (DataType::Integer, "int")
        );
        let status = &orders.columns["status"];
        assert_eq!(status.data_type, DataType::Enum("status".into()));
        assert_eq!(
            status.enum_values.as_deref(),
            Some(&["new".to_string(), "paid".to_string()][..])
        );
        let gift = &orders.columns["is_gift"];
        assert_eq!(
            (gift.data_type.clone(), gift.raw_type.as_str()),
            (DataType::SmallInt, "tinyint")
        );
        assert_eq!(orders.columns["note"].max_length, Some(40));
        assert!(
            orders.unique_constraints.is_empty(),
            "plain KEY is not unique"
        );
    }

    #[test]
    fn sqlite_rowid_keys_and_bare_references() {
        let schema = parse(
            "CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE);
             CREATE TABLE posts (id INTEGER PRIMARY KEY AUTOINCREMENT,
                                 author INTEGER REFERENCES users, title VARCHAR(10));",
            DatabaseType::SQLite,
        );
        let id = &schema.tables["users"].columns["id"];
        assert!(
            id.is_auto_increment && id.nullable,
            "SQLite reports rowid keys as nullable"
        );
        assert_eq!(id.ordinal_position, 0);
        let posts = &schema.tables["posts"];
        assert_eq!(posts.foreign_keys[0].referenced_columns, ["id"]);
        assert_eq!(
            posts.columns["title"].max_length, None,
            "SQLite records no lengths"
        );
    }

    #[test]
    fn sqlite_internal_tables_are_skipped() {
        // `sqlite3 app.db .schema` prints the tables SQLite creates for
        // AUTOINCREMENT and ANALYZE. Live introspection skips them.
        let schema = parse(
            "CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, email TEXT);
             CREATE TABLE sqlite_sequence(name,seq);
             CREATE TABLE posts (id INTEGER PRIMARY KEY, user_id INTEGER REFERENCES users(id));
             CREATE TABLE sqlite_stat1(tbl,idx,stat);
             CREATE TABLE SQLITE_STAT4(tbl,idx,neq,nlt,ndlt,sample);
             CREATE TABLE sqlitebackups (id INTEGER PRIMARY KEY);",
            DatabaseType::SQLite,
        );
        let names: Vec<&str> = schema.tables.keys().map(String::as_str).collect();
        assert_eq!(names, ["posts", "sqlitebackups", "users"]);
    }

    #[test]
    fn unreadable_tables_and_empty_files_are_errors() {
        let err = parse_schema(
            "CREATE TABLE broken (id INT,,);",
            DatabaseType::PostgreSQL,
            "app",
            "public",
        )
        .unwrap_err()
        .to_string();
        assert!(
            err.contains("CREATE TABLE") && err.contains("broken"),
            "{err}"
        );
        let err = parse_schema("SET x = 1;", DatabaseType::PostgreSQL, "app", "public")
            .unwrap_err()
            .to_string();
        assert!(err.contains("no CREATE TABLE"), "{err}");
    }
}