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
//! # Configuration File Parser
//!
//! Reads and parses `seedkit.toml`, the optional user configuration file that
//! customizes SeedKit's behavior without requiring CLI flags. Supports:
//!
//! - `[database]` — default connection URL
//! - `[generate]` — default row count, seed, AI settings
//! - `[tables.<name>]` — per-table row count overrides
//! - `[columns."<table>.<column>"]` — value lists, patterns, ranges, semantic types, null rates
//! - `[graph]` — explicit cycle-breaking edge overrides
//!
//! Example `seedkit.toml`:
//!
//! ```toml
//! [database]
//! url = "postgres://localhost/myapp"
//!
//! [generate]
//! rows = 500
//! seed = 42
//! ai = false
//!
//! [tables.users]
//! rows = 1000
//!
//! [tables.orders]
//! rows = 5000
//!
//! [columns."products.color"]
//! values = ["red", "blue", "green", "black", "white"]
//! weights = [0.25, 0.20, 0.20, 0.20, 0.15]
//!
//! [columns."orders.number"]
//! pattern = "INV-{row:06}"
//!
//! [columns."orders.quantity"]
//! range = [1, 10]
//! null_rate = 0.1
//!
//! [graph]
//! break_cycle_at = ["users.invited_by_id", "comments.parent_id"]
//! ```

use std::collections::BTreeMap;
use std::path::Path;

use serde::{Deserialize, Serialize};

use crate::error::{Result, SeedKitError};

/// Default config file name.
pub const CONFIG_FILE_NAME: &str = "seedkit.toml";

/// Top-level seedkit.toml structure.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct SeedKitConfig {
    /// Database connection settings.
    pub database: DatabaseConfig,
    /// Default generation settings.
    pub generate: GenerateConfig,
    /// Named relational fixtures selected with --scenario.
    pub scenarios: BTreeMap<String, crate::generate::scenario::Scenario>,
    /// Per-table overrides, keyed by table name.
    pub tables: BTreeMap<String, TableConfig>,
    /// Per-column overrides, keyed by "table.column".
    pub columns: BTreeMap<String, ColumnConfig>,
    /// Relationships that draw keys from rows already present in the database.
    pub existing_parents: Vec<crate::generate::existing::ExistingParent>,
    /// Dependency graph settings.
    pub graph: GraphConfig,
}

/// Database connection configuration.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct DatabaseConfig {
    /// Database URL (e.g., "postgres://localhost/myapp").
    pub url: Option<String>,
    /// Schema name to introspect (e.g., "public" for PostgreSQL).
    pub schema: Option<String>,
}

/// Default generation settings.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct GenerateConfig {
    /// Default number of rows per table.
    pub rows: Option<usize>,
    /// Fixed random seed for deterministic generation.
    pub seed: Option<u64>,
    /// Whether to enable AI-enhanced classification by default.
    pub ai: Option<bool>,
    /// Tables to include (empty = all).
    pub include: Option<Vec<String>>,
    /// Tables to exclude.
    pub exclude: Option<Vec<String>>,
    /// Locale for names, places, companies, and phone numbers (e.g. "de_DE").
    pub locale: Option<crate::generate::locale::Locale>,
}

/// Per-table configuration override.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct TableConfig {
    /// Number of rows to generate for this table.
    pub rows: Option<usize>,
}

/// Scalar fixture literals keep their TOML and JSON types through lock replay.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FixtureValue {
    Text(String),
    Integer(i64),
    Boolean(bool),
    Float(#[serde(deserialize_with = "finite_float")] f64),
}

fn finite_float<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> std::result::Result<f64, D::Error> {
    let value = f64::deserialize(deserializer)?;
    if value.is_finite() {
        Ok(value)
    } else {
        Err(serde::de::Error::custom("fixture number must be finite"))
    }
}

impl From<&str> for FixtureValue {
    fn from(value: &str) -> Self {
        Self::Text(value.into())
    }
}

impl FixtureValue {
    pub(crate) fn fits(&self, column: &crate::schema::types::Column) -> bool {
        use crate::schema::types::DataType;
        match self {
            Self::Text(s) => column
                .enum_values
                .as_ref()
                .is_none_or(|labels| labels.contains(s)),
            Self::Boolean(_) => {
                matches!(column.data_type, DataType::Boolean) || column.raw_type == "tinyint"
            }
            Self::Integer(_) => column.data_type.is_numeric(),
            Self::Float(_) => matches!(
                column.data_type,
                DataType::Float | DataType::Double | DataType::Numeric | DataType::Money
            ),
        }
    }

