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
use std::borrow::Cow;

use chrono::{Duration as ChronoDuration, NaiveTime};
use fake::faker::address::en::*;
use fake::faker::company::en::*;
use fake::faker::internet::en::*;
use fake::faker::lorem::en::*;
use fake::faker::name::en::*;
use fake::faker::phone_number::en::*;
use fake::Fake;
use rand::Rng;
use uuid::Builder;

use crate::classify::semantic::SemanticType;
use crate::generate::locale::Locale;
use crate::generate::value::Value;
use crate::schema::types::ParsedCheck;

/// Wrap a dynamically generated String into a Value::String.
#[inline]
fn owned(s: String) -> Value {
    Value::String(Cow::Owned(s))
}

/// Wrap a static string literal into a Value::String (zero heap allocation).
#[inline]
fn borrowed(s: &'static str) -> Value {
    Value::String(Cow::Borrowed(s))
}

/// Generate a value for a given semantic type.
///
/// `base_time` is the pinned wall-clock timestamp captured at plan creation.
/// All temporal values are derived from this anchor so that regeneration from a
/// lockfile produces identical output regardless of when it runs.
pub fn generate_value(
    semantic_type: SemanticType,
    rng: &mut impl Rng,
    row_index: usize,
    check_constraints: &[ParsedCheck],
    base_time: chrono::NaiveDateTime,
) -> Value {
    let value = match semantic_type {
        // === Identity ===
        SemanticType::FirstName => owned(FirstName().fake_with_rng(rng)),
        SemanticType::LastName => owned(LastName().fake_with_rng(rng)),
        SemanticType::FullName => owned(Name().fake_with_rng(rng)),
        SemanticType::Username => {
            let user: String = Username().fake_with_rng(rng);
            owned(format!("{}{}", user, row_index))
        }
        SemanticType::DisplayName => owned(Name().fake_with_rng(rng)),

        // === Contact ===
        SemanticType::Email => {
            let email: String = SafeEmail().fake_with_rng(rng);
            let parts: Vec<&str> = email.splitn(2, '@').collect();
            if parts.len() == 2 {
                owned(format!("{}.{}@{}", parts[0], row_index, parts[1]))
            } else {
                owned(format!("user{}@example.com", row_index))
            }
        }
        SemanticType::Phone => owned(PhoneNumber().fake_with_rng(rng)),
        SemanticType::PhoneCountryCode => {
            let codes = ["+1", "+44", "+49", "+33", "+81", "+86", "+91", "+55", "+61"];
            borrowed(codes[rng.random_range(0..codes.len())])
        }

        // === Address ===
        SemanticType::StreetAddress => owned(StreetName().fake_with_rng(rng)),
        SemanticType::City => owned(CityName().fake_with_rng(rng)),
        SemanticType::State => owned(StateName().fake_with_rng(rng)),
        SemanticType::ZipCode => owned(ZipCode().fake_with_rng(rng)),
        SemanticType::PostalCode => owned(ZipCode().fake_with_rng(rng)),
        SemanticType::Country => owned(CountryName().fake_with_rng(rng)),
        SemanticType::CountryCode => owned(CountryCode().fake_with_rng(rng)),
        SemanticType::Latitude => Value::Float(Latitude().fake_with_rng(rng)),
        SemanticType::Longitude => Value::Float(Longitude().fake_with_rng(rng)),

        // === Company ===
        SemanticType::CompanyName => owned(CompanyName().fake_with_rng(rng)),
        SemanticType::JobTitle => owned(Profession().fake_with_rng(rng)),
        SemanticType::Department => {
            let depts = [
                "Engineering",
                "Sales",
                "Marketing",
                "Product",
                "Design",
                "HR",
                "Finance",
                "Legal",
                "Operations",
                "Support",
            ];
            borrowed(depts[rng.random_range(0..depts.len())])
        }
        SemanticType::Industry => owned(Industry().fake_with_rng(rng)),

        // === Internet ===
        SemanticType::Url => {
            let domain: String = DomainSuffix().fake_with_rng(rng);
            owned(format!("https://example-{}.{}", row_index, domain))
        }
        SemanticType::DomainName => owned(FreeEmailProvider().fake_with_rng(rng)),
        SemanticType::IpAddress => owned(IPv4().fake_with_rng(rng)),
        SemanticType::MacAddress => owned(MACAddress().fake_with_rng(rng)),
        SemanticType::UserAgent => owned(UserAgent().fake_with_rng(rng)),
        SemanticType::Slug => {
            let words: Vec<String> = Words(2..4).fake_with_rng(rng);
            owned(words.join("-"))
        }

        // === Content ===
        SemanticType::Title => {
            let words: Vec<String> = Words(3..8).fake_with_rng(rng);
            let title = words.join(" ");
            let mut chars = title.chars();
            let capitalized = match chars.next() {
                None => String::new(),
                Some(c) => c.to_uppercase().to_string() + chars.as_str(),
            };
            owned(capitalized)
        }
        SemanticType::Description => {
            let sentences: Vec<String> = Sentences(2..4).fake_with_rng(rng);
            owned(sentences.join(" "))
        }
        SemanticType::Bio => {
            let sentences: Vec<String> = Sentences(1..3).fake_with_rng(rng);
            owned(sentences.join(" "))
        }
        SemanticType::Paragraph => {
            let paragraphs: Vec<String> = Paragraphs(1..3).fake_with_rng(rng);
            owned(paragraphs.join("\n\n"))
        }
        SemanticType::Sentence => owned(Sentence(5..12).fake_with_rng(rng)),
        SemanticType::HtmlContent => {
            let sentences: Vec<String> = Sentences(2..5).fake_with_rng(rng);
            owned(format!("<p>{}</p>", sentences.join("</p><p>")))
        }
        SemanticType::MarkdownContent => {
            let title_words: Vec<String> = Words(3..6).fake_with_rng(rng);
            let sentences: Vec<String> = Sentences(2..4).fake_with_rng(rng);
            owned(format!(
                "# {}\n\n{}",
                title_words.join(" "),
                sentences.join(" ")
            ))
        }

        // === Media ===
        SemanticType::ImageUrl => {
            owned(format!("https://picsum.photos/seed/{}/800/600", row_index))
        }
        SemanticType::AvatarUrl => owned(format!(
            "https://api.dicebear.com/7.x/avataaars/svg?seed={}",
            row_index
        )),
        SemanticType::ThumbnailUrl => {
            owned(format!("https://picsum.photos/seed/{}/200/200", row_index))
        }
        SemanticType::FileUrl => {
            let exts = ["pdf", "docx", "xlsx", "png", "jpg"];
            owned(format!(
                "https://cdn.example.com/files/file_{}.{}",
                row_index,
                exts[rng.random_range(0..exts.len())]
            ))
        }
        SemanticType::FileName => {
            let words: Vec<String> = Words(1..3).fake_with_rng(rng);
            let exts = ["pdf", "docx", "xlsx", "png", "jpg", "csv", "txt"];
            owned(format!(
                "{}.{}",
                words.join("_"),
                exts[rng.random_range(0..exts.len())]
            ))
        }
        SemanticType::MimeType => {
            let types = [
                "application/pdf",
                "image/png",
                "image/jpeg",
                "text/plain",
                "application/json",
                "text/html",
                "application/xml",
            ];
            borrowed(types[rng.random_range(0..types.len())])
        }
        SemanticType::FileSize => Value::Int(rng.random_range(1024..10_485_760)),

        // === Financial ===
        SemanticType::Price | SemanticType::Amount => {
            let (min, max) = compute_numeric_bounds_f64(0.01, 999.99, check_constraints);
            let val: f64 = rng.random_range(min..=max);
            Value::Float((val * 100.0_f64).round() / 100.0_f64)
        }
        SemanticType::Currency => {
            let currencies = ["USD", "EUR", "GBP", "JPY", "CAD", "AUD", "CHF"];
            borrowed(currencies[rng.random_range(0..currencies.len())])
        }
        SemanticType::CurrencyCode => {
            let codes = ["USD", "EUR", "GBP", "JPY", "CAD", "AUD", "CHF"];
            borrowed(codes[rng.random_range(0..codes.len())])
        }
        SemanticType::Percentage => {
            let val: f64 = rng.random_range(0.0_f64..100.0_f64);
            Value::Float((val * 100.0_f64).round() / 100.0_f64)
        }

        // === Temporal ===
        SemanticType::CreatedAt | SemanticType::Timestamp => {
            let days_ago = rng.random_range(1..365);
            let hours = rng.random_range(0..24);
            let minutes = rng.random_range(0..60);
            let base = base_time - ChronoDuration::days(days_ago)
                + ChronoDuration::hours(hours)
                + ChronoDuration::minutes(minutes);
            Value::Timestamp(base)
        }
        SemanticType::UpdatedAt => {
            let days_ago = rng.random_range(0..30);
            let base = base_time - ChronoDuration::days(days_ago);
            Value::Timestamp(base)
        }
        SemanticType::DeletedAt => {
            let days_ago = rng.random_range(0..7);
            let base = base_time - ChronoDuration::days(days_ago);
            Value::Timestamp(base)
        }
        SemanticType::StartDate => {
            let days_from_now = rng.random_range(-30..90);
            let base = base_time.date() + ChronoDuration::days(days_from_now);
            Value::Date(base)
        }
        SemanticType::EndDate => {
            let days_from_now = rng.random_range(30..180);
            let base = base_time.date() + ChronoDuration::days(days_from_now);
            Value::Date(base)
        }
        SemanticType::BirthDate => {
            let years_ago = rng.random_range(18..80);
            let days_extra = rng.random_range(0..365);
            let base = base_time.date() - ChronoDuration::days(years_ago * 365 + days_extra);
            Value::Date(base)
        }
        SemanticType::DateOnly => {
            let days_offset = rng.random_range(-365..365);
            let base = base_time.date() + ChronoDuration::days(days_offset);
            Value::Date(base)
        }
        SemanticType::TimeOnly => {
            let hour = rng.random_range(0..24) as u32;
            let min = rng.random_range(0..60) as u32;
            let sec = rng.random_range(0..60) as u32;
            Value::Time(NaiveTime::from_hms_opt(hour, min, sec).unwrap_or_default())
        }

        // === Auth/Security ===
        SemanticType::PasswordHash => {
            owned(format!("$2b$12${}", generate_random_alphanumeric(rng, 53)))
        }
        SemanticType::Token | SemanticType::ApiKey | SemanticType::SecretKey => {
            owned(generate_random_alphanumeric(rng, 32))
        }

        // === Identifiers ===
        SemanticType::Uuid => Value::Uuid(Builder::from_random_bytes(rng.random()).into_uuid()),
        SemanticType::AutoIncrement => Value::Int(row_index as i64 + 1),
        SemanticType::ExternalId => owned(format!("ext_{}", generate_random_alphanumeric(rng, 12))),
        SemanticType::Sku => owned(format!("SKU-{:06}", row_index + 1)),
        SemanticType::OrderNumber => owned(format!("ORD-{:08}", row_index + 1)),
        SemanticType::InvoiceNumber => owned(format!("INV-{:08}", row_index + 1)),
        SemanticType::TrackingNumber => owned(format!(
            "TRK{}",
            generate_random_alphanumeric(rng, 16).to_uppercase()
        )),

        // === Status/Enum (static — zero allocation via Cow::Borrowed) ===
        SemanticType::Status => {
            let statuses = ["active", "inactive", "pending", "suspended"];
            borrowed(statuses[rng.random_range(0..statuses.len())])
        }
        SemanticType::Role => {
            let roles = ["admin", "user", "moderator", "editor", "viewer"];
            borrowed(roles[rng.random_range(0..roles.len())])
        }
        SemanticType::Priority => {
            let priorities = ["low", "medium", "high", "critical"];
            borrowed(priorities[rng.random_range(0..priorities.len())])
        }
        SemanticType::Category => {
            let words: Vec<String> = Words(1..2).fake_with_rng(rng);
            owned(words.join(" "))
        }
        SemanticType::Tag => {
            let words: Vec<String> = Words(1..2).fake_with_rng(rng);
            owned(words.join("-"))
        }
        SemanticType::BooleanFlag => Value::Bool(rng.random_bool(0.7)),
        SemanticType::EnumValue => borrowed("unknown"),

        // === Numeric ===
        SemanticType::Quantity => {
            let (min, max) = compute_numeric_bounds_i64(1, 100, check_constraints);
            Value::Int(rng.random_range(min..=max))
        }
        SemanticType::Rating => {
            let val: f64 = rng.random_range(1.0_f64..5.0_f64);
            Value::Float((val * 10.0_f64).round() / 10.0_f64)
        }
        SemanticType::Score => Value::Int(rng.random_range(0..=100)),
        SemanticType::Weight => {
            let val: f64 = rng.random_range(0.1_f64..100.0_f64);
            Value::Float((val * 100.0_f64).round() / 100.0_f64)
        }
        SemanticType::Height => {
            let val: f64 = rng.random_range(50.0_f64..250.0_f64);
            Value::Float((val * 10.0_f64).round() / 10.0_f64)
        }
        SemanticType::Age => Value::Int(rng.random_range(18..90)),
        SemanticType::Duration => Value::Int(rng.random_range(1..3600)),
        SemanticType::SortOrder => Value::Int(row_index as i64),

        // === Data ===
        SemanticType::JsonData => {
            let keys = ["metadata", "preferences", "flags", "raw_payload"];
            let key = keys[rng.random_range(0..keys.len())];
            Value::Json(serde_json::json!({
                key: generate_random_alphanumeric(rng, 8),
                "processed": rng.random_bool(0.8),
                "retries": rng.random_range(0u32..5u32)
            }))
        }
        SemanticType::Color => {
            let colors = [
                "red", "blue", "green", "yellow", "purple", "orange", "pink", "black", "white",
                "gray", "brown", "cyan", "magenta", "teal",
            ];
            borrowed(colors[rng.random_range(0..colors.len())])
        }
        SemanticType::HexColor => owned(format!(
            "#{:02x}{:02x}{:02x}",
            rng.random_range(0..=255u8),
            rng.random_range(0..=255u8),
            rng.random_range(0..=255u8)
        )),
        SemanticType::Locale => {
            let locales = [
                "en_US", "en_GB", "de_DE", "fr_FR", "es_ES", "ja_JP", "zh_CN", "pt_BR",
            ];
            borrowed(locales[rng.random_range(0..locales.len())])
        }
        SemanticType::Timezone => {
            let tzs = [
                "America/New_York",
                "America/Chicago",
                "America/Los_Angeles",
                "Europe/London",
                "Europe/Berlin",
                "Asia/Tokyo",
                "Asia/Shanghai",
                "Australia/Sydney",
                "America/Sao_Paulo",
            ];
            borrowed(tzs[rng.random_range(0..tzs.len())])
        }

        // === Catch-all ===
        SemanticType::Unknown => {
            let word: String = Word().fake_with_rng(rng);
            owned(word)
        }
    };

    value
}

