Skip to main content

sql_splitter/synthetic/
schema.rs

1//! Dialect-agnostic, serializable schema types for synthetic data generation.
2
3use crate::parser::SqlDialect;
4use crate::schema::{Column, Schema, TableSchema};
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7use std::collections::BTreeMap;
8
9/// Coarse-grained classification of a SQL column type, independent of the
10/// source dialect's exact type name. Generation strategies key off this
11/// instead of re-deriving it from `source_type`.
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
13#[serde(rename_all = "snake_case")]
14pub enum SqlTypeFamily {
15    Integer,
16    BigInteger,
17    Decimal,
18    Boolean,
19    Text,
20    Bytes,
21    Uuid,
22    DateTime,
23    Json,
24    Other,
25}
26
27impl SqlTypeFamily {
28    /// Classify a runtime [`crate::schema::ColumnType`], falling back to
29    /// sniffing `source_type` for the dialect-specific types (JSON, binary)
30    /// that `ColumnType` collapses into `Other`.
31    fn from_column(column: &Column) -> Self {
32        use crate::schema::ColumnType;
33
34        match &column.col_type {
35            ColumnType::Int => SqlTypeFamily::Integer,
36            ColumnType::BigInt => SqlTypeFamily::BigInteger,
37            ColumnType::Decimal => SqlTypeFamily::Decimal,
38            ColumnType::Bool => SqlTypeFamily::Boolean,
39            ColumnType::Text => SqlTypeFamily::Text,
40            ColumnType::Uuid => SqlTypeFamily::Uuid,
41            ColumnType::DateTime => SqlTypeFamily::DateTime,
42            ColumnType::Other(_) => Self::from_unclassified_source_type(&column.source_type),
43        }
44    }
45
46    /// Classify a raw SQL type name (e.g. `"bigint"`, `"varchar(255)"`)
47    /// using the same coarse mapping as [`Self::from_column`], for callers
48    /// that only have a type name and not a fully parsed [`Column`] — namely
49    /// the hand-authored `type:` shorthand accepted by [`PortableColumn`].
50    fn from_source_type(source_type: &str) -> Self {
51        use crate::schema::ColumnType;
52
53        match ColumnType::from_sql_type(source_type) {
54            ColumnType::Int => SqlTypeFamily::Integer,
55            ColumnType::BigInt => SqlTypeFamily::BigInteger,
56            ColumnType::Decimal => SqlTypeFamily::Decimal,
57            ColumnType::Bool => SqlTypeFamily::Boolean,
58            ColumnType::Text => SqlTypeFamily::Text,
59            ColumnType::Uuid => SqlTypeFamily::Uuid,
60            ColumnType::DateTime => SqlTypeFamily::DateTime,
61            ColumnType::Other(_) => Self::from_unclassified_source_type(source_type),
62        }
63    }
64
65    /// Shared JSON/blob sniffing for the `ColumnType::Other` fallback,
66    /// used by both [`Self::from_column`] and [`Self::from_source_type`].
67    fn from_unclassified_source_type(source_type: &str) -> Self {
68        let lower = source_type.to_lowercase();
69        if lower.contains("json") {
70            SqlTypeFamily::Json
71        } else if lower.contains("blob") || lower.contains("binary") || lower.contains("bytea") {
72            SqlTypeFamily::Bytes
73        } else {
74            SqlTypeFamily::Other
75        }
76    }
77}
78
79/// Portable column: everything a generation strategy needs to know about a
80/// single column, independent of the source SQL dialect.
81///
82/// Deserialization accepts a concise hand-authored shorthand: `type:` as an
83/// alias for `source_type`, with `family` derived automatically when it is
84/// absent (see [`PortableColumnInput`]). Serialization always emits the
85/// canonical `source_type` + `family` fields; `--emit-config` never writes
86/// the `type:` shorthand.
87#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
88#[serde(try_from = "PortableColumnInput")]
89pub struct PortableColumn {
90    pub name: String,
91    pub source_type: String,
92    pub family: SqlTypeFamily,
93    pub nullable: bool,
94    #[serde(default)]
95    pub primary_key: bool,
96    #[serde(default)]
97    pub unique: bool,
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub default_sql: Option<String>,
100    #[serde(default)]
101    pub generated: bool,
102    #[serde(default)]
103    pub identity: bool,
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub collation: Option<String>,
106}
107
108/// Manual schema: `#[serde(try_from = "PortableColumnInput")]` means the
109/// derive macro would describe `PortableColumn`'s own fields (which always
110/// require `source_type` + `family`), not what YAML actually accepts. This
111/// impl instead mirrors [`PortableColumnInput`]: `family` is optional, and
112/// either `source_type` or its `type` shorthand alias may supply the type
113/// name (see D1 in the module tests below).
114impl JsonSchema for PortableColumn {
115    fn schema_name() -> std::borrow::Cow<'static, str> {
116        "PortableColumn".into()
117    }
118
119    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
120        let family_schema = generator.subschema_for::<SqlTypeFamily>();
121        schemars::json_schema!({
122            "type": "object",
123            "properties": {
124                "name": { "type": "string" },
125                "source_type": { "type": "string" },
126                "type": {
127                    "type": "string",
128                    "description": "Shorthand alias for `source_type`; `family` is derived automatically when omitted."
129                },
130                "family": family_schema,
131                "nullable": { "type": "boolean" },
132                "primary_key": { "type": "boolean" },
133                "unique": { "type": "boolean" },
134                "default_sql": { "type": ["string", "null"] },
135                "generated": { "type": "boolean" },
136                "identity": { "type": "boolean" },
137                "collation": { "type": ["string", "null"] }
138            },
139            "required": ["name", "nullable"],
140            "anyOf": [
141                { "required": ["source_type"] },
142                { "required": ["type"] }
143            ],
144            "additionalProperties": false
145        })
146    }
147}
148
149impl PortableColumn {
150    fn from_runtime(column: &Column) -> Self {
151        Self {
152            name: column.name.clone(),
153            source_type: column.source_type.clone(),
154            family: SqlTypeFamily::from_column(column),
155            nullable: column.is_nullable,
156            primary_key: column.is_primary_key,
157            unique: column.is_unique,
158            default_sql: column.default_sql.clone(),
159            generated: column.is_generated,
160            identity: column.is_identity,
161            collation: column.collation.clone(),
162        }
163    }
164}
165
166/// The input-only shape [`PortableColumn`] deserializes through: `type:` is
167/// accepted as an alias for `source_type`, and `family` is optional, derived
168/// from `source_type` via [`SqlTypeFamily::from_source_type`] when absent.
169/// `#[serde(deny_unknown_fields)]` lives here, not on `PortableColumn`
170/// itself, since this shadow struct is what actually parses YAML keys.
171#[derive(Debug, Deserialize)]
172#[serde(deny_unknown_fields)]
173struct PortableColumnInput {
174    name: String,
175    #[serde(alias = "type")]
176    source_type: String,
177    #[serde(default)]
178    family: Option<SqlTypeFamily>,
179    nullable: bool,
180    #[serde(default)]
181    primary_key: bool,
182    #[serde(default)]
183    unique: bool,
184    #[serde(default)]
185    default_sql: Option<String>,
186    #[serde(default)]
187    generated: bool,
188    #[serde(default)]
189    identity: bool,
190    #[serde(default)]
191    collation: Option<String>,
192}
193
194impl From<PortableColumnInput> for PortableColumn {
195    fn from(input: PortableColumnInput) -> Self {
196        let family = input
197            .family
198            .unwrap_or_else(|| SqlTypeFamily::from_source_type(&input.source_type));
199        Self {
200            name: input.name,
201            source_type: input.source_type,
202            family,
203            nullable: input.nullable,
204            primary_key: input.primary_key,
205            unique: input.unique,
206            default_sql: input.default_sql,
207            generated: input.generated,
208            identity: input.identity,
209            collation: input.collation,
210        }
211    }
212}
213
214/// A table-level UNIQUE constraint, covering one or more columns.
215#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
216#[serde(deny_unknown_fields)]
217pub struct PortableUniqueConstraint {
218    #[serde(default, skip_serializing_if = "Option::is_none")]
219    pub name: Option<String>,
220    pub columns: Vec<String>,
221}
222
223/// A CHECK constraint, with its raw SQL expression preserved verbatim.
224#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
225#[serde(deny_unknown_fields)]
226pub struct PortableCheckConstraint {
227    #[serde(default, skip_serializing_if = "Option::is_none")]
228    pub name: Option<String>,
229    pub expression: String,
230}
231
232/// An index definition (not necessarily unique; see
233/// [`PortableUniqueConstraint`] for UNIQUE constraints).
234#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
235#[serde(deny_unknown_fields)]
236pub struct PortableIndex {
237    pub name: String,
238    pub columns: Vec<String>,
239    #[serde(default)]
240    pub unique: bool,
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub index_type: Option<String>,
243}
244
245/// A declared foreign-key relationship to another table, by name (not
246/// resolved to an ID, since a `PortableSchema` stands alone from the
247/// `Schema` it was built from).
248#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
249#[serde(deny_unknown_fields)]
250pub struct PortableRelationship {
251    #[serde(default, skip_serializing_if = "Option::is_none")]
252    pub name: Option<String>,
253    pub columns: Vec<String>,
254    pub referenced_table: String,
255    pub referenced_columns: Vec<String>,
256}
257
258/// Portable table: ordered columns and constraints, plus the raw same-dialect
259/// DDL for reference. Column and constraint order is preserved in `Vec`s;
260/// only table name lookup uses a `BTreeMap` (see [`PortableSchema::tables`]).
261#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
262#[serde(deny_unknown_fields)]
263pub struct PortableTable {
264    pub name: String,
265    pub columns: Vec<PortableColumn>,
266    #[serde(default)]
267    pub primary_key: Vec<String>,
268    #[serde(default)]
269    pub unique_constraints: Vec<PortableUniqueConstraint>,
270    #[serde(default)]
271    pub check_constraints: Vec<PortableCheckConstraint>,
272    #[serde(default)]
273    pub indexes: Vec<PortableIndex>,
274    #[serde(default, skip_serializing_if = "Option::is_none")]
275    pub create_statement: Option<String>,
276    #[serde(default)]
277    pub relationships: Vec<PortableRelationship>,
278}
279
280impl PortableTable {
281    fn from_runtime(table: &TableSchema) -> Self {
282        let columns: Vec<PortableColumn> = table
283            .columns
284            .iter()
285            .map(PortableColumn::from_runtime)
286            .collect();
287
288        let primary_key = table
289            .primary_key
290            .iter()
291            .filter_map(|&id| table.column(id))
292            .map(|c| c.name.clone())
293            .collect();
294
295        let unique_constraints = table
296            .unique_constraints
297            .iter()
298            .map(|uc| PortableUniqueConstraint {
299                name: uc.name.clone(),
300                columns: uc.columns.clone(),
301            })
302            .collect();
303
304        let check_constraints = table
305            .check_constraints
306            .iter()
307            .map(|cc| PortableCheckConstraint {
308                name: cc.name.clone(),
309                expression: cc.expression.clone(),
310            })
311            .collect();
312
313        let indexes = table
314            .indexes
315            .iter()
316            .map(|idx| PortableIndex {
317                name: idx.name.clone(),
318                columns: idx.columns.clone(),
319                unique: idx.is_unique,
320                index_type: idx.index_type.clone(),
321            })
322            .collect();
323
324        let relationships = table
325            .foreign_keys
326            .iter()
327            .map(|fk| PortableRelationship {
328                name: fk.name.clone(),
329                columns: fk.column_names.clone(),
330                referenced_table: fk.referenced_table.clone(),
331                referenced_columns: fk.referenced_columns.clone(),
332            })
333            .collect();
334
335        Self {
336            name: table.name.clone(),
337            columns,
338            primary_key,
339            unique_constraints,
340            check_constraints,
341            indexes,
342            create_statement: table.create_statement.clone(),
343            relationships,
344        }
345    }
346}
347
348/// Dialect-agnostic snapshot of a full database schema, suitable for
349/// serialization and for driving synthetic data generation without
350/// depending on the DDL parser internals.
351#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
352#[serde(deny_unknown_fields)]
353pub struct PortableSchema {
354    /// The dialect the source DDL was parsed with (e.g. `"mysql"`).
355    pub dialect: String,
356    /// Tables keyed by name for lookup; use each table's own `Vec` fields
357    /// when order matters (declaration order is not implied by map order).
358    pub tables: BTreeMap<String, PortableTable>,
359}
360
361impl PortableSchema {
362    /// Build a portable snapshot from a parsed runtime [`Schema`].
363    pub fn from_runtime(schema: &Schema, dialect: SqlDialect) -> Self {
364        let tables = schema
365            .iter()
366            .map(|table| (table.name.clone(), PortableTable::from_runtime(table)))
367            .collect();
368
369        Self {
370            dialect: dialect.to_string(),
371            tables,
372        }
373    }
374}
375
376#[cfg(test)]
377mod tests {
378    use super::*;
379
380    /// Design decision D1: hand-authored column entries may use a concise
381    /// `type:` shorthand for `source_type`, with `family` derived
382    /// automatically. `--emit-config` never emits this shorthand; see
383    /// `portable_column_canonical_form_round_trips` for the emitted shape.
384    #[test]
385    fn portable_column_accepts_type_shorthand_and_derives_family() {
386        let yaml = "{ name: id, type: bigint, nullable: false, primary_key: true }";
387        let column: PortableColumn = serde_yaml_ng::from_str(yaml).unwrap();
388        assert_eq!(column.source_type, "bigint");
389        assert_eq!(column.family, SqlTypeFamily::BigInteger);
390        assert!(column.primary_key);
391    }
392
393    #[test]
394    fn portable_column_canonical_form_round_trips() {
395        let column = PortableColumn {
396            name: "id".to_string(),
397            source_type: "bigint".to_string(),
398            family: SqlTypeFamily::BigInteger,
399            nullable: false,
400            primary_key: true,
401            unique: false,
402            default_sql: None,
403            generated: false,
404            identity: false,
405            collation: None,
406        };
407
408        let rendered = serde_yaml_ng::to_string(&column).unwrap();
409        assert!(rendered.contains("source_type: bigint"));
410        assert!(rendered.contains("family: big_integer"));
411        assert!(!rendered.contains("\ntype:"));
412
413        let reparsed: PortableColumn = serde_yaml_ng::from_str(&rendered).unwrap();
414        assert_eq!(reparsed, column);
415    }
416
417    #[test]
418    fn portable_column_rejects_unknown_fields_even_with_shorthand() {
419        let yaml = "{ name: id, type: bigint, nullable: false, bogus: true }";
420        let err = serde_yaml_ng::from_str::<PortableColumn>(yaml).unwrap_err();
421        assert!(err.to_string().contains("unknown field"));
422    }
423}