    pub fn to_value(&self) -> crate::generate::value::Value {
        use crate::generate::value::Value;
        match self {
            Self::Text(s) => Value::String(s.clone().into()),
            Self::Integer(i) => Value::Int(*i),
            Self::Boolean(b) => Value::Bool(*b),
            Self::Float(f) => Value::Float(*f),
        }
    }
}

/// Per-column configuration override.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct ColumnConfig {
    /// Fixed list of values to pick from.
    pub values: Option<Vec<FixtureValue>>,
    /// Weights for each value (must be same length as `values`).
    pub weights: Option<Vec<f64>>,
    /// Text pattern: `#` digit, `?` uppercase letter, `{row}` or `{row:N}`
    /// row number. See [`crate::generate::pattern`].
    pub pattern: Option<String>,
    /// Inclusive `[min, max]` for numbers. Integer columns get whole numbers.
    pub range: Option<[f64; 2]>,
    /// Built-in generator to use instead of the naming rules' choice.
    pub semantic: Option<crate::classify::semantic::SemanticType>,
    /// Chance of NULL for a nullable column, from 0 to 1 (default 0.05).
    pub null_rate: Option<f64>,
    /// No longer supported. Kept so a config that sets it gets a clear error.
    pub custom: Option<String>,
}

/// Dependency graph configuration.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct GraphConfig {
    /// Explicit FK edges to break for cycle resolution.
    ///
    /// Each entry is "table.column" (e.g., "users.invited_by_id").
    /// These edges are deferred (INSERT NULL, UPDATE later) instead of
    /// being resolved by the automatic Tarjan SCC heuristic.
    pub break_cycle_at: Vec<String>,
}

/// Read and parse a seedkit.toml file from the given directory.
///
/// Returns `None` if the file doesn't exist (config is optional).
/// Returns an error if the file exists but can't be parsed.
pub fn read_config(dir: &Path) -> Result<Option<SeedKitConfig>> {
    let path = dir.join(CONFIG_FILE_NAME);
    if !path.exists() {
        return Ok(None);
    }

    let content = std::fs::read_to_string(&path).map_err(|e| SeedKitError::Config {
        message: format!("Failed to read {}: {}", path.display(), e),
    })?;

    let config: SeedKitConfig = toml::from_str(&content).map_err(|e| SeedKitError::Config {
        message: format!("Failed to parse {}: {}", path.display(), e),
    })?;

    // Validate semantic constraints that serde can't enforce.
    config.validate()?;

    Ok(Some(config))
}

impl SeedKitConfig {
    /// Build table_row_overrides from the [tables] section.
    pub fn table_row_overrides(&self) -> BTreeMap<String, usize> {
        let mut map = BTreeMap::new();
        for (name, tc) in &self.tables {
            if let Some(rows) = tc.rows {
                map.insert(name.clone(), rows);
            }
        }
        map
    }

    /// Parse break_cycle_at entries into (table, column) pairs.
    ///
    /// Malformed entries (missing the `table.column` dot separator) are logged
    /// as a warning via `tracing::warn` and skipped, so developers see exactly
    /// which config line is being ignored instead of silently losing it.
    pub fn cycle_break_edges(&self) -> Vec<(String, String)> {
        self.graph
            .break_cycle_at
            .iter()
            .filter_map(|entry| {
                let parts: Vec<&str> = entry.splitn(2, '.').collect();
                if parts.len() == 2 {
                    Some((parts[0].to_string(), parts[1].to_string()))
                } else {
                    tracing::warn!(
                        "Invalid graph.break_cycle_at entry: '{}'. \
                         Expected format 'table.column'. Ignoring.",
                        entry
                    );
                    None
                }
            })
            .collect()
    }

