Skip to main content

sql_splitter/schema/
mod.rs

1//! Schema analysis module for FK-aware operations.
2//!
3//! This module provides:
4//! - Data models for table schemas, columns, and foreign keys
5//! - MySQL DDL parsing for extracting schema information
6//! - Dependency graph construction with topological sorting
7//! - Cycle detection for handling circular FK relationships
8
9mod build;
10mod ddl;
11mod graph;
12
13pub use ddl::*;
14pub use graph::*;
15
16use ahash::AHashMap;
17use std::fmt;
18
19/// Unique identifier for a table within a schema
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub struct TableId(pub u32);
22
23impl fmt::Display for TableId {
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        write!(f, "TableId({})", self.0)
26    }
27}
28
29/// Unique identifier for a column within a table
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
31pub struct ColumnId(pub u16);
32
33impl fmt::Display for ColumnId {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        write!(f, "ColumnId({})", self.0)
36    }
37}
38
39/// SQL column type classification
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub enum ColumnType {
42    /// Integer types: INT, INTEGER, TINYINT, SMALLINT, MEDIUMINT
43    Int,
44    /// Big integer types: BIGINT
45    BigInt,
46    /// Text types: CHAR, VARCHAR, TEXT, etc.
47    Text,
48    /// UUID types (detected by column name or type)
49    Uuid,
50    /// Decimal/numeric types
51    Decimal,
52    /// Date/time types
53    DateTime,
54    /// Boolean type
55    Bool,
56    /// Any other type
57    Other(String),
58}
59
60impl ColumnType {
61    /// Parse a SQL type string into a ColumnType
62    /// Supports MySQL, PostgreSQL, SQLite, and MSSQL types.
63    pub fn from_sql_type(type_str: &str) -> Self {
64        let type_lower = type_str.to_lowercase();
65        let base_type = type_lower.split('(').next().unwrap_or(&type_lower).trim();
66
67        // MySQL numeric types can carry `unsigned`/`signed`/`zerofill`
68        // modifiers after the base name. Remove only those trailing modifiers
69        // so genuine multi-word names such as `double precision` remain
70        // intact.
71        let mut base_words: Vec<_> = base_type.split_whitespace().collect();
72        while base_words
73            .last()
74            .is_some_and(|word| matches!(*word, "unsigned" | "signed" | "zerofill"))
75        {
76            base_words.pop();
77        }
78        let base_type = base_words.join(" ");
79
80        match base_type.as_str() {
81            // Integer types (all dialects)
82            "int" | "integer" | "tinyint" | "smallint" | "mediumint" | "int4" | "int2" => {
83                ColumnType::Int
84            }
85            // Auto-increment integer types (PostgreSQL)
86            "serial" | "smallserial" => ColumnType::Int,
87            "bigint" | "int8" | "bigserial" => ColumnType::BigInt,
88            // Text types (all dialects)
89            "char"
90            | "varchar"
91            | "text"
92            | "tinytext"
93            | "mediumtext"
94            | "longtext"
95            | "enum"
96            | "set"
97            | "character"
98            | "character varying"
99            | "char varying"
100            | "national character"
101            | "national character varying"
102            | "national char"
103            | "national char varying"
104            | "nchar"
105            | "nvarchar"
106            | "ntext" => ColumnType::Text,
107            // Decimal types (all dialects)
108            "decimal" | "numeric" | "float" | "double" | "double precision" | "real" | "float4"
109            | "float8" | "money" => ColumnType::Decimal,
110            // Date/time types (all dialects)
111            "date"
112            | "datetime"
113            | "timestamp"
114            | "time"
115            | "year"
116            | "timestamptz"
117            | "timetz"
118            | "interval"
119            | "timestamp with time zone"
120            | "timestamp without time zone"
121            | "time with time zone"
122            | "time without time zone" => ColumnType::DateTime,
123            interval if interval.starts_with("interval ") => ColumnType::DateTime,
124            // Boolean types. A bare BIT is MSSQL's boolean type; retain
125            // parameterized bit strings such as MySQL BIT(8) as unknown.
126            "bool" | "boolean" => ColumnType::Bool,
127            // TODO(deferred, L23): a bare `bit` maps to Bool for SQL Server's
128            // boolean `bit`, which also reclassifies MySQL's bare `BIT` from
129            // Other to Bool. Harmless today (no PK/FK impact); dialect-specific
130            // handling would be needed to treat MySQL's `BIT` differently.
131            "bit" if type_lower.trim() == "bit" => ColumnType::Bool,
132            // Binary types
133            "binary" | "varbinary" | "blob" | "bytea" => {
134                // Could be UUID if binary(16)
135                if type_lower.contains("16") {
136                    ColumnType::Uuid
137                } else {
138                    ColumnType::Other(type_str.to_string())
139                }
140            }
141            "uuid" => ColumnType::Uuid,
142            _ => ColumnType::Other(type_str.to_string()),
143        }
144    }
145
146    /// Parse a MySQL type string into a ColumnType (alias for from_sql_type)
147    pub fn from_mysql_type(type_str: &str) -> Self {
148        Self::from_sql_type(type_str)
149    }
150}
151
152/// Column definition within a table
153#[derive(Debug, Clone)]
154pub struct Column {
155    /// Column name
156    pub name: String,
157    /// Column type
158    pub col_type: ColumnType,
159    /// Raw SQL type as written in the DDL (e.g. `"VARCHAR(255)"`)
160    pub source_type: String,
161    /// Position in table (0-indexed)
162    pub ordinal: ColumnId,
163    /// Whether this column is part of the primary key
164    pub is_primary_key: bool,
165    /// Whether this column allows NULL values
166    pub is_nullable: bool,
167    /// Whether this column has a single-column UNIQUE constraint
168    pub is_unique: bool,
169    /// Raw DEFAULT expression, if any (e.g. `"'active'"`, `"(NOW())"`)
170    pub default_sql: Option<String>,
171    /// Whether this is a generated/computed column (`GENERATED ALWAYS AS (...)`)
172    pub is_generated: bool,
173    /// Whether this column is an auto-generated identity/auto-increment column
174    pub is_identity: bool,
175    /// Explicit column collation, if declared (`COLLATE ...`)
176    pub collation: Option<String>,
177}
178
179/// Index definition
180#[derive(Debug, Clone, PartialEq, Eq)]
181pub struct IndexDef {
182    /// Index name
183    pub name: String,
184    /// Columns in the index
185    pub columns: Vec<String>,
186    /// Whether this is a unique index
187    pub is_unique: bool,
188    /// Index type (BTREE, HASH, GIN, etc.)
189    pub index_type: Option<String>,
190}
191
192/// Table-level UNIQUE constraint, covering one or more columns
193#[derive(Debug, Clone, PartialEq, Eq)]
194pub struct UniqueConstraint {
195    /// Constraint name, if named explicitly
196    pub name: Option<String>,
197    /// Columns covered by the constraint, in declaration order
198    pub columns: Vec<String>,
199}
200
201/// CHECK constraint, with its raw SQL expression preserved verbatim
202#[derive(Debug, Clone, PartialEq, Eq)]
203pub struct CheckConstraint {
204    /// Constraint name, if named explicitly
205    pub name: Option<String>,
206    /// Raw CHECK expression (without the enclosing parentheses)
207    pub expression: String,
208}
209
210/// Foreign key constraint definition
211#[derive(Debug, Clone)]
212pub struct ForeignKey {
213    /// Constraint name (optional)
214    pub name: Option<String>,
215    /// Column IDs in this table that form the FK
216    pub columns: Vec<ColumnId>,
217    /// Column names in this table (before resolution)
218    pub column_names: Vec<String>,
219    /// Referenced table name
220    pub referenced_table: String,
221    /// Referenced column names
222    pub referenced_columns: Vec<String>,
223    /// Resolved referenced table ID (set after schema is complete)
224    pub referenced_table_id: Option<TableId>,
225}
226
227/// Complete table schema definition
228#[derive(Debug, Clone)]
229pub struct TableSchema {
230    /// Table name
231    pub name: String,
232    /// Table ID within the schema
233    pub id: TableId,
234    /// Column definitions in order
235    pub columns: Vec<Column>,
236    /// Primary key column IDs (ordered for composite PKs)
237    pub primary_key: Vec<ColumnId>,
238    /// Foreign key constraints
239    pub foreign_keys: Vec<ForeignKey>,
240    /// Table-level UNIQUE constraints (single- and multi-column)
241    pub unique_constraints: Vec<UniqueConstraint>,
242    /// CHECK constraints (table-level and inline column-level)
243    pub check_constraints: Vec<CheckConstraint>,
244    /// Index definitions
245    pub indexes: Vec<IndexDef>,
246    /// Raw CREATE TABLE statement (for output)
247    pub create_statement: Option<String>,
248}
249
250impl TableSchema {
251    /// Create a new empty table schema
252    pub fn new(name: String, id: TableId) -> Self {
253        Self {
254            name,
255            id,
256            columns: Vec::new(),
257            primary_key: Vec::new(),
258            foreign_keys: Vec::new(),
259            unique_constraints: Vec::new(),
260            check_constraints: Vec::new(),
261            indexes: Vec::new(),
262            create_statement: None,
263        }
264    }
265
266    /// Get a column by name
267    pub fn get_column(&self, name: &str) -> Option<&Column> {
268        self.columns
269            .iter()
270            .find(|c| c.name.eq_ignore_ascii_case(name))
271    }
272
273    /// Get column ID by name
274    pub fn get_column_id(&self, name: &str) -> Option<ColumnId> {
275        self.get_column(name).map(|c| c.ordinal)
276    }
277
278    /// Get column by ID
279    pub fn column(&self, id: ColumnId) -> Option<&Column> {
280        self.columns.get(id.0 as usize)
281    }
282
283    /// Check if column is part of the primary key
284    pub fn is_pk_column(&self, col_id: ColumnId) -> bool {
285        self.primary_key.contains(&col_id)
286    }
287}
288
289/// Complete database schema
290#[derive(Debug)]
291pub struct Schema {
292    /// Map from table name to table ID
293    pub tables: AHashMap<String, TableId>,
294    /// Table schemas indexed by TableId
295    pub table_schemas: Vec<TableSchema>,
296}
297
298impl Schema {
299    /// Create a new empty schema
300    pub fn new() -> Self {
301        Self {
302            tables: AHashMap::new(),
303            table_schemas: Vec::new(),
304        }
305    }
306
307    /// Get table ID by name (case-insensitive)
308    pub fn get_table_id(&self, name: &str) -> Option<TableId> {
309        // Try exact match first
310        if let Some(&id) = self.tables.get(name) {
311            return Some(id);
312        }
313        // Try case-insensitive match
314        let name_lower = name.to_lowercase();
315        self.tables
316            .iter()
317            .find(|(k, _)| k.to_lowercase() == name_lower)
318            .map(|(_, &id)| id)
319    }
320
321    /// Get table schema by ID
322    pub fn table(&self, id: TableId) -> Option<&TableSchema> {
323        self.table_schemas.get(id.0 as usize)
324    }
325
326    /// Get mutable table schema by ID
327    pub fn table_mut(&mut self, id: TableId) -> Option<&mut TableSchema> {
328        self.table_schemas.get_mut(id.0 as usize)
329    }
330
331    /// Get table schema by name
332    pub fn get_table(&self, name: &str) -> Option<&TableSchema> {
333        self.get_table_id(name).and_then(|id| self.table(id))
334    }
335
336    /// Add a new table schema, returning its ID
337    pub fn add_table(&mut self, mut schema: TableSchema) -> TableId {
338        let id = TableId(self.table_schemas.len() as u32);
339        schema.id = id;
340        self.tables.insert(schema.name.clone(), id);
341        self.table_schemas.push(schema);
342        id
343    }
344
345    /// Resolve all foreign key references to table IDs
346    pub fn resolve_foreign_keys(&mut self) {
347        let table_ids: AHashMap<String, TableId> = self.tables.clone();
348
349        for table in &mut self.table_schemas {
350            for fk in &mut table.foreign_keys {
351                fk.referenced_table_id = table_ids
352                    .get(&fk.referenced_table)
353                    .or_else(|| {
354                        // Case-insensitive fallback
355                        let lower = fk.referenced_table.to_lowercase();
356                        table_ids
357                            .iter()
358                            .find(|(k, _)| k.to_lowercase() == lower)
359                            .map(|(_, v)| v)
360                    })
361                    .copied();
362            }
363        }
364    }
365
366    /// Get the number of tables
367    pub fn len(&self) -> usize {
368        self.table_schemas.len()
369    }
370
371    /// Check if schema is empty
372    pub fn is_empty(&self) -> bool {
373        self.table_schemas.is_empty()
374    }
375
376    /// Iterate over all table schemas
377    pub fn iter(&self) -> impl Iterator<Item = &TableSchema> {
378        self.table_schemas.iter()
379    }
380}
381
382impl Default for Schema {
383    fn default() -> Self {
384        Self::new()
385    }
386}