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

use crate::error::{Result, SeedKitError};
use crate::sample::mask::is_pii_column;
use crate::schema::types::{Column, DatabaseSchema, DatabaseType};

/// Statistical distribution profile extracted from production data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DistributionProfile {
    pub table_name: String,
    pub row_count: u64,
    pub column_distributions: HashMap<String, ColumnDistribution>,
}

/// Distribution information for a single column.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ColumnDistribution {
    /// Categorical distribution (enum-like values with frequencies).
    Categorical {
        values: Vec<(String, f64)>, // (value, frequency)
    },
    /// Numeric distribution.
    Numeric {
        min: f64,
        max: f64,
        mean: f64,
        stddev: f64,
    },
    /// Ratio to another table's row count.
    Ratio {
        related_table: String,
        ratio: f64, // e.g., 3.2 orders per user
    },
}

/// Options for controlling the sampling process.
#[derive(Debug, Clone)]
pub struct SampleOptions {
    /// Only sample these tables (None = all tables).
    pub tables: Option<Vec<String>>,
    /// Qualified free-text columns whose source labels may be recorded.
    pub allow_text: Vec<(String, String)>,
    /// Maximum number of distinct values to extract for categorical distributions.
    pub categorical_limit: usize,
    /// Minimum number of rows a table must have to be sampled.
    pub min_row_count: u64,
}

impl Default for SampleOptions {
    fn default() -> Self {
        Self {
            tables: None,
            allow_text: Vec::new(),
            categorical_limit: 50,
            min_row_count: 10,
        }
    }
}

impl SampleOptions {
    fn sample_labels(&self, table: &str, column: &Column) -> bool {
        !is_pii_column(&column.name)
            && (column.enum_values.is_some()
                || (column.data_type.is_string()
                    && self
                        .allow_text
                        .iter()
                        .any(|(t, c)| t == table && c == &column.name)))
    }

    fn validate(&self, schema: &DatabaseSchema) -> Result<()> {
        for (table, name) in &self.allow_text {
            let column = schema.tables.get(table).and_then(|t| t.columns.get(name));
            if !column.is_some_and(|c| self.sample_labels(table, c)) {
                return Err(SeedKitError::Config {
                    message: format!("Cannot sample labels for {table}.{name}: expected an existing text or enum column outside the PII mask"),
                });
            }
        }
        Ok(())
    }
}

/// Generate a SQL query to extract the row count for a table.
pub fn row_count_query(table: &str, db_type: DatabaseType) -> String {
    count_from(&quote_ident(table, db_type))
}

fn count_from(quoted: &str) -> String {
    format!("SELECT COUNT(*) AS cnt FROM {quoted}")
}

/// Generate a SQL query to extract categorical distribution (value frequencies).
///
/// Returns rows of (value, frequency) where frequency is a proportion (0.0–1.0).
pub fn categorical_query(table: &str, column: &str, db_type: DatabaseType, limit: usize) -> String {
    categorical_from(&quote_ident(table, db_type), column, db_type, limit)
}

fn categorical_from(qt: &str, column: &str, db_type: DatabaseType, limit: usize) -> String {
    let qc = quote_ident(column, db_type);
    match db_type {
        DatabaseType::PostgreSQL => format!(
            "SELECT CAST({col} AS TEXT) AS val, \
             COUNT(*)::float / (SELECT COUNT(*) FROM {tbl})::float AS freq \
             FROM {tbl} WHERE {col} IS NOT NULL \
             GROUP BY {col} ORDER BY freq DESC LIMIT {lim}",
            col = qc,
            tbl = qt,
            lim = limit
        ),
        DatabaseType::MySQL => format!(
            "SELECT CAST({col} AS CHAR) AS val, \
             COUNT(*) * 1e0 / (SELECT COUNT(*) FROM {tbl}) AS freq \
             FROM {tbl} WHERE {col} IS NOT NULL \
             GROUP BY {col} ORDER BY freq DESC LIMIT {lim}",
            col = qc,
            tbl = qt,
            lim = limit
        ),
        DatabaseType::SQLite => format!(
            "SELECT CAST({col} AS TEXT) AS val, \
             CAST(COUNT(*) AS REAL) / (SELECT COUNT(*) FROM {tbl}) AS freq \
             FROM {tbl} WHERE {col} IS NOT NULL \
             GROUP BY {col} ORDER BY freq DESC LIMIT {lim}",
            col = qc,
            tbl = qt,
            lim = limit
        ),
    }
}

