1use crate::parser::SqlDialect;
4use crate::schema::{Column, Schema, TableSchema};
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7use std::collections::BTreeMap;
8
9#[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 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 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 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#[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
108impl 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#[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#[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#[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#[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#[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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
352#[serde(deny_unknown_fields)]
353pub struct PortableSchema {
354 pub dialect: String,
356 pub tables: BTreeMap<String, PortableTable>,
359}
360
361impl PortableSchema {
362 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 #[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}