/// [`generate_value`] in a locale: names, places, companies, job titles, and
/// phone numbers come from the locale's data; everything else, and every
/// type in English, from the English generators.
pub fn generate_localized(
    locale: Locale,
    semantic_type: SemanticType,
    rng: &mut impl Rng,
    row_index: usize,
    check_constraints: &[ParsedCheck],
    base_time: chrono::NaiveDateTime,
) -> Value {
    locale.sample(semantic_type, rng).unwrap_or_else(|| {
        generate_value(semantic_type, rng, row_index, check_constraints, base_time)
    })
}

/// Compute safe f64 bounds from CHECK constraints, clamping if they conflict.
fn compute_numeric_bounds_f64(
    default_min: f64,
    default_max: f64,
    constraints: &[ParsedCheck],
) -> (f64, f64) {
    let mut min = default_min;
    let mut max = default_max;
    for c in constraints {
        match c {
            ParsedCheck::GreaterThanOrEqual { value, .. } => min = min.max(*value),
            ParsedCheck::GreaterThan { value, .. } => min = min.max(*value + 0.01),
            ParsedCheck::LessThanOrEqual { value, .. } => max = max.min(*value),
            ParsedCheck::LessThan { value, .. } => max = max.min(*value - 0.01),
            _ => {}
        }
    }
    if min > max {
        tracing::warn!(
            "Conflicting numeric bounds (min: {}, max: {}). Widening.",
            min,
            max
        );
        max = min + 100.0;
    }
    (min, max)
}