/// Generate a SQL query to extract numeric distribution (min, max, mean, stddev).
pub fn numeric_query(table: &str, column: &str, db_type: DatabaseType) -> String {
    numeric_from(&quote_ident(table, db_type), column, db_type)
}

fn numeric_from(qt: &str, column: &str, db_type: DatabaseType) -> String {
    let qc = quote_ident(column, db_type);
    match db_type {
        DatabaseType::PostgreSQL => format!(
            "SELECT MIN({col})::float8 AS min_val, MAX({col})::float8 AS max_val, \
             AVG({col})::float8 AS mean_val, COALESCE(STDDEV_POP({col})::float8, 0) AS stddev_val \
             FROM {tbl} WHERE {col} IS NOT NULL",
            col = qc,
            tbl = qt,
        ),
        // MySQL returns DOUBLE when an aggregate has an approximate numeric operand.
        DatabaseType::MySQL => format!(
            "SELECT MIN({col}) * 1e0 AS min_val, MAX({col}) * 1e0 AS max_val, \
             AVG({col} * 1e0) AS mean_val, COALESCE(STDDEV({col}), 0e0) AS stddev_val \
             FROM {tbl} WHERE {col} IS NOT NULL",
            col = qc,
            tbl = qt,
        ),
        // SQLite has no STDDEV and math functions are optional, so return the
        // population variance; `extract_table_profile_sqlite` takes its root.
        DatabaseType::SQLite => format!(
            "SELECT CAST(MIN({col}) AS REAL) AS min_val, CAST(MAX({col}) AS REAL) AS max_val, \
             AVG({col}) AS mean_val, \
             AVG(CAST({col} AS REAL) * {col}) - AVG({col}) * AVG({col}) AS variance_val \
             FROM {tbl} WHERE {col} IS NOT NULL",
            col = qc,
            tbl = qt,
        ),
    }
}

/// Generate a SQL query to compute the ratio of child rows per parent row.
///
/// Returns a single row with the average number of child rows per distinct parent FK value.
pub fn ratio_query(
    child_table: &str,
    fk_column: &str,
    parent_table: &str,
    db_type: DatabaseType,
) -> String {
    let qct = quote_ident(child_table, db_type);
    let qfk = quote_ident(fk_column, db_type);
    let qpt = quote_ident(parent_table, db_type);
    match db_type {
        DatabaseType::PostgreSQL => format!(
            "SELECT CASE WHEN (SELECT COUNT(*) FROM {pt}) = 0 THEN 0.0 \
             ELSE (SELECT COUNT(*) FROM {ct})::float / (SELECT COUNT(*) FROM {pt})::float \
             END AS ratio",
            ct = qct,
            pt = qpt,
        ),
        DatabaseType::MySQL => format!(
            "SELECT CASE WHEN (SELECT COUNT(*) FROM {pt}) = 0 THEN 0.0 \
             ELSE (SELECT COUNT(*) FROM {ct}) / (SELECT COUNT(*) FROM {pt}) \
             END AS ratio",
            ct = qct,
            pt = qpt,
        ),
        DatabaseType::SQLite => format!(
            "SELECT CASE WHEN (SELECT COUNT(*) FROM {pt}) = 0 THEN 0.0 \
             ELSE CAST((SELECT COUNT(*) FROM {ct}) AS REAL) / (SELECT COUNT(*) FROM {pt}) \
             END AS ratio",
            ct = qct,
            pt = qpt,
        ),
    }
    // fk_column is used for context but the ratio query itself is table-level
    .replace("__FK_COLUMN__", &qfk) // placeholder not used, but keep param for API consistency
}