    /// Validate semantic constraints that serde cannot enforce.
    ///
    /// Call this immediately after parsing. Catches configuration mistakes
    /// (e.g., mismatched `values`/`weights` lengths) before any expensive
    /// database introspection runs.
    pub fn validate(&self) -> Result<()> {
        for (key, col_cfg) in &self.columns {
            let invalid = |message: String| SeedKitError::Config {
                message: format!("Column '{key}': {message}"),
            };
            if col_cfg.custom.is_some() {
                return Err(invalid(
                    "custom providers are not supported. Use values, pattern, range, or \
                     semantic instead."
                        .into(),
                ));
            }
            let generators = [
                col_cfg.values.is_some(),
                col_cfg.pattern.is_some(),
                col_cfg.range.is_some(),
            ];
            if generators.iter().filter(|set| **set).count() > 1 {
                return Err(invalid("set only one of values, pattern, or range.".into()));
            }
            if let Some(pattern) = &col_cfg.pattern {
                crate::generate::pattern::Pattern::parse(pattern)
                    .map_err(|e| invalid(format!("invalid pattern: {e}")))?;
            }
            if let Some([min, max]) = col_cfg.range {
                if !(min.is_finite() && max.is_finite() && min <= max) {
                    return Err(invalid(format!(
                        "range must be [min, max] with min <= max, got [{min}, {max}]"
                    )));
                }
            }
            if let Some(rate) = col_cfg.null_rate {
                if !(0.0..=1.0).contains(&rate) {
                    return Err(invalid(format!(
                        "null_rate must be between 0 and 1, got {rate}"
                    )));
                }
            }
            if let Some(ref weights) = col_cfg.weights {
                match col_cfg.values {
                    Some(ref values) => {
                        if values.len() != weights.len() {
                            return Err(SeedKitError::Config {
                                message: format!(
                                    "Column '{}': weights has {} entries but values has {} entries. \
                                     They must be the same length.",
                                    key,
                                    weights.len(),
                                    values.len(),
                                ),
                            });
                        }
                    }
                    None => {
                        return Err(SeedKitError::Config {
                            message: format!(
                                "Column '{}': weights provided without values. \
                                 Add a matching values list or remove the weights.",
                                key,
                            ),
                        });
                    }
                }
            }
        }
        Ok(())
    }

