1use crate::parser::SqlDialect;
4use crate::schema::{Column, Schema, TableSchema};
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7use std::collections::BTreeMap;
8
9pub(crate) const MAX_GENERATED_DECIMAL_SCALE: u32 = 18;
11
12pub(crate) fn declared_character_length(source_type: &str) -> Option<usize> {
17 let open = source_type.find('(')?;
18 let close = source_type[open + 1..].find(')')? + open + 1;
19 let type_name = source_type[..open]
20 .trim()
21 .trim_matches(['[', ']'])
22 .to_ascii_lowercase();
23 if !matches!(
24 type_name.as_str(),
25 "char"
26 | "varchar"
27 | "nchar"
28 | "nvarchar"
29 | "character"
30 | "character varying"
31 | "national char"
32 | "national character"
33 | "national character varying"
34 | "bpchar"
35 ) {
36 return None;
37 }
38 source_type[open + 1..close].trim().parse().ok()
39}
40
41pub(crate) fn declared_integer_bounds(
47 source_type: &str,
48 dialect: Option<SqlDialect>,
49) -> Option<(i128, i128)> {
50 let lower = source_type.trim().to_ascii_lowercase();
51 let type_name = lower.split(['(', ' ', '[']).find(|part| !part.is_empty())?;
52 let unsigned = lower.split_whitespace().any(|part| part == "unsigned");
53 let signed = match type_name {
54 "tinyint" if unsigned => (i8::MIN as i128, i8::MAX as i128, u8::MAX as i128),
55 "tinyint" => match dialect {
56 Some(SqlDialect::MySql) => (i8::MIN as i128, i8::MAX as i128, u8::MAX as i128),
57 Some(SqlDialect::Mssql) => (0, u8::MAX as i128, u8::MAX as i128),
58 Some(SqlDialect::Postgres | SqlDialect::Sqlite) | None => return None,
59 },
60 "smallint" | "int2" | "smallserial" => {
61 (i16::MIN as i128, i16::MAX as i128, u16::MAX as i128)
62 }
63 "mediumint" => (-8_388_608, 8_388_607, 16_777_215),
64 "int" | "integer" | "int4" | "serial" => {
65 (i32::MIN as i128, i32::MAX as i128, u32::MAX as i128)
66 }
67 "bigint" | "int8" | "bigserial" => (i64::MIN as i128, i64::MAX as i128, u64::MAX as i128),
68 _ => return None,
69 };
70 Some(if unsigned {
71 (0, signed.2)
72 } else {
73 (signed.0, signed.1)
74 })
75}
76
77pub(crate) fn conservative_integer_generation_bounds(source_type: &str) -> Option<(i128, i128)> {
80 declared_integer_bounds(source_type, None).or_else(|| {
81 let lower = source_type.trim().to_ascii_lowercase();
82 let type_name = lower.split(['(', ' ', '[']).find(|part| !part.is_empty())?;
83 (type_name == "tinyint").then_some((0, i8::MAX as i128))
84 })
85}
86
87pub(crate) fn declared_decimal_shape(source_type: &str) -> Option<(u32, u32)> {
89 let open = source_type.find('(')?;
90 let close = source_type[open + 1..].find(')')? + open + 1;
91 let type_name = source_type[..open].trim().to_ascii_lowercase();
92 if !matches!(type_name.as_str(), "decimal" | "numeric" | "dec" | "fixed") {
93 return None;
94 }
95 let mut parts = source_type[open + 1..close].split(',').map(str::trim);
96 let precision = parts.next()?.parse().ok()?;
97 let scale = parts.next().unwrap_or("0").parse().ok()?;
98 (scale <= precision).then_some((precision, scale))
99}
100
101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
105#[serde(rename_all = "snake_case")]
106pub enum SqlTypeFamily {
107 Integer,
108 BigInteger,
109 Decimal,
110 Boolean,
111 Text,
112 Bytes,
113 Uuid,
114 DateTime,
115 Json,
116 Other,
117}
118
119impl SqlTypeFamily {
120 fn from_column(column: &Column) -> Self {
124 use crate::schema::ColumnType;
125
126 match &column.col_type {
127 ColumnType::Int => SqlTypeFamily::Integer,
128 ColumnType::BigInt => SqlTypeFamily::BigInteger,
129 ColumnType::Decimal => SqlTypeFamily::Decimal,
130 ColumnType::Bool => SqlTypeFamily::Boolean,
131 ColumnType::Text => SqlTypeFamily::Text,
132 ColumnType::Uuid => SqlTypeFamily::Uuid,
133 ColumnType::DateTime => SqlTypeFamily::DateTime,
134 ColumnType::Other(_) => Self::from_unclassified_source_type(&column.source_type),
135 }
136 }
137
138 fn from_source_type(source_type: &str) -> Self {
143 use crate::schema::ColumnType;
144
145 match ColumnType::from_sql_type(source_type) {
146 ColumnType::Int => SqlTypeFamily::Integer,
147 ColumnType::BigInt => SqlTypeFamily::BigInteger,
148 ColumnType::Decimal => SqlTypeFamily::Decimal,
149 ColumnType::Bool => SqlTypeFamily::Boolean,
150 ColumnType::Text => SqlTypeFamily::Text,
151 ColumnType::Uuid => SqlTypeFamily::Uuid,
152 ColumnType::DateTime => SqlTypeFamily::DateTime,
153 ColumnType::Other(_) => Self::from_unclassified_source_type(source_type),
154 }
155 }
156
157 fn from_unclassified_source_type(source_type: &str) -> Self {
160 let lower = source_type.to_lowercase();
161 if lower.contains("json") {
162 SqlTypeFamily::Json
163 } else if lower.contains("blob") || lower.contains("binary") || lower.contains("bytea") {
164 SqlTypeFamily::Bytes
165 } else {
166 SqlTypeFamily::Other
167 }
168 }
169}
170
171#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
180#[serde(try_from = "PortableColumnInput")]
181pub struct PortableColumn {
182 pub name: String,
183 pub source_type: String,
184 pub family: SqlTypeFamily,
185 pub nullable: bool,
186 #[serde(default)]
187 pub primary_key: bool,
188 #[serde(default)]
189 pub unique: bool,
190 #[serde(default, skip_serializing_if = "Option::is_none")]
191 pub default_sql: Option<String>,
192 #[serde(default)]
193 pub generated: bool,
194 #[serde(default)]
195 pub identity: bool,
196 #[serde(default, skip_serializing_if = "Option::is_none")]
197 pub collation: Option<String>,
198}
199
200impl JsonSchema for PortableColumn {
207 fn schema_name() -> std::borrow::Cow<'static, str> {
208 "PortableColumn".into()
209 }
210
211 fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
212 let family_schema = generator.subschema_for::<SqlTypeFamily>();
213 schemars::json_schema!({
214 "type": "object",
215 "properties": {
216 "name": { "type": "string" },
217 "source_type": { "type": "string" },
218 "type": {
219 "type": "string",
220 "description": "Shorthand alias for `source_type`; `family` is derived automatically when omitted."
221 },
222 "family": family_schema,
223 "nullable": { "type": "boolean" },
224 "primary_key": { "type": "boolean" },
225 "unique": { "type": "boolean" },
226 "default_sql": { "type": ["string", "null"] },
227 "generated": { "type": "boolean" },
228 "identity": { "type": "boolean" },
229 "collation": { "type": ["string", "null"] }
230 },
231 "required": ["name", "nullable"],
232 "anyOf": [
233 { "required": ["source_type"] },
234 { "required": ["type"] }
235 ],
236 "additionalProperties": false
237 })
238 }
239}
240
241impl PortableColumn {
242 fn from_runtime(column: &Column) -> Self {
243 Self {
244 name: column.name.clone(),
245 source_type: column.source_type.clone(),
246 family: SqlTypeFamily::from_column(column),
247 nullable: column.is_nullable,
248 primary_key: column.is_primary_key,
249 unique: column.is_unique,
250 default_sql: column.default_sql.clone(),
251 generated: column.is_generated,
252 identity: column.is_identity,
253 collation: column.collation.clone(),
254 }
255 }
256}
257
258#[derive(Debug, Deserialize)]
264#[serde(deny_unknown_fields)]
265struct PortableColumnInput {
266 name: String,
267 #[serde(alias = "type")]
268 source_type: String,
269 #[serde(default)]
270 family: Option<SqlTypeFamily>,
271 nullable: bool,
272 #[serde(default)]
273 primary_key: bool,
274 #[serde(default)]
275 unique: bool,
276 #[serde(default)]
277 default_sql: Option<String>,
278 #[serde(default)]
279 generated: bool,
280 #[serde(default)]
281 identity: bool,
282 #[serde(default)]
283 collation: Option<String>,
284}
285
286impl From<PortableColumnInput> for PortableColumn {
287 fn from(input: PortableColumnInput) -> Self {
288 let family = input
289 .family
290 .unwrap_or_else(|| SqlTypeFamily::from_source_type(&input.source_type));
291 Self {
292 name: input.name,
293 source_type: input.source_type,
294 family,
295 nullable: input.nullable,
296 primary_key: input.primary_key,
297 unique: input.unique,
298 default_sql: input.default_sql,
299 generated: input.generated,
300 identity: input.identity,
301 collation: input.collation,
302 }
303 }
304}
305
306#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
308#[serde(deny_unknown_fields)]
309pub struct PortableUniqueConstraint {
310 #[serde(default, skip_serializing_if = "Option::is_none")]
311 pub name: Option<String>,
312 pub columns: Vec<String>,
313}
314
315#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
317#[serde(deny_unknown_fields)]
318pub struct PortableCheckConstraint {
319 #[serde(default, skip_serializing_if = "Option::is_none")]
320 pub name: Option<String>,
321 pub expression: String,
322}
323
324#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
327#[serde(deny_unknown_fields)]
328pub struct PortableIndex {
329 pub name: String,
330 pub columns: Vec<String>,
331 #[serde(default)]
332 pub unique: bool,
333 #[serde(default, skip_serializing_if = "Option::is_none")]
334 pub index_type: Option<String>,
335}
336
337#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
341#[serde(deny_unknown_fields)]
342pub struct PortableRelationship {
343 #[serde(default, skip_serializing_if = "Option::is_none")]
344 pub name: Option<String>,
345 pub columns: Vec<String>,
346 pub referenced_table: String,
347 pub referenced_columns: Vec<String>,
348}
349
350#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
354#[serde(deny_unknown_fields)]
355pub struct PortableTable {
356 pub name: String,
357 pub columns: Vec<PortableColumn>,
358 #[serde(default)]
359 pub primary_key: Vec<String>,
360 #[serde(default)]
361 pub unique_constraints: Vec<PortableUniqueConstraint>,
362 #[serde(default)]
363 pub check_constraints: Vec<PortableCheckConstraint>,
364 #[serde(default)]
365 pub indexes: Vec<PortableIndex>,
366 #[serde(default, skip_serializing_if = "Option::is_none")]
367 pub create_statement: Option<String>,
368 #[serde(default)]
369 pub relationships: Vec<PortableRelationship>,
370}
371
372impl PortableTable {
373 fn from_runtime(table: &TableSchema) -> Self {
374 let columns: Vec<PortableColumn> = table
375 .columns
376 .iter()
377 .map(PortableColumn::from_runtime)
378 .collect();
379
380 let primary_key = table
381 .primary_key
382 .iter()
383 .filter_map(|&id| table.column(id))
384 .map(|c| c.name.clone())
385 .collect();
386
387 let unique_constraints = table
388 .unique_constraints
389 .iter()
390 .map(|uc| PortableUniqueConstraint {
391 name: uc.name.clone(),
392 columns: uc.columns.clone(),
393 })
394 .collect();
395
396 let check_constraints = table
397 .check_constraints
398 .iter()
399 .map(|cc| PortableCheckConstraint {
400 name: cc.name.clone(),
401 expression: cc.expression.clone(),
402 })
403 .collect();
404
405 let indexes = table
406 .indexes
407 .iter()
408 .map(|idx| PortableIndex {
409 name: idx.name.clone(),
410 columns: idx.columns.clone(),
411 unique: idx.is_unique,
412 index_type: idx.index_type.clone(),
413 })
414 .collect();
415
416 let relationships = table
417 .foreign_keys
418 .iter()
419 .map(|fk| PortableRelationship {
420 name: fk.name.clone(),
421 columns: fk.column_names.clone(),
422 referenced_table: fk.referenced_table.clone(),
423 referenced_columns: fk.referenced_columns.clone(),
424 })
425 .collect();
426
427 Self {
428 name: table.name.clone(),
429 columns,
430 primary_key,
431 unique_constraints,
432 check_constraints,
433 indexes,
434 create_statement: table.create_statement.clone(),
435 relationships,
436 }
437 }
438}
439
440#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
444#[serde(deny_unknown_fields)]
445pub struct PortableSchema {
446 pub dialect: String,
448 pub tables: BTreeMap<String, PortableTable>,
451}
452
453impl PortableSchema {
454 pub fn from_runtime(schema: &Schema, dialect: SqlDialect) -> Self {
456 let tables = schema
457 .iter()
458 .map(|table| (table.name.clone(), PortableTable::from_runtime(table)))
459 .collect();
460
461 Self {
462 dialect: dialect.to_string(),
463 tables,
464 }
465 }
466}
467
468#[cfg(test)]
469mod tests {
470 use super::*;
471
472 #[test]
477 fn portable_column_accepts_type_shorthand_and_derives_family() {
478 let yaml = "{ name: id, type: bigint, nullable: false, primary_key: true }";
479 let column: PortableColumn = serde_yaml_ng::from_str(yaml).unwrap();
480 assert_eq!(column.source_type, "bigint");
481 assert_eq!(column.family, SqlTypeFamily::BigInteger);
482 assert!(column.primary_key);
483 }
484
485 #[test]
486 fn portable_column_canonical_form_round_trips() {
487 let column = PortableColumn {
488 name: "id".to_string(),
489 source_type: "bigint".to_string(),
490 family: SqlTypeFamily::BigInteger,
491 nullable: false,
492 primary_key: true,
493 unique: false,
494 default_sql: None,
495 generated: false,
496 identity: false,
497 collation: None,
498 };
499
500 let rendered = serde_yaml_ng::to_string(&column).unwrap();
501 assert!(rendered.contains("source_type: bigint"));
502 assert!(rendered.contains("family: big_integer"));
503 assert!(!rendered.contains("\ntype:"));
504
505 let reparsed: PortableColumn = serde_yaml_ng::from_str(&rendered).unwrap();
506 assert_eq!(reparsed, column);
507 }
508
509 #[test]
510 fn portable_column_rejects_unknown_fields_even_with_shorthand() {
511 let yaml = "{ name: id, type: bigint, nullable: false, bogus: true }";
512 let err = serde_yaml_ng::from_str::<PortableColumn>(yaml).unwrap_err();
513 assert!(err.to_string().contains("unknown field"));
514 }
515
516 #[test]
517 fn declared_character_length_only_accepts_bounded_text_types() {
518 assert_eq!(declared_character_length("varchar(8)"), Some(8));
519 assert_eq!(declared_character_length("VARCHAR(255)"), Some(255));
520 assert_eq!(declared_character_length("character varying(42)"), Some(42));
521 assert_eq!(declared_character_length("nvarchar(12)"), Some(12));
522 assert_eq!(declared_character_length("text"), None);
523 assert_eq!(declared_character_length("decimal(10,2)"), None);
524 assert_eq!(declared_character_length("geometry(4326)"), None);
525 }
526
527 #[test]
528 fn declared_numeric_shapes_capture_width_and_signedness() {
529 assert_eq!(
530 declared_integer_bounds("tinyint unsigned", None),
531 Some((0, 255))
532 );
533 assert_eq!(
534 declared_integer_bounds("tinyint", Some(SqlDialect::MySql)),
535 Some((-128, 127))
536 );
537 assert_eq!(
538 declared_integer_bounds("tinyint", Some(SqlDialect::Mssql)),
539 Some((0, 255))
540 );
541 assert_eq!(declared_integer_bounds("tinyint", None), None);
542 assert_eq!(
543 conservative_integer_generation_bounds("tinyint"),
544 Some((0, 127))
545 );
546 assert_eq!(
547 declared_integer_bounds("smallint", None),
548 Some((-32_768, 32_767))
549 );
550 assert_eq!(
551 declared_integer_bounds("bigint unsigned", None),
552 Some((0, u64::MAX as i128))
553 );
554 assert_eq!(declared_integer_bounds("decimal(10,2)", None), None);
555 assert_eq!(declared_decimal_shape("decimal(10,8)"), Some((10, 8)));
556 assert_eq!(declared_decimal_shape("NUMERIC(12)"), Some((12, 0)));
557 assert_eq!(declared_decimal_shape("varchar(12)"), None);
558 }
559}