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
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
use std::collections::{BTreeMap, HashMap};

use crate::classify::semantic::{CorrelationGroup, SemanticType};
use crate::config::ColumnConfig;
use crate::generate::numeric::NumericFallback;
use crate::generate::value::Value;
use crate::graph::topo::DeferredEdge;
use crate::sample::stats::{ColumnDistribution, DistributionProfile};
use crate::schema::types::{Column, DataType, DatabaseSchema, DatabaseType, ParsedCheck};

/// The complete generation plan for all tables.
#[derive(Debug, Clone)]
pub struct GenerationPlan {
    /// Compiled scenario relationships keyed by child table.
    pub scenario: BTreeMap<String, super::scenario::TableRules>,
    /// Tables in insertion order (respects FK dependencies).
    pub table_plans: Vec<TableGenerationPlan>,
    /// Deferred FK edges to resolve after all inserts.
    pub deferred_edges: Vec<DeferredEdge>,
    /// Global seed for deterministic generation.
    pub seed: u64,
    pub generator_version: crate::generate::random::GeneratorVersion,
    /// Default row count per table (can be overridden per-table).
    pub default_row_count: usize,
    /// Pinned base timestamp for deterministic temporal generation.
    /// Captured once at plan creation time (or read from lockfile),
    /// so regeneration from a lockfile produces identical timestamps
    /// regardless of when it runs.
    pub base_time: chrono::NaiveDateTime,
    /// Offset added to synthesized auto-increment IDs.
    ///
    /// When seeding into an empty database with reset sequences, this is 0
    /// (the default). When seeding into a database where sequences already
    /// have a known starting value, set this to that value so FK references
    /// match the real database-assigned IDs.
    ///
    /// Pass a nonzero offset to `insert_direct_with_offset` when inserting directly.
    pub sequence_offset: u64,
    /// Locale for names, places, companies, and phone numbers.
    pub locale: crate::generate::locale::Locale,
}

/// Generation plan for a single table.
#[derive(Debug, Clone)]
pub struct TableGenerationPlan {
    /// Field overrides for the first scenario rows, in declaration order.
    pub records: Vec<BTreeMap<String, crate::generate::value::Value>>,
    pub table_name: String,
    pub row_count: usize,
    pub column_plans: Vec<ColumnGenerationPlan>,
    pub correlation_groups: Vec<CorrelationGroupPlan>,
}

/// Generation plan for a single column.
#[derive(Debug, Clone)]
pub struct ColumnGenerationPlan {
    pub column_name: String,
    pub semantic_type: SemanticType,
    pub strategy: GenerationStrategy,
    pub nullable: bool,
    /// Probability of generating NULL (0.0 to 1.0), only if nullable.
    pub null_probability: f64,
    /// Intersection of literal IN constraints, converted to the column type.
    pub allowed_values: Option<Vec<Value>>,
    /// Check constraints that apply to this column.
    pub check_constraints: Vec<ParsedCheck>,
}

/// How a column's value should be generated.
#[derive(Debug, Clone)]
pub enum GenerationStrategy {
    /// Auto-incrementing (serial/bigserial) — skip, let DB handle it.
    AutoIncrement,
    /// Off-schema parent without an explicitly configured key pool.
    ExternalReference { target: String },
    /// Reference a value from a parent table's column.
    ForeignKeyReference {
        referenced_table: String,
        referenced_column: String,
    },
    /// This column is assigned together with the other columns of its foreign key.
    CompositeReference,
    /// One-to-one relationship in which the child's primary key is the parent key.
    SharedPrimaryKey {
        referenced_table: String,
        referenced_column: String,
    },
    /// Use the semantic type's provider to generate a value.
    SemanticProvider,
    /// Generate an unclassified numeric column within its storage type.
    NumericFallback(NumericFallback),
    /// Build a value in the syntax of an array, interval, XML, range, or point column.
    Typed(crate::generate::typed::TypedFallback),
    /// Pick from a fixed list of enum values.
    EnumValue { values: Vec<String> },
    /// Generate as part of a correlation group — handled by the group.
    Correlated { group_index: usize },
    /// Deferred — insert NULL now, UPDATE later (for cycle-breaking).
    Deferred,
    /// Skip entirely (e.g., generated columns, columns with server defaults).
    Skip,
    /// Text from a configured `pattern`.
    Pattern(crate::generate::pattern::Pattern),
    /// A number in a configured `range`; whole numbers when `decimals` is `None`.
    Range {
        min: f64,
        max: f64,
        decimals: Option<u32>,
    },
    /// Pick from a user-configured value list (from seedkit.toml).
    /// Distinct from EnumValue which comes from database schema enum types.
    ValueList {
        values: Vec<crate::config::FixtureValue>,
        weights: Option<Vec<f64>>,
    },
    /// Keys bound by a scenario or existing-parent pool, in child row order.
    /// Reusable pools cycle, and components of a tuple share their row index.
    ReferenceKeys(Vec<crate::generate::value::Value>),
    /// Generate from a sampled production distribution profile.
    Distribution { distribution: ColumnDistribution },
}

