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