/// Extract distribution profiles from a live database.
pub async fn extract_distributions(
    url: &str,
    schema: &DatabaseSchema,
    options: &SampleOptions,
) -> Result<Vec<DistributionProfile>> {
    options.validate(schema)?;
    let tables_to_sample: Vec<&String> = if let Some(ref include) = options.tables {
        schema
            .tables
            .keys()
            .filter(|t| include.contains(t))
            .collect()
    } else {
        schema.tables.keys().collect()
    };

    let mut profiles = Vec::new();

    match schema.database_type {
        DatabaseType::PostgreSQL => {
            let pool = sqlx::postgres::PgPoolOptions::new()
                .max_connections(3)
                .connect(url)
                .await
                .map_err(|e| SeedKitError::Introspection {
                    query: "sample connect".to_string(),
                    source: e,
                })?;

            for table_name in &tables_to_sample {
                let profile = extract_table_profile_pg(&pool, table_name, schema, options).await?;
                if let Some(p) = profile {
                    profiles.push(p);
                }
            }
            pool.close().await;
        }
        DatabaseType::MySQL => {
            let pool = sqlx::mysql::MySqlPoolOptions::new()
                .max_connections(3)
                .connect(url)
                .await
                .map_err(|e| SeedKitError::Introspection {
                    query: "sample connect".to_string(),
                    source: e,
                })?;

            for table_name in &tables_to_sample {
                let profile =
                    extract_table_profile_mysql(&pool, table_name, schema, options).await?;
                if let Some(p) = profile {
                    profiles.push(p);
                }
            }
            pool.close().await;
        }
        DatabaseType::SQLite => {
            let pool = sqlx::sqlite::SqlitePoolOptions::new()
                .max_connections(1)
                .connect(url)
                .await
                .map_err(|e| SeedKitError::Introspection {
                    query: "sample connect".to_string(),
                    source: e,
                })?;

            for table_name in &tables_to_sample {
                let profile =
                    extract_table_profile_sqlite(&pool, table_name, schema, options).await?;
                if let Some(p) = profile {
                    profiles.push(p);
                }
            }
            pool.close().await;
        }
    }

    // Compute ratio distributions from FK relationships
    compute_ratio_distributions(&mut profiles, schema);

    Ok(profiles)
}

async fn extract_table_profile_pg(
    pool: &sqlx::PgPool,
    table_name: &str,
    schema: &DatabaseSchema,
    options: &SampleOptions,
) -> Result<Option<DistributionProfile>> {
    use sqlx::Row;

    // Get row count
    let quoted_table = schema.quoted_table(table_name);
    let count_sql = count_from(&quoted_table);
    let row: (i64,) = sqlx::query_as(&count_sql)
        .fetch_one(pool)
        .await
        .map_err(|e| SeedKitError::Introspection {
            query: format!("row count for {}", table_name),
            source: e,
        })?;

    let row_count = row.0 as u64;
    if row_count < options.min_row_count {
        return Ok(None);
    }

    let table = match schema.tables.get(table_name) {
        Some(t) => t,
        None => return Ok(None),
    };

    let mut distributions = HashMap::new();

    for (col_name, column) in &table.columns {
        // Skip auto-increment PKs
        if column.is_auto_increment || column.data_type.is_serial() {
            continue;
        }

        if column.data_type.is_numeric() {
            let sql = numeric_from(&quoted_table, col_name, DatabaseType::PostgreSQL);
            let result = sqlx::query(&sql).fetch_one(pool).await;
            if let Ok(row) = result {
                let min_val: Option<f64> = row.get("min_val");
                let max_val: Option<f64> = row.get("max_val");
                let mean_val: Option<f64> = row.get("mean_val");
                let stddev_val: Option<f64> = row.get("stddev_val");
                if let (Some(min), Some(max), Some(mean), Some(stddev)) =
                    (min_val, max_val, mean_val, stddev_val)
                {
                    distributions.insert(
                        col_name.clone(),
                        ColumnDistribution::Numeric {
                            min,
                            max,
                            mean,
                            stddev,
                        },
                    );
                }
            }
        } else if options.sample_labels(table_name, column) {
            let sql = categorical_from(
                &quoted_table,
                col_name,
                DatabaseType::PostgreSQL,
                options.categorical_limit,
            );
            let result = sqlx::query(&sql).fetch_all(pool).await;
            if let Ok(rows) = result {
                let values: Vec<(String, f64)> = rows
                    .iter()
                    .filter_map(|r| {
                        let val: Option<String> = r.get("val");
                        let freq: Option<f64> = r.get("freq");
                        val.zip(freq)
                    })
                    .collect();
                if !values.is_empty() {
                    distributions
                        .insert(col_name.clone(), ColumnDistribution::Categorical { values });
                }
            }
        }
    }

    Ok(Some(DistributionProfile {
        table_name: table_name.to_string(),
        row_count,
        column_distributions: distributions,
    }))
}