/// Plan for generating correlated column values.
#[derive(Debug, Clone)]
pub struct CorrelationGroupPlan {
    pub group: CorrelationGroup,
    pub columns: Vec<(String, SemanticType)>,
}

impl GenerationPlan {
    /// Build a generation plan from a schema and classification results.
    ///
    /// `base_time` is pinned at plan creation so temporal values are deterministic.
    /// When restoring from a lockfile, pass the lockfile's stored `base_time`.
    /// When creating fresh, pass `None` to capture the current wall-clock time.
    #[allow(clippy::too_many_arguments)]
    pub fn build(
        schema: &DatabaseSchema,
        classifications: &BTreeMap<(String, String), SemanticType>,
        insertion_order: &[String],
        deferred_edges: Vec<DeferredEdge>,
        default_row_count: usize,
        table_row_overrides: &BTreeMap<String, usize>,
        seed: u64,
        base_time: Option<chrono::NaiveDateTime>,
        column_overrides: &BTreeMap<String, ColumnConfig>,
        distribution_profiles: Option<&[DistributionProfile]>,
    ) -> Self {
        let deferred_columns: HashMap<(&str, &str), bool> = deferred_edges
            .iter()
            .flat_map(|e| {
                e.source_columns
                    .iter()
                    .map(move |col| (e.source_table.as_str(), col.as_str()))
            })
            .map(|k| (k, true))
            .collect();

        // Build a distribution lookup: (table, column) -> ColumnDistribution
        let dist_lookup: HashMap<(&str, &str), &ColumnDistribution> = distribution_profiles
            .unwrap_or(&[])
            .iter()
            .flat_map(|p| {
                p.column_distributions
                    .iter()
                    .filter(|(_, d)| !matches!(d, ColumnDistribution::Ratio { .. }))
                    .map(move |(col, dist)| ((p.table_name.as_str(), col.as_str()), dist))
            })
            .collect();

        // Build ratio lookup for adjusting row counts
        let ratio_lookup: HashMap<(&str, &str), f64> = distribution_profiles
            .unwrap_or(&[])
            .iter()
            .flat_map(|p| {
                p.column_distributions.values().filter_map(move |dist| {
                    if let ColumnDistribution::Ratio {
                        related_table,
                        ratio,
                    } = dist
                    {
                        Some(((p.table_name.as_str(), related_table.as_str()), *ratio))
                    } else {
                        None
                    }
                })
            })
            .collect();

        let mut table_plans = Vec::new();

        for table_name in insertion_order {
            let table = match schema.tables.get(table_name) {
                Some(t) => t,
                None => continue,
            };

            // Row count: explicit override > ratio-adjusted > default
            let row_count = if let Some(&explicit) = table_row_overrides.get(table_name) {
                explicit
            } else {
                // Check if any FK has a ratio profile that adjusts row count
                let ratio_adjusted = table.local_foreign_keys().find_map(|fk| {
                    ratio_lookup
                        .get(&(table_name.as_str(), fk.referenced_table.as_str()))
                        .map(|ratio| {
                            let parent_count = table_row_overrides
                                .get(&fk.referenced_table)
                                .copied()
                                .unwrap_or(default_row_count);
                            (parent_count as f64 * ratio).round() as usize
                        })
                });
                ratio_adjusted.unwrap_or(default_row_count)
            };

            // Detect correlation groups for this table
            let mut correlation_groups = Vec::new();
            let mut correlated_columns: HashMap<String, usize> = HashMap::new();

            // Group columns by their correlation group
            let mut group_map: BTreeMap<CorrelationGroup, Vec<(String, SemanticType)>> =
                BTreeMap::new();
            let writable_columns = || table.columns.iter().filter(|(_, c)| !c.is_generated);
            // A configured `semantic` replaces the naming rules' choice.
            let semantic_of = |col_name: &String| {
                column_overrides
                    .get(&format!("{table_name}.{col_name}"))
                    .and_then(|cfg| cfg.semantic)
                    .or_else(|| {
                        classifications
                            .get(&(table_name.clone(), col_name.clone()))
                            .copied()
                    })
            };
            for (col_name, _) in writable_columns() {
                if let Some(st) = semantic_of(col_name).as_ref() {
                    if let Some(group) = st.correlation_group() {
                        group_map
                            .entry(group)
                            .or_default()
                            .push((col_name.clone(), *st));
                    }
                }
            }

            for (group, columns) in group_map {
                if columns.len() >= 2 {
                    let group_index = correlation_groups.len();
                    for (col_name, _) in &columns {
                        correlated_columns.insert(col_name.clone(), group_index);
                    }
                    correlation_groups.push(CorrelationGroupPlan { group, columns });
                }
            }

            // Build column plans
            let mut column_plans = Vec::new();
            let pk_columns: Vec<&str> = table
                .primary_key
                .as_ref()
                .map(|pk| pk.columns.iter().map(|s| s.as_str()).collect())
                .unwrap_or_default();

            for (col_name, column) in writable_columns() {
                let semantic_type = semantic_of(col_name).unwrap_or(SemanticType::Unknown);

                // Check for user-configured column overrides (seedkit.toml)
                let col_key = format!("{}.{}", table_name, col_name);
                let column_config = column_overrides.get(&col_key);
                let config_strategy = column_config.and_then(|cfg| {
                    if let Some(values) = &cfg.values {
                        return Some(GenerationStrategy::ValueList {
                            values: values.clone(),
                            weights: cfg.weights.clone(),
                        });
                    }
                    if let Some(pattern) = &cfg.pattern {
                        // Validated with the config; an invalid pattern is ignored here.
                        return crate::generate::pattern::Pattern::parse(pattern)
                            .ok()
                            .map(GenerationStrategy::Pattern);
                    }
                    cfg.range.map(|[min, max]| GenerationStrategy::Range {
                        min,
                        max,
                        decimals: (!column.data_type.is_integer())
                            .then(|| column.numeric_scale.unwrap_or(2).min(6)),
                    })
                });

                let external_key = table.foreign_keys.iter().find(|fk| {
                    fk.referenced_schema.is_some() && fk.source_columns.contains(col_name)
                });
                let foreign_key = table.local_foreign_keys().find(|fk| {
                    fk.source_columns.len() == 1
                        && fk.referenced_columns.len() == 1
                        && fk.source_columns[0] == *col_name
                });
                let shared_key = foreign_key.filter(|fk| {
                    (pk_columns.as_slice() == [col_name.as_str()]
                        || table
                            .unique_constraints
                            .iter()
                            .any(|u| u.columns.as_slice() == [col_name.as_str()]))
                        && fk.referenced_table != *table_name
                        && insertion_order.contains(&fk.referenced_table)
                });
                // Determine generation strategy — config overrides take priority
                let strategy = if let Some(fk) = external_key {
                    GenerationStrategy::ExternalReference {
                        target: fk.target_name(),
                    }
                } else if let Some(s) = config_strategy {
                    s
                } else if deferred_columns.contains_key(&(table_name.as_str(), col_name.as_str())) {
                    GenerationStrategy::Deferred
                } else if table.local_foreign_keys().any(|fk| {
                    fk.source_columns.len() > 1
                        && fk.source_columns.contains(col_name)
                        && insertion_order.contains(&fk.referenced_table)
                }) {
                    GenerationStrategy::CompositeReference
                } else if let Some(fk) = shared_key {
                    GenerationStrategy::SharedPrimaryKey {
                        referenced_table: fk.referenced_table.clone(),
                        referenced_column: fk.referenced_columns[0].clone(),
                    }
                } else if column.is_auto_increment || column.data_type.is_serial() {
                    if pk_columns.contains(&col_name.as_str()) {
                        GenerationStrategy::AutoIncrement
                    } else {
                        GenerationStrategy::SemanticProvider
                    }
                } else if let Some(fk) = foreign_key {
                    // GUARD: Only use ForeignKeyReference if the referenced table
                    // is actually in this generation plan's insertion order.
                    // If the parent was excluded (via --exclude or --include that
                    // didn't capture it), fall back to semantic generation so the
                    // engine doesn't crash looking for an empty FK pool.
                    if insertion_order.contains(&fk.referenced_table) {
                        GenerationStrategy::ForeignKeyReference {
                            referenced_table: fk.referenced_table.clone(),
                            referenced_column: fk.referenced_columns[0].clone(),
                        }
                    } else {
                        GenerationStrategy::SemanticProvider
                    }
                } else if let Some(dist) =
                    dist_lookup.get(&(table_name.as_str(), col_name.as_str()))
                {
                    GenerationStrategy::Distribution {
                        distribution: (*dist).clone(),
                    }
                } else if let Some(ref values) = column.enum_values {
                    GenerationStrategy::EnumValue {
                        values: values.clone(),
                    }
                } else if let Some(&group_index) = correlated_columns.get(col_name) {
                    GenerationStrategy::Correlated { group_index }
                } else {
                    GenerationStrategy::SemanticProvider
                };

                let strategy = if semantic_type == SemanticType::Unknown
                    && matches!(strategy, GenerationStrategy::SemanticProvider)
                {
                    NumericFallback::for_column(column)
                        .map(GenerationStrategy::NumericFallback)
                        .unwrap_or(strategy)
                } else {
                    strategy
                };

                // Structured types need values in their own syntax, whatever the
                // column name suggests. Arrays still use the semantic type for
                // their elements.
                let strategy = match strategy {
                    generated @ (GenerationStrategy::SemanticProvider
                    | GenerationStrategy::Correlated { .. }
                    | GenerationStrategy::NumericFallback(_)) => {
                        crate::generate::typed::TypedFallback::for_column(column, &schema.enums)
                            .map_or(generated, GenerationStrategy::Typed)
                    }
                    other => other,
                };

                // Collect applicable check constraints
                let check_constraints: Vec<ParsedCheck> = table
                    .check_constraints
                    .iter()
                    .filter_map(|cc| {
                        cc.parsed.as_ref().and_then(|p| {
                            if check_applies_to_column(p, col_name, schema.database_type) {
                                Some(p.clone())
                            } else {
                                None
                            }
                        })
                    })
                    .collect();

                let allowed_values = allowed_values(column, &check_constraints);
                let strategy = if allowed_values.is_some()
                    && matches!(
                        strategy,
                        GenerationStrategy::Correlated { .. }
                            | GenerationStrategy::EnumValue { .. }
                    ) {
                    GenerationStrategy::SemanticProvider
                } else {
                    strategy
                };

                let null_probability =
                    if column.nullable && !pk_columns.contains(&col_name.as_str()) {
                        column_config
                            .and_then(|cfg| cfg.null_rate)
                            .unwrap_or(match semantic_type {
                                SemanticType::DeletedAt => 0.8, // Most rows aren't soft-deleted
                                _ => 0.05, // Small chance of NULL for nullable columns
                            })
                    } else {
                        0.0
                    };

                column_plans.push(ColumnGenerationPlan {
                    column_name: col_name.clone(),
                    semantic_type,
                    strategy,
                    nullable: column.nullable,
                    null_probability,
                    check_constraints,
                    allowed_values,
                });
            }

            table_plans.push(TableGenerationPlan {
                records: Vec::new(),
                table_name: table_name.clone(),
                row_count,
                column_plans,
                correlation_groups,
            });
        }

        GenerationPlan {
            scenario: BTreeMap::new(),
            table_plans,
            deferred_edges,
            seed,
            default_row_count,
            base_time: base_time.unwrap_or_else(|| chrono::Utc::now().naive_utc()),
            generator_version: Default::default(),
            sequence_offset: 0,
            locale: Default::default(),
        }
    }
}

