Skip to main content

sql_splitter/schema/
ddl.rs

1//! MySQL DDL parsing for schema extraction.
2//!
3//! Parses CREATE TABLE and ALTER TABLE statements to extract:
4//! - Column definitions with types
5//! - Primary key constraints
6//! - Foreign key constraints
7
8use super::{
9    CheckConstraint, Column, ColumnId, ColumnType, ForeignKey, IndexDef, Schema, TableId,
10    TableSchema, UniqueConstraint,
11};
12use once_cell::sync::Lazy;
13use regex::Regex;
14
15/// Regex to extract table name from CREATE TABLE
16/// Supports: `table` (MySQL), "table" (PostgreSQL), [table] (MSSQL), table (SQLite/unquoted), schema.table
17static CREATE_TABLE_NAME_RE: Lazy<Regex> = Lazy::new(|| {
18    // Match table name with various quoting styles including MSSQL brackets
19    // Pattern handles: schema.table, [schema].[table], `schema`.`table`, "schema"."table"
20    Regex::new(r#"(?i)CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:[\[\]`"\w]+\s*\.\s*)*[\[`"]?([^\[\]`"\s(]+)[\]`"]?"#)
21        .unwrap()
22});
23
24/// Regex to extract table name from ALTER TABLE
25/// Supports: `table` (MySQL), "table" (PostgreSQL), [table] (MSSQL), table (SQLite/unquoted), schema.table
26static ALTER_TABLE_NAME_RE: Lazy<Regex> = Lazy::new(|| {
27    Regex::new(
28        r#"(?i)ALTER\s+TABLE\s+(?:ONLY\s+)?(?:[\[\]`"\w]+\s*\.\s*)*[\[`"]?([^\[\]`"\s]+)[\]`"]?"#,
29    )
30    .unwrap()
31});
32
33/// Regex for column definition
34/// Supports: `column` (MySQL), "column" (PostgreSQL), [column] (MSSQL), column (unquoted)
35static COLUMN_DEF_RE: Lazy<Regex> = Lazy::new(|| {
36    Regex::new(r#"^\s*[\[`"]?([^\[\]`"\s,]+)[\]`"]?\s+(\w+(?:\([^)]+\))?(?:\s+unsigned)?)"#)
37        .unwrap()
38});
39
40/// Regex for PRIMARY KEY constraint
41/// Supports MSSQL CLUSTERED/NONCLUSTERED keywords: PRIMARY KEY CLUSTERED ([col])
42static PRIMARY_KEY_RE: Lazy<Regex> = Lazy::new(|| {
43    Regex::new(r"(?i)PRIMARY\s+KEY\s*(?:CLUSTERED\s+|NONCLUSTERED\s+)?\(([^)]+)\)").unwrap()
44});
45
46/// Regex for inline PRIMARY KEY on column
47static INLINE_PRIMARY_KEY_RE: Lazy<Regex> =
48    Lazy::new(|| Regex::new(r"(?i)\bPRIMARY\s+KEY\b").unwrap());
49
50/// Regex for FOREIGN KEY constraint with optional constraint name
51/// Supports: `name` (MySQL), "name" (PostgreSQL), [name] (MSSQL), name (unquoted)
52static FOREIGN_KEY_RE: Lazy<Regex> = Lazy::new(|| {
53    Regex::new(
54        r#"(?i)(?:CONSTRAINT\s+[\[`"]?([^\[\]`"\s]+)[\]`"]?\s+)?FOREIGN\s+KEY\s*\(([^)]+)\)\s*REFERENCES\s+(?:[\[\]`"\w]+\s*\.\s*)*[\[`"]?([^\[\]`"\s(]+)[\]`"]?\s*\(([^)]+)\)"#,
55    )
56    .unwrap()
57});
58
59/// Regex to detect NOT NULL constraint
60static NOT_NULL_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bNOT\s+NULL\b").unwrap());
61
62/// Regex for inline INDEX/KEY in CREATE TABLE
63/// Matches: INDEX idx_name (col1, col2), KEY idx_name (col1), UNIQUE INDEX idx_name (col1)
64/// Supports MSSQL bracket quoting: INDEX [idx_name] ([col])
65static INLINE_INDEX_RE: Lazy<Regex> = Lazy::new(|| {
66    Regex::new(r#"(?i)(?:(UNIQUE)\s+)?(?:INDEX|KEY)\s+[\[`"]?(\w+)[\]`"]?\s*\(([^)]+)\)"#).unwrap()
67});
68
69/// Regex for CREATE INDEX statement
70/// Matches: CREATE [UNIQUE] [CLUSTERED|NONCLUSTERED] INDEX [IF NOT EXISTS] idx_name ON table [USING method] (columns)
71/// Supports MSSQL bracket quoting and schema prefixes
72static CREATE_INDEX_RE: Lazy<Regex> = Lazy::new(|| {
73    Regex::new(
74        r#"(?i)CREATE\s+(UNIQUE\s+)?(?:CLUSTERED\s+|NONCLUSTERED\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?[\[`"]?(\w+)[\]`"]?\s+ON\s+(?:[\[\]`"\w]+\s*\.\s*)*[\[`"]?(\w+)[\]`"]?\s*(?:USING\s+(\w+)\s*)?\(([^)]+)\)"#,
75    )
76    .unwrap()
77});
78
79/// Builder for constructing schema from DDL statements
80#[derive(Debug, Default)]
81pub struct SchemaBuilder {
82    schema: Schema,
83}
84
85impl SchemaBuilder {
86    /// Create a new schema builder
87    pub fn new() -> Self {
88        Self {
89            schema: Schema::new(),
90        }
91    }
92
93    /// Parse a CREATE TABLE statement and add to schema
94    pub fn parse_create_table(&mut self, stmt: &str) -> Option<TableId> {
95        let table_name = extract_create_table_name(stmt)?;
96
97        // Check if table already exists
98        if self.schema.get_table_id(&table_name).is_some() {
99            return self.schema.get_table_id(&table_name);
100        }
101
102        let mut table = TableSchema::new(table_name, TableId(0));
103        table.create_statement = Some(stmt.to_string());
104
105        // Extract the body between first ( and last )
106        let body = extract_table_body(stmt)?;
107
108        // Parse columns and constraints
109        parse_table_body(&body, &mut table);
110
111        // Add table to schema
112        Some(self.schema.add_table(table))
113    }
114
115    /// Parse an ALTER TABLE statement and update existing table
116    pub fn parse_alter_table(&mut self, stmt: &str) -> Option<TableId> {
117        let table_name = extract_alter_table_name(stmt)?;
118        let table_id = self.schema.get_table_id(&table_name)?;
119
120        // Parse any FK constraints added by ALTER TABLE
121        for fk in parse_foreign_keys(stmt) {
122            if let Some(table) = self.schema.table_mut(table_id) {
123                // Resolve column names to IDs
124                let mut resolved_fk = fk;
125                resolved_fk.columns = resolved_fk
126                    .column_names
127                    .iter()
128                    .filter_map(|name| table.get_column_id(name))
129                    .collect();
130                table.foreign_keys.push(resolved_fk);
131            }
132        }
133
134        Some(table_id)
135    }
136
137    /// Parse a CREATE INDEX statement and add to the appropriate table
138    pub fn parse_create_index(&mut self, stmt: &str) -> Option<TableId> {
139        let caps = CREATE_INDEX_RE.captures(stmt)?;
140
141        let is_unique = caps.get(1).is_some();
142        let index_name = caps.get(2)?.as_str().to_string();
143        let table_name = caps.get(3)?.as_str().to_string();
144        let index_type = caps.get(4).map(|m| m.as_str().to_uppercase());
145        let columns_str = caps.get(5)?.as_str();
146        let columns = parse_column_list(columns_str);
147
148        let table_id = self.schema.get_table_id(&table_name)?;
149
150        if let Some(table) = self.schema.table_mut(table_id) {
151            table.indexes.push(IndexDef {
152                name: index_name,
153                columns,
154                is_unique,
155                index_type,
156            });
157        }
158
159        Some(table_id)
160    }
161
162    /// Finalize the schema, resolving all FK references
163    pub fn build(mut self) -> Schema {
164        self.schema.resolve_foreign_keys();
165        self.schema
166    }
167
168    /// Get current schema (for inspection during building)
169    pub fn schema(&self) -> &Schema {
170        &self.schema
171    }
172}
173
174/// Extract table name from CREATE TABLE statement
175pub fn extract_create_table_name(stmt: &str) -> Option<String> {
176    CREATE_TABLE_NAME_RE
177        .captures(stmt)
178        .and_then(|c| c.get(1))
179        .map(|m| m.as_str().to_string())
180}
181
182/// Extract table name from ALTER TABLE statement
183pub fn extract_alter_table_name(stmt: &str) -> Option<String> {
184    ALTER_TABLE_NAME_RE
185        .captures(stmt)
186        .and_then(|c| c.get(1))
187        .map(|m| m.as_str().to_string())
188}
189
190/// Extract the body of a CREATE TABLE statement (between first ( and matching ))
191fn extract_table_body(stmt: &str) -> Option<String> {
192    let bytes = stmt.as_bytes();
193    let mut depth = 0;
194    let mut start = None;
195    let mut in_string = false;
196    let mut escape_next = false;
197
198    for (i, &b) in bytes.iter().enumerate() {
199        if escape_next {
200            escape_next = false;
201            continue;
202        }
203
204        if b == b'\\' && in_string {
205            escape_next = true;
206            continue;
207        }
208
209        if b == b'\'' {
210            in_string = !in_string;
211            continue;
212        }
213
214        if in_string {
215            continue;
216        }
217
218        if b == b'(' {
219            if depth == 0 {
220                start = Some(i + 1);
221            }
222            depth += 1;
223        } else if b == b')' {
224            depth -= 1;
225            if depth == 0 {
226                if let Some(s) = start {
227                    return Some(stmt[s..i].to_string());
228                }
229            }
230        }
231    }
232
233    None
234}
235
236/// Parse the body of a CREATE TABLE to extract columns and constraints
237fn parse_table_body(body: &str, table: &mut TableSchema) {
238    // Split by commas, but respect nested parentheses
239    let parts = split_table_body(body);
240
241    for part in parts {
242        let trimmed = part.trim();
243        if trimmed.is_empty() {
244            continue;
245        }
246
247        // Check if this is a constraint or a column
248        let upper = trimmed.to_uppercase();
249        if upper.starts_with("PRIMARY KEY")
250            || upper.starts_with("CONSTRAINT")
251            || upper.starts_with("FOREIGN KEY")
252            || upper.starts_with("KEY ")
253            || upper.starts_with("INDEX ")
254            || upper.starts_with("UNIQUE ")
255            || upper.starts_with("FULLTEXT ")
256            || upper.starts_with("SPATIAL ")
257            || upper.starts_with("CHECK ")
258        {
259            // Parse constraints
260            if let Some(pk_cols) = parse_primary_key_constraint(trimmed) {
261                for col_name in pk_cols {
262                    if let Some(col) = table
263                        .columns
264                        .iter_mut()
265                        .find(|c| c.name.eq_ignore_ascii_case(&col_name))
266                    {
267                        col.is_primary_key = true;
268                        if !table.primary_key.contains(&col.ordinal) {
269                            table.primary_key.push(col.ordinal);
270                        }
271                    }
272                }
273            }
274
275            for fk in parse_foreign_keys(trimmed) {
276                let mut resolved_fk = fk;
277                resolved_fk.columns = resolved_fk
278                    .column_names
279                    .iter()
280                    .filter_map(|name| table.get_column_id(name))
281                    .collect();
282                table.foreign_keys.push(resolved_fk);
283            }
284
285            // Parse inline indexes (INDEX, KEY, UNIQUE INDEX, UNIQUE KEY)
286            if let Some(idx) = parse_inline_index(trimmed) {
287                table.indexes.push(idx);
288            }
289
290            // Parse a bare table-level UNIQUE (col, ...) constraint, marking a
291            // single covered column as unique too.
292            if let Some(uc) = parse_unique_constraint(trimmed) {
293                if let [only_column] = uc.columns.as_slice() {
294                    if let Some(col) = table
295                        .columns
296                        .iter_mut()
297                        .find(|c| c.name.eq_ignore_ascii_case(only_column))
298                    {
299                        col.is_unique = true;
300                    }
301                }
302                table.unique_constraints.push(uc);
303            }
304
305            // Parse a table-level CHECK (...) constraint
306            if let Some(cc) = parse_check_constraint(trimmed) {
307                table.check_constraints.push(cc);
308            }
309        } else {
310            // Parse column definition
311            if let Some((col, inline_check)) =
312                parse_column_def(trimmed, ColumnId(table.columns.len() as u16))
313            {
314                if let Some(expression) = inline_check {
315                    table.check_constraints.push(CheckConstraint {
316                        name: None,
317                        expression,
318                    });
319                }
320
321                // Check for inline PRIMARY KEY
322                if INLINE_PRIMARY_KEY_RE.is_match(trimmed) {
323                    let mut col = col;
324                    col.is_primary_key = true;
325                    table.primary_key.push(col.ordinal);
326                    table.columns.push(col);
327                } else {
328                    table.columns.push(col);
329                }
330            }
331        }
332    }
333}
334
335/// Split table body by commas, respecting nested parentheses
336pub fn split_table_body(body: &str) -> Vec<String> {
337    let mut parts = Vec::new();
338    let mut current = String::new();
339    let mut depth = 0;
340    let mut in_string = false;
341    let mut escape_next = false;
342
343    for ch in body.chars() {
344        if escape_next {
345            current.push(ch);
346            escape_next = false;
347            continue;
348        }
349
350        if ch == '\\' && in_string {
351            current.push(ch);
352            escape_next = true;
353            continue;
354        }
355
356        if ch == '\'' {
357            in_string = !in_string;
358            current.push(ch);
359            continue;
360        }
361
362        if in_string {
363            current.push(ch);
364            continue;
365        }
366
367        match ch {
368            '(' => {
369                depth += 1;
370                current.push(ch);
371            }
372            ')' => {
373                depth -= 1;
374                current.push(ch);
375            }
376            ',' if depth == 0 => {
377                parts.push(current.trim().to_string());
378                current = String::new();
379            }
380            _ => {
381                current.push(ch);
382            }
383        }
384    }
385
386    if !current.trim().is_empty() {
387        parts.push(current.trim().to_string());
388    }
389
390    parts
391}
392
393/// Parse a column definition, returning the column plus any inline
394/// column-level CHECK expression found among its modifiers (callers attach
395/// that to the table's check constraints, since `Column` has no such field).
396fn parse_column_def(def: &str, ordinal: ColumnId) -> Option<(Column, Option<String>)> {
397    let caps = COLUMN_DEF_RE.captures(def)?;
398    let whole = caps.get(0)?;
399    let name = caps.get(1)?.as_str().to_string();
400    let type_str = caps.get(2)?.as_str().to_string();
401
402    let col_type = ColumnType::from_mysql_type(&type_str);
403    let is_nullable = !NOT_NULL_RE.is_match(def);
404
405    let remainder = &def[whole.end()..];
406    let modifiers = parse_column_modifiers(remainder);
407    // PostgreSQL `serial`/`bigserial`/`smallserial` columns are backed by an
408    // implicit sequence, so they carry identity semantics even without an
409    // explicit IDENTITY/AUTO_INCREMENT modifier.
410    let is_identity = modifiers.is_identity || type_str.to_lowercase().contains("serial");
411
412    let column = Column {
413        name,
414        col_type,
415        source_type: type_str,
416        ordinal,
417        is_primary_key: false,
418        is_nullable,
419        is_unique: modifiers.is_unique,
420        default_sql: modifiers.default_sql,
421        is_generated: modifiers.is_generated,
422        is_identity,
423        collation: modifiers.collation,
424    };
425
426    Some((column, modifiers.inline_check))
427}
428
429/// Modifiers found after a column's name and type: UNIQUE, DEFAULT,
430/// GENERATED .. AS (...), IDENTITY/AUTO_INCREMENT, COLLATE, and inline CHECK.
431#[derive(Debug, Default)]
432struct ColumnModifiers {
433    is_unique: bool,
434    default_sql: Option<String>,
435    is_generated: bool,
436    is_identity: bool,
437    collation: Option<String>,
438    inline_check: Option<String>,
439}
440
441/// Parse the column modifiers following the name/type, using
442/// [`tokenize_ddl`] so that quoted defaults and parenthesized expressions
443/// (e.g. `DEFAULT 'active'`, `CHECK (a > 0 AND (b < 1))`) are kept intact
444/// rather than split on whitespace.
445fn parse_column_modifiers(remainder: &str) -> ColumnModifiers {
446    let tokens = tokenize_ddl(remainder);
447    let mut modifiers = ColumnModifiers::default();
448    let mut i = 0;
449
450    while i < tokens.len() {
451        let upper = tokens[i].to_uppercase();
452        match upper.as_str() {
453            "UNIQUE" => {
454                modifiers.is_unique = true;
455                i += 1;
456            }
457            "DEFAULT" => {
458                if let Some(value) = tokens.get(i + 1) {
459                    modifiers.default_sql = Some(value.clone());
460                    i += 2;
461                } else {
462                    i += 1;
463                }
464            }
465            "COLLATE" => {
466                if let Some(value) = tokens.get(i + 1) {
467                    modifiers.collation = Some(strip_quotes(value));
468                    i += 2;
469                } else {
470                    i += 1;
471                }
472            }
473            "CHECK" => {
474                if let Some(expr) = tokens.get(i + 1) {
475                    modifiers.inline_check = Some(strip_outer_parens(expr));
476                    i += 2;
477                } else {
478                    i += 1;
479                }
480            }
481            "GENERATED" => {
482                // Skip ALWAYS/BY/DEFAULT until AS, then inspect what follows:
483                // `AS (expr)` is a computed column, `AS IDENTITY` is identity.
484                let mut j = i + 1;
485                while j < tokens.len() && !tokens[j].eq_ignore_ascii_case("AS") {
486                    j += 1;
487                }
488                if let Some(as_expr) = tokens.get(j + 1) {
489                    if as_expr.starts_with('(') {
490                        modifiers.is_generated = true;
491                    } else if as_expr.eq_ignore_ascii_case("IDENTITY") {
492                        modifiers.is_identity = true;
493                    }
494                }
495                i = j + 2;
496            }
497            "AUTO_INCREMENT" | "AUTOINCREMENT" => {
498                modifiers.is_identity = true;
499                i += 1;
500            }
501            _ if upper.starts_with("IDENTITY(") || upper == "IDENTITY" => {
502                modifiers.is_identity = true;
503                i += 1;
504            }
505            _ => {
506                i += 1;
507            }
508        }
509    }
510
511    modifiers
512}
513
514/// Split a fragment of DDL into whitespace-separated tokens, treating
515/// single-quoted strings and parenthesized groups (including nested
516/// parentheses) as atomic units. This lets callers pull out `DEFAULT`,
517/// `CHECK`, and `GENERATED ... AS (...)` values without splitting the SQL
518/// expressions they contain on internal whitespace.
519fn tokenize_ddl(s: &str) -> Vec<String> {
520    let mut tokens = Vec::new();
521    let mut current = String::new();
522    let mut depth = 0u32;
523    let mut in_string = false;
524    let mut escape_next = false;
525
526    for ch in s.chars() {
527        if escape_next {
528            current.push(ch);
529            escape_next = false;
530            continue;
531        }
532
533        if ch == '\\' && in_string {
534            current.push(ch);
535            escape_next = true;
536            continue;
537        }
538
539        if ch == '\'' {
540            in_string = !in_string;
541            current.push(ch);
542            continue;
543        }
544
545        if in_string {
546            current.push(ch);
547            continue;
548        }
549
550        match ch {
551            '(' => {
552                depth += 1;
553                current.push(ch);
554            }
555            ')' => {
556                depth = depth.saturating_sub(1);
557                current.push(ch);
558            }
559            c if c.is_whitespace() && depth == 0 => {
560                if !current.is_empty() {
561                    tokens.push(std::mem::take(&mut current));
562                }
563            }
564            _ => current.push(ch),
565        }
566    }
567
568    if !current.is_empty() {
569        tokens.push(current);
570    }
571
572    tokens
573}
574
575/// Strip surrounding quote/bracket characters from an identifier-like token
576fn strip_quotes(s: &str) -> String {
577    s.trim_matches('\'')
578        .trim_matches('"')
579        .trim_matches('`')
580        .trim_matches('[')
581        .trim_matches(']')
582        .to_string()
583}
584
585/// Strip a single layer of enclosing parentheses from an expression token,
586/// if present (used to store CHECK expressions without the outer parens).
587fn strip_outer_parens(s: &str) -> String {
588    let trimmed = s.trim();
589    match trimmed
590        .strip_prefix('(')
591        .and_then(|rest| rest.strip_suffix(')'))
592    {
593        Some(inner) => inner.trim().to_string(),
594        None => trimmed.to_string(),
595    }
596}
597
598/// Parse a table-level UNIQUE constraint: `[CONSTRAINT name] UNIQUE (cols)`.
599/// Does not match `UNIQUE INDEX`/`UNIQUE KEY` forms, which are handled by
600/// [`parse_inline_index`].
601fn parse_unique_constraint(constraint: &str) -> Option<UniqueConstraint> {
602    let tokens = tokenize_ddl(constraint);
603    let mut i = 0;
604    let mut name = None;
605
606    if tokens.first()?.eq_ignore_ascii_case("CONSTRAINT") {
607        name = tokens.get(1).map(|s| strip_quotes(s));
608        i = 2;
609    }
610
611    if !tokens.get(i)?.eq_ignore_ascii_case("UNIQUE") {
612        return None;
613    }
614
615    let cols_token = tokens.get(i + 1)?;
616    if !cols_token.starts_with('(') {
617        // Not a bare `UNIQUE (cols)` constraint (e.g. `UNIQUE INDEX ...` or
618        // `UNIQUE KEY ...`, handled separately by `parse_inline_index`).
619        return None;
620    }
621    let columns = parse_column_list(strip_outer_parens(cols_token).as_str());
622    if columns.is_empty() {
623        return None;
624    }
625
626    Some(UniqueConstraint { name, columns })
627}
628
629/// Parse a table-level CHECK constraint: `[CONSTRAINT name] CHECK (expr)`.
630fn parse_check_constraint(constraint: &str) -> Option<CheckConstraint> {
631    let tokens = tokenize_ddl(constraint);
632    let mut i = 0;
633    let mut name = None;
634
635    if tokens.first()?.eq_ignore_ascii_case("CONSTRAINT") {
636        name = tokens.get(1).map(|s| strip_quotes(s));
637        i = 2;
638    }
639
640    if !tokens.get(i)?.eq_ignore_ascii_case("CHECK") {
641        return None;
642    }
643
644    let expr_token = tokens.get(i + 1)?;
645    if !expr_token.starts_with('(') {
646        return None;
647    }
648
649    Some(CheckConstraint {
650        name,
651        expression: strip_outer_parens(expr_token),
652    })
653}
654
655/// Parse PRIMARY KEY constraint, returns column names
656fn parse_primary_key_constraint(constraint: &str) -> Option<Vec<String>> {
657    let caps = PRIMARY_KEY_RE.captures(constraint)?;
658    let cols_str = caps.get(1)?.as_str();
659    Some(parse_column_list(cols_str))
660}
661
662/// Parse inline INDEX/KEY constraint from CREATE TABLE body
663fn parse_inline_index(constraint: &str) -> Option<IndexDef> {
664    let caps = INLINE_INDEX_RE.captures(constraint)?;
665
666    let is_unique = caps.get(1).is_some();
667    let index_name = caps.get(2)?.as_str().to_string();
668    let columns_str = caps.get(3)?.as_str();
669    let columns = parse_column_list(columns_str);
670
671    Some(IndexDef {
672        name: index_name,
673        columns,
674        is_unique,
675        index_type: None, // Inline indexes don't specify type
676    })
677}
678
679/// Parse FOREIGN KEY constraints from a statement
680fn parse_foreign_keys(stmt: &str) -> Vec<ForeignKey> {
681    let mut fks = Vec::new();
682
683    for caps in FOREIGN_KEY_RE.captures_iter(stmt) {
684        let name = caps.get(1).map(|m| m.as_str().to_string());
685        let local_cols = caps
686            .get(2)
687            .map(|m| parse_column_list(m.as_str()))
688            .unwrap_or_default();
689        let ref_table = caps
690            .get(3)
691            .map(|m| m.as_str().to_string())
692            .unwrap_or_default();
693        let ref_cols = caps
694            .get(4)
695            .map(|m| parse_column_list(m.as_str()))
696            .unwrap_or_default();
697
698        if !local_cols.is_empty() && !ref_table.is_empty() && !ref_cols.is_empty() {
699            fks.push(ForeignKey {
700                name,
701                columns: Vec::new(), // Will be resolved later
702                column_names: local_cols,
703                referenced_table: ref_table,
704                referenced_columns: ref_cols,
705                referenced_table_id: None,
706            });
707        }
708    }
709
710    fks
711}
712
713/// Parse a comma-separated column list, stripping quotes (backticks, double quotes, brackets)
714pub fn parse_column_list(s: &str) -> Vec<String> {
715    s.split(',')
716        .map(|c| {
717            c.trim()
718                .trim_matches('`')
719                .trim_matches('"')
720                .trim_matches('[')
721                .trim_matches(']')
722                .to_string()
723        })
724        .filter(|c| !c.is_empty())
725        .collect()
726}