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
//! # Prompt Templates
//!
//! Builds structured prompts for LLM-based schema analysis. The prompt
//! includes a compact DDL representation of the database schema and
//! requests a JSON classification response.

use crate::schema::types::DatabaseSchema;

/// Semantic types a classifier may return, spelled as `SemanticType` deserializes them.
pub const SEMANTIC_TYPE_NAMES: &[&str] = &[
    "FirstName",
    "LastName",
    "FullName",
    "Username",
    "DisplayName",
    "Email",
    "Phone",
    "PhoneCountryCode",
    "StreetAddress",
    "City",
    "State",
    "ZipCode",
    "PostalCode",
    "Country",
    "CountryCode",
    "Latitude",
    "Longitude",
    "CompanyName",
    "JobTitle",
    "Department",
    "Industry",
    "Url",
    "DomainName",
    "IpAddress",
    "MacAddress",
    "UserAgent",
    "Slug",
    "Title",
    "Description",
    "Bio",
    "Paragraph",
    "Sentence",
    "HtmlContent",
    "MarkdownContent",
    "ImageUrl",
    "AvatarUrl",
    "ThumbnailUrl",
    "FileUrl",
    "FileName",
    "MimeType",
    "FileSize",
    "Price",
    "Currency",
    "CurrencyCode",
    "Amount",
    "Percentage",
    "CreatedAt",
    "UpdatedAt",
    "DeletedAt",
    "StartDate",
    "EndDate",
    "BirthDate",
    "DateOnly",
    "TimeOnly",
    "Timestamp",
    "PasswordHash",
    "Token",
    "ApiKey",
    "SecretKey",
    "Uuid",
    "AutoIncrement",
    "ExternalId",
    "Sku",
    "OrderNumber",
    "InvoiceNumber",
    "TrackingNumber",
    "Status",
    "Role",
    "Priority",
    "Category",
    "Tag",
    "BooleanFlag",
    "EnumValue",
    "Quantity",
    "Rating",
    "Score",
    "Weight",
    "Height",
    "Age",
    "Duration",
    "SortOrder",
    "JsonData",
    "Color",
    "HexColor",
    "Locale",
    "Timezone",
    "Unknown",
];

/// A column the rule-based classifier could not place.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClassificationTarget {
    pub table: String,
    pub column: String,
    pub sql_type: String,
}

impl ClassificationTarget {
    pub fn new(table: &str, column: &str, sql_type: &str) -> Self {
        Self {
            table: table.to_owned(),
            column: column.to_owned(),
            sql_type: sql_type.to_owned(),
        }
    }
}

/// Ask for the semantic type of each target column.
///
/// The schema comes first, then the exact columns to classify. An earlier
/// prompt put the schema last and asked the model to skip "obvious" columns;
/// it sometimes returned a single placeholder row instead of classifying.
pub fn classification_prompt(ddl: &str, targets: &[ClassificationTarget]) -> String {
    let listed: String = targets
        .iter()
        .map(|t| format!("- {}.{} ({})\n", t.table, t.column, t.sql_type))
        .collect();
    format!(
        r#"<schema>
{ddl}
</schema>

SeedKit generates realistic test data for the database schema above. Its name-based rules could not tell what kind of value these columns hold:

{listed}
For each listed column, choose the semantic type that best describes the values it stores. Use the table, the column name, its SQL type, and neighboring columns as evidence. Choose from: {types}. Use Unknown when no type fits.

Give each choice a confidence from 0.0 to 1.0, and return one entry per listed column in this form:
{{"classifications": [
  {{"table": "users", "column": "display_name", "semantic_type": "FullName", "confidence": 0.8}}
]}}"#,
        ddl = ddl.trim(),
        types = SEMANTIC_TYPE_NAMES.join(", "),
    )
}

/// JSON schema of the classification response. With `enumerate_types`, the
/// schema lists every semantic type, so providers that enforce it can only
/// return known variants. Gemini rejects an enum this large.
pub fn classification_schema(enumerate_types: bool) -> serde_json::Value {
    let mut schema = serde_json::json!({
        "type": "object",
        "properties": {
            "classifications": {
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": {
                        "table": {"type": "string"},
                        "column": {"type": "string"},
                        "semantic_type": {"type": "string", "enum": SEMANTIC_TYPE_NAMES},
                        "confidence": {"type": "number"}
                    },
                    "required": ["table", "column", "semantic_type", "confidence"],
                    "additionalProperties": false
                }
            }
        },
        "required": ["classifications"],
        "additionalProperties": false
    });
    if !enumerate_types {
        let semantic_type =
            &mut schema["properties"]["classifications"]["items"]["properties"]["semantic_type"];
        semantic_type
            .as_object_mut()
            .expect("semantic_type is an object")
            .remove("enum");
    }
    schema
}