/// Filter an insertion order by include/exclude lists.
///
/// When `include` is non-empty, only tables in the list (plus their FK
/// dependencies) are kept. When `exclude` is non-empty, listed tables are
/// removed. `include` takes priority: if both are set, `include` is applied
/// first and `exclude` is then applied to the result.
///
/// FK dependencies are automatically added — if you `--include orders` and
/// `orders` FK-references `users`, then `users` is included automatically so
/// FK generation doesn't break.
pub fn filter_insertion_order(
    insertion_order: &[String],
    schema: &DatabaseSchema,
    include: &[String],
    exclude: &[String],
) -> Vec<String> {
    if include.is_empty() && exclude.is_empty() {
        return insertion_order.to_vec();
    }

    let mut wanted: std::collections::HashSet<String> = if include.is_empty() {
        // Start with all tables
        insertion_order.iter().cloned().collect()
    } else {
        // Start with explicitly included tables
        let mut set: std::collections::HashSet<String> = include.iter().cloned().collect();
        // Close over FK dependencies: walk each included table's FKs
        // and add referenced tables (transitively).
        let mut queue: Vec<String> = include.to_vec();
        while let Some(table_name) = queue.pop() {
            if let Some(table) = schema.tables.get(&table_name) {
                for fk in table.local_foreign_keys() {
                    if set.insert(fk.referenced_table.clone()) {
                        queue.push(fk.referenced_table.clone());
                    }
                }
            }
        }
        set
    };

    // Apply excludes
    for table_name in exclude {
        wanted.remove(table_name);
    }

    // Preserve original insertion order (topological)
    insertion_order
        .iter()
        .filter(|t| wanted.contains(t.as_str()))
        .cloned()
        .collect()
}