async fn extract_table_profile_mysql(
    pool: &sqlx::MySqlPool,
    table_name: &str,
    schema: &DatabaseSchema,
    options: &SampleOptions,
) -> Result<Option<DistributionProfile>> {
    use sqlx::Row;

    let count_sql = row_count_query(table_name, DatabaseType::MySQL);
    let row: (i64,) = sqlx::query_as(&count_sql)
        .fetch_one(pool)
        .await
        .map_err(|e| SeedKitError::Introspection {
            query: format!("row count for {}", table_name),
            source: e,
        })?;

    let row_count = row.0 as u64;
    if row_count < options.min_row_count {
        return Ok(None);
    }

    let table = match schema.tables.get(table_name) {
        Some(t) => t,
        None => return Ok(None),
    };

    let mut distributions = HashMap::new();

    for (col_name, column) in &table.columns {
        if column.is_auto_increment || column.data_type.is_serial() {
            continue;
        }

        if column.data_type.is_numeric() {
            let sql = numeric_query(table_name, col_name, DatabaseType::MySQL);
            let result = sqlx::query(&sql).fetch_one(pool).await;
            if let Ok(row) = result {
                let min_val: Option<f64> = row.get("min_val");
                let max_val: Option<f64> = row.get("max_val");
                let mean_val: Option<f64> = row.get("mean_val");
                let stddev_val: Option<f64> = row.get("stddev_val");
                if let (Some(min), Some(max), Some(mean), Some(stddev)) =
                    (min_val, max_val, mean_val, stddev_val)
                {
                    distributions.insert(
                        col_name.clone(),
                        ColumnDistribution::Numeric {
                            min,
                            max,
                            mean,
                            stddev,
                        },
                    );
                }
            }
        } else if options.sample_labels(table_name, column) {
            let sql = categorical_query(
                table_name,
                col_name,
                DatabaseType::MySQL,
                options.categorical_limit,
            );
            let result = sqlx::query(&sql).fetch_all(pool).await;
            if let Ok(rows) = result {
                let values: Vec<(String, f64)> = rows
                    .iter()
                    .filter_map(|r| {
                        let val: Option<String> = r.get("val");
                        let freq: Option<f64> = r.get("freq");
                        val.zip(freq)
                    })
                    .collect();
                if !values.is_empty() {
                    distributions
                        .insert(col_name.clone(), ColumnDistribution::Categorical { values });
                }
            }
        }
    }

    Ok(Some(DistributionProfile {
        table_name: table_name.to_string(),
        row_count,
        column_distributions: distributions,
    }))
}

