drizzle-seed 0.3.1

Deterministic database seeding for drizzle-rs
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
//! Column value generators: the [`Generator`] trait, [`GeneratorKind`], and
//! [`SeedValue`].

pub mod numeric;
pub mod special;
pub mod string;
pub mod temporal;

/// A generated column value, before it is rendered for a dialect.
#[derive(Debug, Clone, PartialEq)]
pub enum SeedValue {
    /// The SQL `DEFAULT` keyword (the column's own default).
    Default,
    /// SQL `NULL`.
    Null,
    /// Signed integer IR. Dialects may bind nonnegative values as unsigned,
    /// but generated values remain limited to `i64::MAX`.
    Integer(i64),
    /// A floating-point number.
    Float(f64),
    /// A string.
    Text(String),
    /// A boolean.
    Bool(bool),
    /// Raw bytes.
    Blob(Vec<u8>),
    /// "Now", rendered as the dialect's current-timestamp expression.
    CurrentTime,
}

/// Produces one column value per row.
///
/// Implement it for custom data and pass it to `SeedConfig::generator`.
/// Use only `rng` for randomness so output stays deterministic.
///
/// # Examples
///
/// ```rust
/// use drizzle_seed::{Generator, RngCore, SeedValue};
///
/// struct Sku;
///
/// impl Generator for Sku {
///     fn generate(&self, _rng: &mut dyn RngCore, index: usize, _sql_type: &str) -> SeedValue {
///         SeedValue::Text(format!("SKU-{:05}", index + 1))
///     }
///
///     fn name(&self) -> &'static str {
///         "Sku"
///     }
/// }
///
/// # use rand::SeedableRng;
/// let mut rng = rand::rngs::StdRng::seed_from_u64(0);
/// assert_eq!(Sku.generate(&mut rng, 0, "TEXT"), SeedValue::Text("SKU-00001".into()));
/// ```
pub trait Generator: Send + Sync {
    /// Returns the value for row `index` (0-based). `sql_type` is the
    /// column's SQL type as declared, e.g. `"INTEGER"` or `"TEXT"`.
    fn generate(&self, rng: &mut dyn RngCore, index: usize, sql_type: &str) -> SeedValue;

    /// Returns a short name for debugging. Defaults to the type name.
    fn name(&self) -> &'static str {
        core::any::type_name::<Self>()
    }
}

impl<G: Generator + ?Sized> Generator for Box<G> {
    fn generate(&self, rng: &mut dyn RngCore, index: usize, sql_type: &str) -> SeedValue {
        (**self).generate(rng, index, sql_type)
    }

    fn name(&self) -> &'static str {
        (**self).name()
    }
}

impl<G: Generator + ?Sized> Generator for std::sync::Arc<G> {
    fn generate(&self, rng: &mut dyn RngCore, index: usize, sql_type: &str) -> SeedValue {
        (**self).generate(rng, index, sql_type)
    }

    fn name(&self) -> &'static str {
        (**self).name()
    }
}

/// A built-in kind is itself a generator, so it can be passed wherever a
/// [`Generator`] is expected.
impl Generator for GeneratorKind {
    fn generate(&self, rng: &mut dyn RngCore, index: usize, sql_type: &str) -> SeedValue {
        self.into_generator().generate(rng, index, sql_type)
    }

    fn name(&self) -> &'static str {
        self.into_generator().name()
    }
}

macro_rules! seed_value_from {
    ($variant:ident: $($ty:ty),*) => {$(
        impl From<$ty> for SeedValue {
            fn from(value: $ty) -> Self {
                Self::$variant(value.into())
            }
        }
    )*};
}

seed_value_from!(Integer: i8, i16, i32, i64, u8, u16, u32);
seed_value_from!(Float: f32, f64);
seed_value_from!(Text: String, &str, char);
seed_value_from!(Bool: bool);
seed_value_from!(Blob: Vec<u8>, &[u8]);

impl<T: Into<SeedValue>> From<Option<T>> for SeedValue {
    /// `None` becomes `NULL`.
    fn from(value: Option<T>) -> Self {
        value.map_or(Self::Null, Into::into)
    }
}

/// Re-export of `rand::RngCore`, the RNG passed to [`Generator::generate`].
pub use rand::RngCore;