    /// Validate column overrides against the introspected schema.
    ///
    /// Returns a list of warning messages for overrides that reference
    /// tables or columns not present in the schema. Called after introspection
    /// so developers catch stale config entries early.
    pub fn validate_against_schema(
        &self,
        schema: &crate::schema::types::DatabaseSchema,
    ) -> Vec<String> {
        let mut warnings = Vec::new();
        for key in self.columns.keys() {
            if let Some((table, col)) = key.split_once('.') {
                if let Some(table_def) = schema.tables.get(table) {
                    if !table_def.columns.contains_key(col) {
                        warnings.push(format!(
                            "seedkit.toml: [columns.\"{}\"] references column '{}' \
                             which does not exist in table '{}'",
                            key, col, table
                        ));
                    }
                } else {
                    warnings.push(format!(
                        "seedkit.toml: [columns.\"{}\"] references table '{}' \
                         which does not exist in schema",
                        key, table
                    ));
                }
            } else {
                warnings.push(format!(
                    "seedkit.toml: [columns.\"{}\"] is not in 'table.column' format",
                    key
                ));
            }
        }
        warnings
    }
}

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

    #[test]
    fn test_parse_full_config() {
        let toml = r#"
[database]
url = "postgres://localhost/myapp"
schema = "public"

[generate]
rows = 500
seed = 42
ai = false

[tables.users]
rows = 1000

[tables.orders]
rows = 5000

[columns."products.color"]
values = ["red", "blue", "green"]
weights = [0.5, 0.3, 0.2]

[columns."orders.tax_code"]
custom = "./scripts/tax_gen.js"

[graph]
break_cycle_at = ["users.invited_by_id", "comments.parent_id"]
"#;

        let config: SeedKitConfig = toml::from_str(toml).unwrap();

        assert_eq!(
            config.database.url.as_deref(),
            Some("postgres://localhost/myapp")
        );
        assert_eq!(config.database.schema.as_deref(), Some("public"));
        assert_eq!(config.generate.rows, Some(500));
        assert_eq!(config.generate.seed, Some(42));
        assert_eq!(config.generate.ai, Some(false));
        assert_eq!(config.tables["users"].rows, Some(1000));
        assert_eq!(config.tables["orders"].rows, Some(5000));

        let colors = config.columns["products.color"].values.as_ref().unwrap();
        assert_eq!(colors, &["red", "blue", "green"].map(FixtureValue::from));

        let weights = config.columns["products.color"].weights.as_ref().unwrap();
        assert_eq!(weights.len(), 3);

        assert_eq!(
            config.columns["orders.tax_code"].custom.as_deref(),
            Some("./scripts/tax_gen.js")
        );

        assert_eq!(config.graph.break_cycle_at.len(), 2);
    }

    #[test]
    fn test_parse_empty_config() {
        let toml = "";
        let config: SeedKitConfig = toml::from_str(toml).unwrap();

        assert!(config.database.url.is_none());
        assert!(config.generate.rows.is_none());
        assert!(config.tables.is_empty());
        assert!(config.columns.is_empty());
        assert!(config.graph.break_cycle_at.is_empty());
    }

    #[test]
    fn test_parse_minimal_config() {
        let toml = r#"
[database]
url = "sqlite://dev.db"
"#;

        let config: SeedKitConfig = toml::from_str(toml).unwrap();
        assert_eq!(config.database.url.as_deref(), Some("sqlite://dev.db"));
        assert!(config.generate.rows.is_none());
    }

    #[test]
    fn test_table_row_overrides() {
        let toml = r#"
[tables.users]
rows = 1000

[tables.orders]
rows = 5000

[tables.products]
"#;

        let config: SeedKitConfig = toml::from_str(toml).unwrap();
        let overrides = config.table_row_overrides();

        assert_eq!(overrides.len(), 2);
        assert_eq!(overrides["users"], 1000);
        assert_eq!(overrides["orders"], 5000);
    }

    #[test]
    fn test_cycle_break_edges() {
        let toml = r#"
[graph]
break_cycle_at = ["users.invited_by_id", "comments.parent_id", "invalid"]
"#;

        let config: SeedKitConfig = toml::from_str(toml).unwrap();
        let edges = config.cycle_break_edges();

        // "invalid" has no dot separator, so it's filtered out
        assert_eq!(edges.len(), 2);
        assert_eq!(edges[0], ("users".to_string(), "invited_by_id".to_string()));
        assert_eq!(edges[1], ("comments".to_string(), "parent_id".to_string()));
    }

    #[test]
    fn test_read_config_nonexistent() {
        let result = read_config(Path::new("/nonexistent/dir"));
        assert!(result.is_ok());
        assert!(result.unwrap().is_none());
    }

    #[test]
    fn test_read_config_from_disk() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("seedkit.toml");
        std::fs::write(
            &config_path,
            r#"
[database]
url = "postgres://localhost/test"

[generate]
rows = 200
"#,
        )
        .unwrap();

        let result = read_config(dir.path()).unwrap();
        assert!(result.is_some());
        let config = result.unwrap();
        assert_eq!(
            config.database.url.as_deref(),
            Some("postgres://localhost/test")
        );
        assert_eq!(config.generate.rows, Some(200));
    }

    #[test]
    fn test_read_config_invalid_toml() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("seedkit.toml");
        std::fs::write(&config_path, "this is not valid [[[toml").unwrap();

        let result = read_config(dir.path());
        assert!(result.is_err());
    }

    // --- Fix 1: cycle_break_edges should warn on malformed entries ---

    #[test]
    fn test_cycle_break_edges_malformed_entry_still_parses_valid() {
        // "invalid" has no dot separator — should be warned about and filtered out.
        // Valid entries should still be returned.
        let toml = r#"
[graph]
break_cycle_at = ["users.invited_by_id", "no_dot_here", "comments.parent_id"]
"#;
        let config: SeedKitConfig = toml::from_str(toml).unwrap();
        let edges = config.cycle_break_edges();

        assert_eq!(edges.len(), 2);
        assert_eq!(edges[0], ("users".to_string(), "invited_by_id".to_string()));
        assert_eq!(edges[1], ("comments".to_string(), "parent_id".to_string()));
        // The tracing::warn is verified by inspection — tests confirm behavior doesn't change.
    }

    #[test]
    fn read_config_rejects_custom_providers_with_a_replacement() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("seedkit.toml"),
            "[columns.\"orders.tax_code\"]\ncustom = \"./scripts/tax_gen.js\"\n",
        )
        .unwrap();
        let err = read_config(dir.path()).unwrap_err().to_string();
        assert!(
            err.contains("orders.tax_code") && err.contains("pattern"),
            "{err}"
        );
    }

    // --- Fix 3: validate() catches mismatched values/weights ---

    #[test]
    fn test_validate_matching_values_weights() {
        let toml = r#"
[columns."products.color"]
values = ["red", "blue", "green"]
weights = [0.5, 0.3, 0.2]
"#;
        let config: SeedKitConfig = toml::from_str(toml).unwrap();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_validate_mismatched_values_weights_fails() {
        let toml = r#"
[columns."products.color"]
values = ["red", "blue", "green", "black", "white"]
weights = [0.25, 0.20, 0.20, 0.20]
"#;
        let config: SeedKitConfig = toml::from_str(toml).unwrap();
        let err = config.validate();
        assert!(err.is_err());
        let msg = format!("{}", err.unwrap_err());
        assert!(
            msg.contains("products.color"),
            "Error should name the column: {}",
            msg
        );
        assert!(
            msg.contains("5"),
            "Error should mention values count: {}",
            msg
        );
        assert!(
            msg.contains("4"),
            "Error should mention weights count: {}",
            msg
        );
    }

    #[test]
    fn test_validate_weights_without_values_fails() {
        let toml = r#"
[columns."orders.status"]
weights = [0.5, 0.3, 0.2]
"#;
        let config: SeedKitConfig = toml::from_str(toml).unwrap();
        let err = config.validate();
        assert!(err.is_err());
        let msg = format!("{}", err.unwrap_err());
        assert!(
            msg.contains("orders.status"),
            "Error should name the column: {}",
            msg
        );
    }

    #[test]
    fn test_validate_values_without_weights_ok() {
        // values without weights is fine — uniform distribution
        let toml = r#"
[columns."products.color"]
values = ["red", "blue", "green"]
"#;
        let config: SeedKitConfig = toml::from_str(toml).unwrap();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_validate_no_columns_ok() {
        let toml = r#"
[generate]
rows = 100
"#;
        let config: SeedKitConfig = toml::from_str(toml).unwrap();
        assert!(config.validate().is_ok());
    }

    // --- Column generators ---

    fn columns(toml: &str) -> Result<SeedKitConfig> {
        let config: SeedKitConfig = toml::from_str(toml).map_err(|e| SeedKitError::Config {
            message: e.to_string(),
        })?;
        config.validate().map(|_| config)
    }

    #[test]
    fn column_generators_parse() {
        let config = columns(
            r#"
[columns."orders.number"]
pattern = "INV-{row:06}"

[columns."orders.total"]
range = [5, 500.5]
null_rate = 0.25

[columns."users.employer"]
semantic = "CompanyName"
"#,
        )
        .unwrap();
        assert_eq!(
            config.columns["orders.number"].pattern.as_deref(),
            Some("INV-{row:06}")
        );
        assert_eq!(config.columns["orders.total"].range, Some([5.0, 500.5]));
        assert_eq!(config.columns["orders.total"].null_rate, Some(0.25));
        assert_eq!(
            config.columns["users.employer"].semantic,
            Some(crate::classify::semantic::SemanticType::CompanyName)
        );
    }

    #[test]
    fn invalid_column_generators_are_rejected_before_introspection() {
        let cases = [
            ("null_rate = 1.5", "null_rate"),
            ("range = [10, 1]", "range"),
            ("values = [\"a\"]\npattern = \"X-#\"", "only one of"),
            ("pattern = \"INV-{row\"", "pattern"),
            ("pattern = \"\"", "pattern"),
            ("semantic = \"ProductCode\"", "ProductCode"),
            (
                "custom = \"./tax.js\"",
                "custom providers are not supported",
            ),
        ];
        for (body, expected) in cases {
            let err = columns(&format!("[columns.\"orders.code\"]\n{body}\n"))
                .err()
                .unwrap_or_else(|| panic!("{body} should be rejected"))
                .to_string();
            assert!(
                err.contains("orders.code") || err.contains(expected),
                "{body}: {err}"
            );
            assert!(err.contains(expected), "{body}: {err}");
        }
    }

    // --- Schema validation tests ---

    #[test]
    fn test_validate_against_schema_valid_override() {
        use crate::schema::types::*;

        let toml = r#"
[columns."users.email"]
values = ["a@b.com", "c@d.com"]
"#;
        let config: SeedKitConfig = toml::from_str(toml).unwrap();

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

        let warnings = config.validate_against_schema(&schema);
        assert!(
            warnings.is_empty(),
            "Valid override should produce no warnings: {:?}",
            warnings
        );
    }

    #[test]
    fn test_validate_against_schema_nonexistent_table() {
        use crate::schema::types::*;

        let toml = r#"
[columns."ghost.name"]
values = ["x"]
"#;
        let config: SeedKitConfig = toml::from_str(toml).unwrap();
        let schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());

        let warnings = config.validate_against_schema(&schema);
        assert_eq!(warnings.len(), 1);
        assert!(
            warnings[0].contains("ghost"),
            "Should mention table: {}",
            warnings[0]
        );
    }

    #[test]
    fn test_validate_against_schema_nonexistent_column() {
        use crate::schema::types::*;

        let toml = r#"
[columns."users.nonexistent"]
values = ["x"]
"#;
        let config: SeedKitConfig = toml::from_str(toml).unwrap();

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

        let warnings = config.validate_against_schema(&schema);
        assert_eq!(warnings.len(), 1);
        assert!(
            warnings[0].contains("nonexistent"),
            "Should mention column: {}",
            warnings[0]
        );
    }
}