async fn extract_table_profile_sqlite(
    pool: &sqlx::SqlitePool,
    table_name: &str,
    schema: &DatabaseSchema,
    options: &SampleOptions,
) -> Result<Option<DistributionProfile>> {
    use sqlx::Row;

    let count_sql = row_count_query(table_name, DatabaseType::SQLite);
    let row: (i64,) = sqlx::query_as(&count_sql)
        .fetch_one(pool)
        .await
        .map_err(|e| SeedKitError::Introspection {
            query: format!("row count for {}", table_name),
            source: e,
        })?;

    let row_count = row.0 as u64;
    if row_count < options.min_row_count {
        return Ok(None);
    }

    let table = match schema.tables.get(table_name) {
        Some(t) => t,
        None => return Ok(None),
    };

    let mut distributions = HashMap::new();

    for (col_name, column) in &table.columns {
        if column.is_auto_increment || column.data_type.is_serial() {
            continue;
        }

        if column.data_type.is_numeric() {
            let sql = numeric_query(table_name, col_name, DatabaseType::SQLite);
            let result = sqlx::query(&sql).fetch_one(pool).await;
            if let Ok(row) = result {
                let min_val: Option<f64> = row.get("min_val");
                let max_val: Option<f64> = row.get("max_val");
                let mean_val: Option<f64> = row.get("mean_val");
                // Rounding can leave a tiny negative variance for constant columns.
                let stddev_val = row
                    .get::<Option<f64>, _>("variance_val")
                    .map(|variance| variance.max(0.0).sqrt());
                if let (Some(min), Some(max), Some(mean), Some(stddev)) =
                    (min_val, max_val, mean_val, stddev_val)
                {
                    distributions.insert(
                        col_name.clone(),
                        ColumnDistribution::Numeric {
                            min,
                            max,
                            mean,
                            stddev,
                        },
                    );
                }
            }
        } else if options.sample_labels(table_name, column) {
            let sql = categorical_query(
                table_name,
                col_name,
                DatabaseType::SQLite,
                options.categorical_limit,
            );
            let result = sqlx::query(&sql).fetch_all(pool).await;
            if let Ok(rows) = result {
                let values: Vec<(String, f64)> = rows
                    .iter()
                    .filter_map(|r| {
                        let val: Option<String> = r.get("val");
                        let freq: Option<f64> = r.get("freq");
                        val.zip(freq)
                    })
                    .collect();
                if !values.is_empty() {
                    distributions
                        .insert(col_name.clone(), ColumnDistribution::Categorical { values });
                }
            }
        }
    }

    Ok(Some(DistributionProfile {
        table_name: table_name.to_string(),
        row_count,
        column_distributions: distributions,
    }))
}

/// Compute ratio distributions from FK relationships.
///
/// For each FK relationship, if both parent and child tables were sampled,
/// add a `Ratio` distribution to the child table's profile.
fn compute_ratio_distributions(profiles: &mut [DistributionProfile], schema: &DatabaseSchema) {
    // Build a lookup of table_name -> row_count from profiles
    let row_counts: HashMap<&str, u64> = profiles
        .iter()
        .map(|p| (p.table_name.as_str(), p.row_count))
        .collect();

    // Collect ratios to add (avoid borrowing profiles mutably while iterating)
    let mut ratios_to_add: Vec<(String, String, String, f64)> = Vec::new();

    for table_name in schema.tables.keys() {
        if let Some(table) = schema.tables.get(table_name) {
            for fk in table.local_foreign_keys() {
                if let (Some(&child_count), Some(&parent_count)) = (
                    row_counts.get(table_name.as_str()),
                    row_counts.get(fk.referenced_table.as_str()),
                ) {
                    if parent_count > 0 {
                        let ratio = child_count as f64 / parent_count as f64;
                        let col_name = fk.source_columns.first().cloned().unwrap_or_default();
                        ratios_to_add.push((
                            table_name.clone(),
                            col_name,
                            fk.referenced_table.clone(),
                            ratio,
                        ));
                    }
                }
            }
        }
    }

    for (table_name, col_name, ref_table, ratio) in ratios_to_add {
        if let Some(profile) = profiles.iter_mut().find(|p| p.table_name == table_name) {
            let key = format!("__ratio_{}", col_name);
            profile.column_distributions.insert(
                key,
                ColumnDistribution::Ratio {
                    related_table: ref_table,
                    ratio,
                },
            );
        }
    }
}