/// A built-in generator, chosen by type/name inference or set with
/// `SeedConfig::kind`.
///
/// New kinds may be added in any release, so a `match` on it needs a `_`
/// arm.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum GeneratorKind {
    /// Sequential integers starting at 1 (row index + 1).
    IntPrimaryKey,
    /// Random integer from 0 to 10 000.
    Int,
    /// Random number from 0 up to 10 000, rounded to 2 decimals.
    Float,
    /// Random boolean.
    Bool,
    /// 5 to 50 random lowercase letters.
    Text,
    /// First name from a built-in list.
    FirstName,
    /// Last name from a built-in list.
    LastName,
    /// First and last name.
    FullName,
    /// `first.last{row}@example.com` (or another domain reserved for
    /// testing); the row index keeps emails unique.
    Email,
    /// US-style phone number, `(555) 555-5555`.
    Phone,
    /// City name from a built-in list.
    City,
    /// Country name from a built-in list.
    Country,
    /// Street address, `123 Name Street`.
    Address,
    /// Job title from a built-in list.
    JobTitle,
    /// A short sentence-case phrase, such as a post title: `Dolor sit amet`.
    Title,
    /// `https://` URL on a reserved example domain; the row index keeps
    /// URLs unique.
    Url,
    /// Lowercase `first_last{row}`; the row index keeps usernames unique.
    Username,
    /// URL slug, `dolor-sit-amet-{row}`; the row index keeps slugs unique.
    Slug,
    /// Company name: a last name and a suffix, such as `Smith Inc`.
    Company,
    /// Ten words of lorem ipsum.
    LoremIpsum,
    /// Random UUID v4 as text (`8-4-4-4-12` hex).
    Uuid,
    /// Small JSON object as text.
    Json,
    /// Date between 2000 and 2030 as `YYYY-MM-DD`; for an integer column
    /// type, its Unix milliseconds (UTC midnight) instead.
    Date,
    /// Timestamp between 2000 and 2030 as `YYYY-MM-DD HH:MM:SS`; for an
    /// integer column type, its Unix milliseconds (UTC) instead.
    Timestamp,
    /// Time of day, `HH:MM:SS`.
    Time,
    /// Time of day with a UTC offset, `HH:MM:SS+HH`.
    TimeTz,
    /// `PostgreSQL` interval of 1 to 72 hours, such as `"12 hours"`.
    Interval,
    /// 32 random bytes.
    Blob,
    /// `PostgreSQL` INET
    PgInet,
    /// `PostgreSQL` CIDR
    PgCidr,
    /// `PostgreSQL` MACADDR
    PgMacAddr,
    /// `PostgreSQL` MACADDR8
    PgMacAddr8,
    /// `PostgreSQL` POINT
    PgPoint,
    /// `PostgreSQL` LINE
    PgLine,
    /// `PostgreSQL` LSEG
    PgLseg,
    /// `PostgreSQL` BOX
    PgBox,
    /// `PostgreSQL` PATH
    PgPath,
    /// `PostgreSQL` POLYGON
    PgPolygon,
    /// `PostgreSQL` CIRCLE
    PgCircle,
    /// `PostgreSQL` BIT: 8 random bits.
    PgBit,
    /// `PostgreSQL` VARBIT: 1 to 32 random bits.
    PgVarBit,
    /// `PostgreSQL` array: always the empty array literal `{}`.
    PgArray,
}