fn allowed_values(column: &Column, checks: &[ParsedCheck]) -> Option<Vec<Value>> {
    fn literal(data_type: &DataType, s: &str) -> Option<Value> {
        match data_type {
            DataType::SmallInt
            | DataType::Integer
            | DataType::BigInt
            | DataType::Serial
            | DataType::BigSerial => {
                let integer = s
                    .split_once('.')
                    .filter(|(_, fraction)| fraction.bytes().all(|b| b == b'0'))
                    .map_or(s, |(whole, _)| whole);
                integer.parse().ok().map(Value::Int)
            }
            DataType::Numeric | DataType::Float | DataType::Double => {
                s.parse().ok().map(Value::Float)
            }
            DataType::Boolean => match s.to_ascii_lowercase().as_str() {
                "true" | "1" => Some(Value::Bool(true)),
                "false" | "0" => Some(Value::Bool(false)),
                _ => None,
            },
            _ => Some(Value::String(s.to_owned().into())),
        }
    }
    let mut lists = checks.iter().filter_map(|check| match check {
        ParsedCheck::InValues { values, .. } => Some(
            values
                .iter()
                .filter(|v| {
                    column
                        .enum_values
                        .as_ref()
                        .is_none_or(|labels| labels.contains(v))
                })
                .filter_map(|s| literal(&column.data_type, s))
                .collect::<Vec<_>>(),
        ),
        _ => None,
    });
    let mut allowed = lists.next()?;
    for list in lists {
        allowed.retain(|v| list.contains(v));
    }
    Some(allowed)
}