fn quote_ident(name: &str, db_type: DatabaseType) -> String {
    db_type.quote_identifier(name)
}

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

    #[test]
    fn test_categorical_query_postgres() {
        let sql = categorical_query("users", "status", DatabaseType::PostgreSQL, 50);
        assert!(sql.contains("CAST(\"status\" AS TEXT)"));
        assert!(sql.contains("::float"));
        assert!(sql.contains("LIMIT 50"));
        assert!(sql.contains("GROUP BY"));
    }

    #[test]
    fn test_categorical_query_mysql() {
        let sql = categorical_query("users", "status", DatabaseType::MySQL, 25);
        assert!(sql.contains("CAST(`status` AS CHAR)"));
        assert!(sql.contains("LIMIT 25"));
        assert!(sql.contains("`users`"));
    }

    #[test]
    fn test_categorical_query_sqlite() {
        let sql = categorical_query("users", "status", DatabaseType::SQLite, 50);
        assert!(sql.contains("CAST(\"status\" AS TEXT)"));
        assert!(sql.contains("CAST(COUNT(*) AS REAL)"));
    }

    #[test]
    fn test_numeric_query_postgres() {
        let sql = numeric_query("products", "price", DatabaseType::PostgreSQL);
        assert!(sql.contains("MIN(\"price\")"));
        assert!(sql.contains("STDDEV_POP"));
        assert!(sql.contains("::float8"));
    }

    #[test]
    fn test_numeric_query_mysql() {
        let sql = numeric_query("products", "price", DatabaseType::MySQL);
        assert!(sql.contains("MIN(`price`)"));
        assert!(sql.contains("STDDEV("));
        assert!(!sql.contains("STDDEV_POP"));
    }

    #[test]
    fn test_numeric_query_sqlite_population_variance() {
        let sql = numeric_query("products", "price", DatabaseType::SQLite);
        assert!(sql.contains(
            "AVG(CAST(\"price\" AS REAL) * \"price\") - AVG(\"price\") * AVG(\"price\") AS variance_val"
        ));
        assert!(!sql.contains("STDDEV"));
    }

    #[test]
    fn test_ratio_query_postgres() {
        let sql = ratio_query("orders", "user_id", "users", DatabaseType::PostgreSQL);
        assert!(sql.contains("\"orders\""));
        assert!(sql.contains("\"users\""));
        assert!(sql.contains("::float"));
    }

    #[test]
    fn test_row_count_query() {
        let sql = row_count_query("users", DatabaseType::PostgreSQL);
        assert_eq!(sql, "SELECT COUNT(*) AS cnt FROM \"users\"");
    }

    #[test]
    fn samples_declared_enums_without_text_opt_in() {
        let mut col = Column::new(
            "status".into(),
            crate::schema::types::DataType::Enum("state".into()),
            "state".into(),
        );
        col.enum_values = Some(vec!["open".into()]);
        assert!(SampleOptions::default().sample_labels("orders", &col));
        col.name = "email".into();
        assert!(!SampleOptions::default().sample_labels("orders", &col));
    }

    #[test]
    fn test_sample_options_default() {
        let opts = SampleOptions::default();
        assert_eq!(opts.categorical_limit, 50);
        assert_eq!(opts.min_row_count, 10);
        assert!(opts.tables.is_none());
    }

    #[test]
    fn test_distribution_profile_serde_round_trip() {
        let profile = DistributionProfile {
            table_name: "users".to_string(),
            row_count: 1000,
            column_distributions: {
                let mut m = HashMap::new();
                m.insert(
                    "status".to_string(),
                    ColumnDistribution::Categorical {
                        values: vec![("active".to_string(), 0.7), ("inactive".to_string(), 0.3)],
                    },
                );
                m.insert(
                    "age".to_string(),
                    ColumnDistribution::Numeric {
                        min: 18.0,
                        max: 90.0,
                        mean: 35.0,
                        stddev: 12.5,
                    },
                );
                m.insert(
                    "__ratio_user_id".to_string(),
                    ColumnDistribution::Ratio {
                        related_table: "orders".to_string(),
                        ratio: 3.2,
                    },
                );
                m
            },
        };

        let json = serde_json::to_string_pretty(&profile).unwrap();
        let restored: DistributionProfile = serde_json::from_str(&json).unwrap();
        assert_eq!(restored.table_name, "users");
        assert_eq!(restored.row_count, 1000);
        assert_eq!(restored.column_distributions.len(), 3);
    }
}