/// Build a compact DDL representation from an introspected schema.
///
/// Produces a CREATE TABLE-style summary that includes column names, types,
/// nullability, primary keys, and foreign keys — enough for the LLM to
/// classify columns without needing the full raw DDL.
pub fn schema_to_compact_ddl(schema: &DatabaseSchema) -> String {
    let mut ddl = String::new();

    for (table_name, table) in &schema.tables {
        ddl.push_str(&format!("CREATE TABLE {} (\n", table_name));

        let mut col_lines = Vec::new();
        for (col_name, column) in &table.columns {
            let mut line = format!("  {} {}", col_name, column.raw_type);
            if !column.nullable {
                line.push_str(" NOT NULL");
            }
            if column.is_auto_increment {
                line.push_str(" AUTO_INCREMENT");
            }
            if column.has_default {
                line.push_str(" DEFAULT ...");
            }
            if let Some(ref vals) = column.enum_values {
                line.push_str(&format!(" /* ENUM: {} */", vals.join(", ")));
            }
            col_lines.push(line);
        }

        if let Some(pk) = &table.primary_key {
            col_lines.push(format!("  PRIMARY KEY ({})", pk.columns.join(", ")));
        }

        for fk in &table.foreign_keys {
            col_lines.push(format!(
                "  FOREIGN KEY ({}) REFERENCES {}({})",
                fk.source_columns.join(", "),
                fk.target_name(),
                fk.referenced_columns.join(", "),
            ));
        }

        for ck in &table.check_constraints {
            col_lines.push(format!("  CHECK ({})", ck.expression));
        }

        ddl.push_str(&col_lines.join(",\n"));
        ddl.push_str("\n);\n\n");
    }

    ddl
}

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

    #[test]
    fn test_classification_prompt_contains_ddl() {
        let prompt = classification_prompt("CREATE TABLE users (id SERIAL PRIMARY KEY);", &[]);
        assert!(prompt.contains("CREATE TABLE users"));
        assert!(prompt.contains("semantic_type"));
        assert!(prompt.contains(r#"{"classifications": ["#));
    }

    #[test]
    fn every_listed_semantic_type_deserializes() {
        use crate::classify::semantic::SemanticType;
        for name in SEMANTIC_TYPE_NAMES {
            let parsed = serde_json::from_value::<SemanticType>(serde_json::json!(name));
            assert!(parsed.is_ok(), "{name} is not a SemanticType");
        }
        assert!(SEMANTIC_TYPE_NAMES.contains(&"Unknown"));
    }

    #[test]
    fn response_schema_constrains_every_field() {
        let schema = classification_schema(true);
        let item = &schema["properties"]["classifications"]["items"];
        assert_eq!(schema["additionalProperties"], false);
        assert_eq!(item["additionalProperties"], false);
        assert_eq!(
            item["required"],
            serde_json::json!(["table", "column", "semantic_type", "confidence"])
        );
        let labels = item["properties"]["semantic_type"]["enum"]
            .as_array()
            .unwrap();
        assert_eq!(labels.len(), SEMANTIC_TYPE_NAMES.len());
    }

    #[test]
    fn test_classification_prompt_lists_semantic_types() {
        let prompt = classification_prompt("", &[]);
        assert!(prompt.contains("FirstName"));
        assert!(prompt.contains("Email"));
        assert!(prompt.contains("PasswordHash"));
        assert!(prompt.contains("Unknown"));
    }

    #[test]
    fn test_schema_to_compact_ddl() {
        let mut schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());
        let mut table = Table::new("users".to_string());

        let mut id_col = Column::new("id".to_string(), DataType::Integer, "serial".to_string());
        id_col.is_auto_increment = true;
        table.columns.insert("id".to_string(), id_col);

        let mut name_col = Column::new(
            "name".to_string(),
            DataType::VarChar,
            "varchar(255)".to_string(),
        );
        name_col.nullable = false;
        table.columns.insert("name".to_string(), name_col);

        let mut bio_col = Column::new("bio".to_string(), DataType::Text, "text".to_string());
        bio_col.nullable = true;
        table.columns.insert("bio".to_string(), bio_col);

        table.primary_key = Some(PrimaryKey {
            columns: vec!["id".to_string()],
            name: None,
        });

        schema.tables.insert("users".to_string(), table);

        let ddl = schema_to_compact_ddl(&schema);

        assert!(ddl.contains("CREATE TABLE users"));
        assert!(ddl.contains("id serial"));
        assert!(ddl.contains("AUTO_INCREMENT"));
        assert!(ddl.contains("name varchar(255) NOT NULL"));
        assert!(ddl.contains("bio text"));
        assert!(ddl.contains("PRIMARY KEY (id)"));
    }

    #[test]
    fn test_compact_ddl_includes_foreign_keys() {
        let mut schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());

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

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

        let ddl = schema_to_compact_ddl(&schema);
        assert!(ddl.contains("FOREIGN KEY (user_id) REFERENCES users(id)"));
    }

    // --- Fix 1: Enum values and check constraints in DDL ---

    #[test]
    fn test_compact_ddl_includes_enum_values() {
        let mut schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());
        let mut table = Table::new("users".to_string());

        let mut status_col = Column::new(
            "status".to_string(),
            DataType::VarChar,
            "varchar(50)".to_string(),
        );
        status_col.nullable = false;
        status_col.enum_values = Some(vec![
            "active".to_string(),
            "suspended".to_string(),
            "banned".to_string(),
        ]);
        table.columns.insert("status".to_string(), status_col);

        schema.tables.insert("users".to_string(), table);

        let ddl = schema_to_compact_ddl(&schema);
        assert!(
            ddl.contains("ENUM: active, suspended, banned"),
            "DDL should contain enum values: {}",
            ddl
        );
    }

    #[test]
    fn test_compact_ddl_includes_check_constraints() {
        let mut schema = DatabaseSchema::new(DatabaseType::PostgreSQL, "test".to_string());
        let mut table = Table::new("products".to_string());

        let mut price_col = Column::new(
            "price".to_string(),
            DataType::Numeric,
            "numeric(10,2)".to_string(),
        );
        price_col.nullable = false;
        table.columns.insert("price".to_string(), price_col);

        table.check_constraints.push(CheckConstraint {
            name: Some("products_price_check".to_string()),
            expression: "price >= 0".to_string(),
            parsed: None,
        });

        schema.tables.insert("products".to_string(), table);

        let ddl = schema_to_compact_ddl(&schema);
        assert!(
            ddl.contains("CHECK (price >= 0)"),
            "DDL should contain check constraint: {}",
            ddl
        );
    }

    // --- Explicit targets ---

    #[test]
    fn prompt_puts_the_schema_first_and_lists_each_target_column() {
        let targets = [
            ClassificationTarget::new("products", "margin", "REAL"),
            ClassificationTarget::new("shipments", "kg", "REAL"),
        ];
        let prompt = classification_prompt("CREATE TABLE products (margin REAL);", &targets);
        // Claude follows a long input more reliably when the data comes first.
        assert!(prompt.starts_with("<schema>\nCREATE TABLE products (margin REAL);\n</schema>"));
        assert!(prompt.contains("\n- products.margin (REAL)\n- shipments.kg (REAL)\n"));
        // An open-ended "skip obvious columns" instruction let the model return
        // a placeholder row instead of classifying anything.
        assert!(!prompt.contains("skip"));
    }

    // --- Fix 3: Few-shot example ---

    #[test]
    fn test_prompt_contains_few_shot_example() {
        let prompt = classification_prompt("", &[]);
        // Should contain a concrete JSON example to prevent hallucination
        assert!(
            prompt.contains("\"table\""),
            "Prompt should have example with table key"
        );
        assert!(
            prompt.contains("\"semantic_type\""),
            "Prompt should have example with semantic_type key"
        );
        assert!(
            prompt.contains("\"confidence\""),
            "Prompt should have example with confidence key"
        );
        // The example should use real SemanticType variants
        assert!(
            prompt.contains("FullName") || prompt.contains("Percentage"),
            "Example should use real SemanticType variants"
        );
    }
}