/// Compute safe i64 bounds from CHECK constraints.
fn compute_numeric_bounds_i64(
    default_min: i64,
    default_max: i64,
    constraints: &[ParsedCheck],
) -> (i64, i64) {
    let mut min = default_min;
    let mut max = default_max;
    for c in constraints {
        match c {
            ParsedCheck::GreaterThanOrEqual { value, .. } => min = min.max(*value as i64),
            ParsedCheck::GreaterThan { value, .. } => min = min.max(*value as i64 + 1),
            ParsedCheck::LessThanOrEqual { value, .. } => max = max.min(*value as i64),
            ParsedCheck::LessThan { value, .. } => max = max.min(*value as i64 - 1),
            _ => {}
        }
    }
    if min > max {
        tracing::warn!(
            "Conflicting integer bounds (min: {}, max: {}). Widening.",
            min,
            max
        );
        max = min + 100;
    }
    (min, max)
}

fn generate_random_alphanumeric(rng: &mut impl Rng, len: usize) -> String {
    const CHARS: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    (0..len)
        .map(|_| CHARS[rng.random_range(0..CHARS.len())] as char)
        .collect()
}

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

    fn test_base_time() -> chrono::NaiveDateTime {
        chrono::NaiveDateTime::new(
            chrono::NaiveDate::from_ymd_opt(2025, 6, 15).unwrap(),
            chrono::NaiveTime::from_hms_opt(12, 0, 0).unwrap(),
        )
    }

    #[test]
    fn test_generate_email() {
        let mut rng = rand::rngs::StdRng::seed_from_u64(42);
        let value = generate_value(SemanticType::Email, &mut rng, 0, &[], test_base_time());
        if let Value::String(s) = value {
            assert!(s.contains('@'));
        } else {
            panic!("Expected string");
        }
    }

    #[test]
    fn test_generate_price_with_constraint() {
        let mut rng = rand::rngs::StdRng::seed_from_u64(42);
        let constraints = vec![ParsedCheck::GreaterThanOrEqual {
            column: "price".to_string(),
            value: 0.0,
        }];
        let value = generate_value(
            SemanticType::Price,
            &mut rng,
            0,
            &constraints,
            test_base_time(),
        );
        if let Value::Float(f) = value {
            assert!(f >= 0.0);
        } else {
            panic!("Expected float");
        }
    }

    #[test]
    fn test_generate_uuid() {
        let mut rng = rand::rngs::StdRng::seed_from_u64(42);
        let value = generate_value(SemanticType::Uuid, &mut rng, 0, &[], test_base_time());
        let Value::Uuid(id) = value else {
            panic!("Expected UUID")
        };
        assert_eq!(id.get_version_num(), 4);
        assert_eq!(id.get_variant(), uuid::Variant::RFC4122);
    }

    #[test]
    fn test_generate_boolean() {
        let mut rng = rand::rngs::StdRng::seed_from_u64(42);
        let value = generate_value(
            SemanticType::BooleanFlag,
            &mut rng,
            0,
            &[],
            test_base_time(),
        );
        assert!(matches!(value, Value::Bool(_)));
    }

    #[test]
    fn test_json_data_is_non_empty() {
        let mut rng = rand::rngs::StdRng::seed_from_u64(42);
        let value = generate_value(SemanticType::JsonData, &mut rng, 0, &[], test_base_time());
        if let Value::Json(j) = value {
            let obj = j.as_object().expect("JsonData should be an object");
            assert!(
                obj.len() >= 2,
                "JsonData should have at least 2 keys, got {}",
                obj.len()
            );
        } else {
            panic!("Expected Json variant");
        }
    }

    #[test]
    fn test_temporal_determinism() {
        let bt = test_base_time();
        let mut rng1 = rand::rngs::StdRng::seed_from_u64(99);
        let mut rng2 = rand::rngs::StdRng::seed_from_u64(99);

        let v1 = generate_value(SemanticType::CreatedAt, &mut rng1, 0, &[], bt);
        let v2 = generate_value(SemanticType::CreatedAt, &mut rng2, 0, &[], bt);
        assert_eq!(
            v1, v2,
            "Same seed + same base_time must produce identical timestamps"
        );
    }
}