fn check_applies_to_column(check: &ParsedCheck, column_name: &str, db: DatabaseType) -> bool {
    match check {
        ParsedCheck::GreaterThanOrEqual { column, .. }
        | ParsedCheck::GreaterThan { column, .. }
        | ParsedCheck::LessThanOrEqual { column, .. }
        | ParsedCheck::LessThan { column, .. }
        | ParsedCheck::MinLength { column, .. } => column == column_name,
        ParsedCheck::InValues { column, .. } if db != DatabaseType::PostgreSQL => {
            column.eq_ignore_ascii_case(column_name)
        }
        ParsedCheck::InValues { column, .. } => column == column_name,
        ParsedCheck::Between { column, .. } => column == column_name,
        ParsedCheck::ColumnLessThan { left, right } => left == column_name || right == column_name,
    }
}

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

    /// Helper: build a schema with users → orders → order_items FK chain.
    fn build_chain_schema() -> DatabaseSchema {
        let mut schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());

        let users = Table::new("users".to_string());
        schema.tables.insert("users".to_string(), users);

        let mut orders = Table::new("orders".to_string());
        orders.foreign_keys.push(ForeignKey {
            name: None,
            source_columns: vec!["user_id".to_string()],
            referenced_schema: None,
            referenced_table: "users".to_string(),
            referenced_columns: vec!["id".to_string()],
            on_delete: ForeignKeyAction::NoAction,
            on_update: ForeignKeyAction::NoAction,
            is_deferrable: false,
        });
        schema.tables.insert("orders".to_string(), orders);

        let mut order_items = Table::new("order_items".to_string());
        order_items.foreign_keys.push(ForeignKey {
            name: None,
            source_columns: vec!["order_id".to_string()],
            referenced_schema: None,
            referenced_table: "orders".to_string(),
            referenced_columns: vec!["id".to_string()],
            on_delete: ForeignKeyAction::NoAction,
            on_update: ForeignKeyAction::NoAction,
            is_deferrable: false,
        });
        schema.tables.insert("order_items".to_string(), order_items);

        let products = Table::new("products".to_string());
        schema.tables.insert("products".to_string(), products);

        schema
    }

    #[test]
    fn test_filter_no_include_no_exclude_returns_all() {
        let schema = build_chain_schema();
        let order = vec![
            "users".into(),
            "products".into(),
            "orders".into(),
            "order_items".into(),
        ];
        let result = filter_insertion_order(&order, &schema, &[], &[]);
        assert_eq!(result, order);
    }

    #[test]
    fn test_filter_include_single_table_no_fk_deps() {
        let schema = build_chain_schema();
        let order = vec![
            "users".into(),
            "products".into(),
            "orders".into(),
            "order_items".into(),
        ];
        let result = filter_insertion_order(&order, &schema, &["products".into()], &[]);
        assert_eq!(result, vec!["products"]);
    }

    #[test]
    fn test_filter_include_auto_adds_fk_dependencies() {
        let schema = build_chain_schema();
        let order = vec![
            "users".into(),
            "products".into(),
            "orders".into(),
            "order_items".into(),
        ];
        // Including "orders" should auto-include "users" (FK dependency)
        let result = filter_insertion_order(&order, &schema, &["orders".into()], &[]);
        assert_eq!(result, vec!["users", "orders"]);
    }

    #[test]
    fn test_filter_include_transitive_fk_dependencies() {
        let schema = build_chain_schema();
        let order = vec![
            "users".into(),
            "products".into(),
            "orders".into(),
            "order_items".into(),
        ];
        // Including "order_items" should auto-include "orders" AND "users" transitively
        let result = filter_insertion_order(&order, &schema, &["order_items".into()], &[]);
        assert_eq!(result, vec!["users", "orders", "order_items"]);
    }

    #[test]
    fn test_filter_exclude_removes_table() {
        let schema = build_chain_schema();
        let order = vec![
            "users".into(),
            "products".into(),
            "orders".into(),
            "order_items".into(),
        ];
        let result = filter_insertion_order(&order, &schema, &[], &["products".into()]);
        assert_eq!(result, vec!["users", "orders", "order_items"]);
    }

    #[test]
    fn test_filter_include_and_exclude_combined() {
        let schema = build_chain_schema();
        let order = vec![
            "users".into(),
            "products".into(),
            "orders".into(),
            "order_items".into(),
        ];
        // Include orders (auto-includes users), then exclude users
        let result = filter_insertion_order(&order, &schema, &["orders".into()], &["users".into()]);
        // users excluded even though it was a dependency — user's explicit choice
        assert_eq!(result, vec!["orders"]);
    }

    #[test]
    fn test_filter_preserves_topological_order() {
        let schema = build_chain_schema();
        let order = vec![
            "users".into(),
            "products".into(),
            "orders".into(),
            "order_items".into(),
        ];
        let result = filter_insertion_order(
            &order,
            &schema,
            &["order_items".into(), "products".into()],
            &[],
        );
        // Should preserve: users, products, orders, order_items
        // (users and orders are auto-included as deps of order_items)
        assert_eq!(result, vec!["users", "products", "orders", "order_items"]);
    }

    #[test]
    fn test_filter_include_nonexistent_table_ignored() {
        let schema = build_chain_schema();
        let order = vec!["users".into(), "products".into()];
        let result = filter_insertion_order(
            &order,
            &schema,
            &["users".into(), "nonexistent".into()],
            &[],
        );
        assert_eq!(result, vec!["users"]);
    }

    #[test]
    fn test_unclassified_integer_fk_to_excluded_parent_uses_numeric_fallback() {
        let mut schema = build_chain_schema();

        // Give orders a user_id column so it can be classified
        let user_id_col = Column::new(
            "user_id".to_string(),
            DataType::Integer,
            "integer".to_string(),
        );
        schema
            .tables
            .get_mut("orders")
            .unwrap()
            .columns
            .insert("user_id".to_string(), user_id_col);

        let classifications = BTreeMap::new();
        // Only "orders" in the insertion order — "users" excluded
        let insertion_order = vec!["orders".to_string()];

        let plan = GenerationPlan::build(
            &schema,
            &classifications,
            &insertion_order,
            Vec::new(),
            10,
            &BTreeMap::new(),
            42,
            None,
            &BTreeMap::new(),
            None,
        );

        // Find the user_id column plan in orders
        let orders_plan = plan
            .table_plans
            .iter()
            .find(|t| t.table_name == "orders")
            .unwrap();
        let user_id_plan = orders_plan
            .column_plans
            .iter()
            .find(|c| c.column_name == "user_id")
            .unwrap();

        assert!(matches!(
            user_id_plan.strategy,
            GenerationStrategy::NumericFallback(NumericFallback::Integer { .. })
        ));
    }

    #[test]
    fn test_fk_to_included_parent_uses_fk_reference() {
        let mut schema = build_chain_schema();

        let user_id_col = Column::new(
            "user_id".to_string(),
            DataType::Integer,
            "integer".to_string(),
        );
        schema
            .tables
            .get_mut("orders")
            .unwrap()
            .columns
            .insert("user_id".to_string(), user_id_col);

        let classifications = BTreeMap::new();
        // Both "users" and "orders" in the insertion order
        let insertion_order = vec!["users".to_string(), "orders".to_string()];

        let plan = GenerationPlan::build(
            &schema,
            &classifications,
            &insertion_order,
            Vec::new(),
            10,
            &BTreeMap::new(),
            42,
            None,
            &BTreeMap::new(),
            None,
        );

        let orders_plan = plan
            .table_plans
            .iter()
            .find(|t| t.table_name == "orders")
            .unwrap();
        let user_id_plan = orders_plan
            .column_plans
            .iter()
            .find(|c| c.column_name == "user_id")
            .unwrap();

        // Should be ForeignKeyReference since "users" is in the plan
        assert!(
            matches!(
                user_id_plan.strategy,
                GenerationStrategy::ForeignKeyReference { .. }
            ),
            "Expected ForeignKeyReference for FK to included parent, got {:?}",
            user_id_plan.strategy
        );
    }

    // --- Config column override tests ---

    #[test]
    fn test_value_list_override_takes_priority_over_semantic() {
        let mut schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());
        let mut table = Table::new("products".to_string());
        let col = Column::new(
            "color".to_string(),
            DataType::VarChar,
            "varchar".to_string(),
        );
        table.columns.insert("color".to_string(), col);
        schema.tables.insert("products".to_string(), table);

        let classifications = BTreeMap::new();
        let insertion_order = vec!["products".to_string()];

        let mut overrides = BTreeMap::new();
        overrides.insert(
            "products.color".to_string(),
            crate::config::ColumnConfig {
                values: Some(vec!["red".into(), "blue".into()]),
                weights: Some(vec![0.7, 0.3]),
                ..Default::default()
            },
        );

        let plan = GenerationPlan::build(
            &schema,
            &classifications,
            &insertion_order,
            Vec::new(),
            10,
            &BTreeMap::new(),
            42,
            None,
            &overrides,
            None,
        );

        let col_plan = plan.table_plans[0]
            .column_plans
            .iter()
            .find(|c| c.column_name == "color")
            .unwrap();
        assert!(
            matches!(col_plan.strategy, GenerationStrategy::ValueList { .. }),
            "Expected ValueList from config override, got {:?}",
            col_plan.strategy
        );
    }

    #[test]
    fn pattern_and_range_overrides_choose_their_strategies() {
        let mut schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());
        let mut table = Table::new("orders".to_string());
        for (name, data_type) in [("tax_code", DataType::VarChar), ("qty", DataType::Integer)] {
            let col = Column::new(name.to_string(), data_type.clone(), data_type.to_string());
            table.columns.insert(name.to_string(), col);
        }
        schema.tables.insert("orders".to_string(), table);

        let overrides = BTreeMap::from([
            (
                "orders.tax_code".to_string(),
                crate::config::ColumnConfig {
                    pattern: Some("TX-####".into()),
                    ..Default::default()
                },
            ),
            (
                "orders.qty".to_string(),
                crate::config::ColumnConfig {
                    range: Some([1.0, 9.0]),
                    ..Default::default()
                },
            ),
        ]);

        let plan = GenerationPlan::build(
            &schema,
            &BTreeMap::new(),
            &["orders".to_string()],
            Vec::new(),
            10,
            &BTreeMap::new(),
            42,
            None,
            &overrides,
            None,
        );

        let strategy = |name: &str| {
            &plan.table_plans[0]
                .column_plans
                .iter()
                .find(|c| c.column_name == name)
                .unwrap()
                .strategy
        };
        assert!(matches!(
            strategy("tax_code"),
            GenerationStrategy::Pattern(_)
        ));
        assert!(matches!(
            strategy("qty"),
            GenerationStrategy::Range { decimals: None, .. }
        ));
    }

    #[test]
    fn test_override_for_nonexistent_column_is_harmless() {
        let mut schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());
        let mut table = Table::new("users".to_string());
        let col = Column::new("name".to_string(), DataType::VarChar, "varchar".to_string());
        table.columns.insert("name".to_string(), col);
        schema.tables.insert("users".to_string(), table);

        let mut overrides = BTreeMap::new();
        overrides.insert(
            "users.nonexistent".to_string(),
            crate::config::ColumnConfig {
                values: Some(vec!["x".into()]),
                weights: None,
                ..Default::default()
            },
        );

        // Should not panic — the override simply has no matching column
        let plan = GenerationPlan::build(
            &schema,
            &BTreeMap::new(),
            &["users".to_string()],
            Vec::new(),
            10,
            &BTreeMap::new(),
            42,
            None,
            &overrides,
            None,
        );

        // "name" column should use SemanticProvider (no override for it)
        let col_plan = plan.table_plans[0]
            .column_plans
            .iter()
            .find(|c| c.column_name == "name")
            .unwrap();
        assert!(
            matches!(col_plan.strategy, GenerationStrategy::SemanticProvider),
            "Nonexistent override should not affect other columns, got {:?}",
            col_plan.strategy
        );
    }

    // --- Distribution profile tests ---

    #[test]
    fn test_ratio_adjusts_row_counts() {
        use crate::sample::stats::{ColumnDistribution, DistributionProfile};

        let schema = build_chain_schema();
        let classifications = BTreeMap::new();
        let insertion_order = vec![
            "users".to_string(),
            "products".to_string(),
            "orders".to_string(),
            "order_items".to_string(),
        ];

        // Profiles say: orders has 3.2x the rows of users
        let profiles = vec![
            DistributionProfile {
                table_name: "users".to_string(),
                row_count: 1000,
                column_distributions: std::collections::HashMap::new(),
            },
            DistributionProfile {
                table_name: "orders".to_string(),
                row_count: 3200,
                column_distributions: {
                    let mut m = std::collections::HashMap::new();
                    m.insert(
                        "__ratio_user_id".to_string(),
                        ColumnDistribution::Ratio {
                            related_table: "users".to_string(),
                            ratio: 3.2,
                        },
                    );
                    m
                },
            },
        ];

        let plan = GenerationPlan::build(
            &schema,
            &classifications,
            &insertion_order,
            Vec::new(),
            100, // default row count
            &BTreeMap::new(),
            42,
            None,
            &BTreeMap::new(),
            Some(&profiles),
        );

        // users should be 100 (default)
        let users_plan = plan
            .table_plans
            .iter()
            .find(|t| t.table_name == "users")
            .unwrap();
        assert_eq!(users_plan.row_count, 100);

        // orders should be adjusted: 100 * 3.2 = 320
        let orders_plan = plan
            .table_plans
            .iter()
            .find(|t| t.table_name == "orders")
            .unwrap();
        assert_eq!(
            orders_plan.row_count, 320,
            "orders should be ratio-adjusted to 320 (100 * 3.2)"
        );
    }

    #[test]
    fn test_distribution_profile_overrides_semantic_provider() {
        use crate::sample::stats::{ColumnDistribution, DistributionProfile};

        let mut schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());
        let mut table = Table::new("products".to_string());
        let col = Column::new(
            "status".to_string(),
            DataType::VarChar,
            "varchar".to_string(),
        );
        table.columns.insert("status".to_string(), col);
        schema.tables.insert("products".to_string(), table);

        let profiles = vec![DistributionProfile {
            table_name: "products".to_string(),
            row_count: 500,
            column_distributions: {
                let mut m = std::collections::HashMap::new();
                m.insert(
                    "status".to_string(),
                    ColumnDistribution::Categorical {
                        values: vec![("active".to_string(), 0.9), ("draft".to_string(), 0.1)],
                    },
                );
                m
            },
        }];

        let plan = GenerationPlan::build(
            &schema,
            &BTreeMap::new(),
            &["products".to_string()],
            Vec::new(),
            10,
            &BTreeMap::new(),
            42,
            None,
            &BTreeMap::new(),
            Some(&profiles),
        );

        let col_plan = plan.table_plans[0]
            .column_plans
            .iter()
            .find(|c| c.column_name == "status")
            .unwrap();
        assert!(
            matches!(col_plan.strategy, GenerationStrategy::Distribution { .. }),
            "Expected Distribution strategy from profile, got {:?}",
            col_plan.strategy
        );
    }
}