use crate::schema::types::DatabaseSchema;
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",
];
#[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(),
}
}
}
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(", "),
)
}
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
}
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)"));
}
#[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
);
}
#[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);
assert!(prompt.starts_with("<schema>\nCREATE TABLE products (margin REAL);\n</schema>"));
assert!(prompt.contains("\n- products.margin (REAL)\n- shipments.kg (REAL)\n"));
assert!(!prompt.contains("skip"));
}
#[test]
fn test_prompt_contains_few_shot_example() {
let prompt = classification_prompt("", &[]);
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"
);
assert!(
prompt.contains("FullName") || prompt.contains("Percentage"),
"Example should use real SemanticType variants"
);
}
}