impl GeneratorKind {
    /// Returns the generator for this kind.
    #[must_use]
    pub fn into_generator(self) -> Box<dyn Generator> {
        match self {
            Self::IntPrimaryKey => Box::new(numeric::IntPrimaryKeyGen),
            Self::Int => Box::new(numeric::IntGen {
                min: 0,
                max: 10_000,
            }),
            Self::Float => Box::new(numeric::FloatGen {
                min: 0.0,
                max: 10_000.0,
            }),
            Self::Bool => Box::new(numeric::BoolGen),
            Self::Text => Box::new(string::TextGen {
                min_len: 5,
                max_len: 50,
            }),
            Self::FirstName => Box::new(string::FirstNameGen),
            Self::LastName => Box::new(string::LastNameGen),
            Self::FullName => Box::new(string::FullNameGen),
            Self::Email => Box::new(string::EmailGen),
            Self::Phone => Box::new(string::PhoneGen),
            Self::City => Box::new(string::CityGen),
            Self::Country => Box::new(string::CountryGen),
            Self::Address => Box::new(string::AddressGen),
            Self::JobTitle => Box::new(string::JobTitleGen),
            Self::Title => Box::new(string::TitleGen),
            Self::Url => Box::new(string::UrlGen),
            Self::Username => Box::new(string::UsernameGen),
            Self::Slug => Box::new(string::SlugGen),
            Self::Company => Box::new(string::CompanyGen),
            Self::LoremIpsum => Box::new(string::LoremGen { words: 10 }),
            Self::Uuid => Box::new(special::UuidGen),
            Self::Json => Box::new(special::JsonGen),
            Self::Date => Box::new(temporal::DateGen),
            Self::Timestamp => Box::new(temporal::TimestampGen),
            Self::Time => Box::new(temporal::TimeGen),
            Self::TimeTz => Box::new(temporal::TimeTzGen),
            Self::Interval => Box::new(temporal::IntervalGen),
            Self::Blob => Box::new(special::BlobGen { size: 32 }),
            Self::PgInet => Box::new(special::InetGen),
            Self::PgCidr => Box::new(special::CidrGen),
            Self::PgMacAddr => Box::new(special::MacAddrGen),
            Self::PgMacAddr8 => Box::new(special::MacAddr8Gen),
            Self::PgPoint => Box::new(special::PointGen),
            Self::PgLine => Box::new(special::LineGen),
            Self::PgLseg => Box::new(special::LsegGen),
            Self::PgBox => Box::new(special::BoxGen),
            Self::PgPath => Box::new(special::PathGen),
            Self::PgPolygon => Box::new(special::PolygonGen),
            Self::PgCircle => Box::new(special::CircleGen),
            Self::PgBit => Box::new(special::BitGen {
                min_len: 8,
                max_len: 8,
            }),
            Self::PgVarBit => Box::new(special::BitGen {
                min_len: 1,
                max_len: 32,
            }),
            Self::PgArray => Box::new(special::ArrayGen),
        }
    }
}

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

    /// Every GeneratorKind must produce identical output given identical RNG state.
    #[test]
    fn every_kind_is_deterministic() {
        let kinds = [
            GeneratorKind::IntPrimaryKey,
            GeneratorKind::Int,
            GeneratorKind::Float,
            GeneratorKind::Bool,
            GeneratorKind::Text,
            GeneratorKind::FirstName,
            GeneratorKind::LastName,
            GeneratorKind::FullName,
            GeneratorKind::Email,
            GeneratorKind::Phone,
            GeneratorKind::City,
            GeneratorKind::Country,
            GeneratorKind::Address,
            GeneratorKind::JobTitle,
            GeneratorKind::Title,
            GeneratorKind::Url,
            GeneratorKind::Username,
            GeneratorKind::Slug,
            GeneratorKind::Company,
            GeneratorKind::LoremIpsum,
            GeneratorKind::Uuid,
            GeneratorKind::Json,
            GeneratorKind::Date,
            GeneratorKind::Timestamp,
            GeneratorKind::Time,
            GeneratorKind::TimeTz,
            GeneratorKind::Interval,
            GeneratorKind::Blob,
            GeneratorKind::PgInet,
            GeneratorKind::PgCidr,
            GeneratorKind::PgMacAddr,
            GeneratorKind::PgMacAddr8,
            GeneratorKind::PgPoint,
            GeneratorKind::PgLine,
            GeneratorKind::PgLseg,
            GeneratorKind::PgBox,
            GeneratorKind::PgPath,
            GeneratorKind::PgPolygon,
            GeneratorKind::PgCircle,
            GeneratorKind::PgBit,
            GeneratorKind::PgVarBit,
            GeneratorKind::PgArray,
        ];

        for seed in [0u64, 42, 999, u64::MAX] {
            for kind in &kinds {
                let g1 = kind.into_generator();
                let g2 = kind.into_generator();

                // Generate a sequence of 20 values with each RNG
                let seq1: Vec<SeedValue> = (0..20)
                    .map(|i| {
                        let mut rng = StdRng::seed_from_u64(seed.wrapping_add(i as u64));
                        g1.generate(&mut rng, i, "TEXT")
                    })
                    .collect();
                let seq2: Vec<SeedValue> = (0..20)
                    .map(|i| {
                        let mut rng = StdRng::seed_from_u64(seed.wrapping_add(i as u64));
                        g2.generate(&mut rng, i, "TEXT")
                    })
                    .collect();

                assert_eq!(
                    seq1, seq2,
                    "Determinism violation for {:?} with seed {seed}",
                    kind
                );
            }
        }
    }

    /// Date and Timestamp generators must produce identical INTEGER values
    /// when sql_type is INTEGER/BIGINT (SQLite timestamp_ms mode).
    #[test]
    fn date_timestamp_deterministic_for_integer_columns() {
        for sql_type in ["INTEGER", "BIGINT"] {
            for seed in [0u64, 42, 12345] {
                let date_seq1: Vec<SeedValue> = (0..50)
                    .map(|i| {
                        let mut rng = StdRng::seed_from_u64(seed.wrapping_add(i as u64));
                        temporal::DateGen.generate(&mut rng, i, sql_type)
                    })
                    .collect();
                let date_seq2: Vec<SeedValue> = (0..50)
                    .map(|i| {
                        let mut rng = StdRng::seed_from_u64(seed.wrapping_add(i as u64));
                        temporal::DateGen.generate(&mut rng, i, sql_type)
                    })
                    .collect();
                assert_eq!(
                    date_seq1, date_seq2,
                    "DateGen not deterministic for {sql_type} seed={seed}"
                );
                // Verify they're actually integers
                assert!(
                    matches!(date_seq1[0], SeedValue::Integer(_)),
                    "DateGen should produce Integer for {sql_type}"
                );

                let ts_seq1: Vec<SeedValue> = (0..50)
                    .map(|i| {
                        let mut rng = StdRng::seed_from_u64(seed.wrapping_add(i as u64));
                        temporal::TimestampGen.generate(&mut rng, i, sql_type)
                    })
                    .collect();
                let ts_seq2: Vec<SeedValue> = (0..50)
                    .map(|i| {
                        let mut rng = StdRng::seed_from_u64(seed.wrapping_add(i as u64));
                        temporal::TimestampGen.generate(&mut rng, i, sql_type)
                    })
                    .collect();
                assert_eq!(
                    ts_seq1, ts_seq2,
                    "TimestampGen not deterministic for {sql_type} seed={seed}"
                );
                assert!(
                    matches!(ts_seq1[0], SeedValue::Integer(_)),
                    "TimestampGen should produce Integer for {sql_type}"
                );
            }
        }
    }

    /// Different seeds must produce different sequences (no degenerate RNG).
    #[test]
    fn different_seeds_produce_different_output() {
        let kinds = [
            GeneratorKind::Int,
            GeneratorKind::Text,
            GeneratorKind::Email,
            GeneratorKind::Date,
            GeneratorKind::Timestamp,
            GeneratorKind::Uuid,
        ];

        for kind in &kinds {
            let g = kind.into_generator();
            let mut rng_a = StdRng::seed_from_u64(1);
            let mut rng_b = StdRng::seed_from_u64(2);

            let seq_a: Vec<SeedValue> =
                (0..10).map(|i| g.generate(&mut rng_a, i, "TEXT")).collect();
            let seq_b: Vec<SeedValue> =
                (0..10).map(|i| g.generate(&mut rng_b, i, "TEXT")).collect();

            assert_ne!(
                seq_a, seq_b,
                "{:?} produced identical output for different seeds",
                kind
            );
        }
    }

    /// A continuous RNG stream must be deterministic (same seed, shared RNG across rows).
    #[test]
    fn continuous_rng_stream_is_deterministic() {
        let kinds = [
            GeneratorKind::Int,
            GeneratorKind::Float,
            GeneratorKind::Text,
            GeneratorKind::Email,
            GeneratorKind::Date,
            GeneratorKind::Timestamp,
        ];

        for kind in &kinds {
            let g1 = kind.into_generator();
            let g2 = kind.into_generator();
            let mut rng1 = StdRng::seed_from_u64(42);
            let mut rng2 = StdRng::seed_from_u64(42);

            for i in 0..100 {
                assert_eq!(
                    g1.generate(&mut rng1, i, "TEXT"),
                    g2.generate(&mut rng2, i, "TEXT"),
                    "Stream diverged at row {i} for {:?}",
                    kind
                );
            }
        }
    }
}