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    Regex::new(
19        r#"(?ix)
20        CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?
21        (
22            (?:(?:\[(?:[^\]]|\]\])*\]|`(?:[^`]|``)*`|"(?:[^"]|"")*"|[^\s().,;]+)\s*\.\s*)*
23            (?:\[(?:[^\]]|\]\])*\]|`(?:[^`]|``)*`|"(?:[^"]|"")*"|[^\s().,;]+)
24        )
25        "#,
26    )
27    .unwrap()
28});
29
30/// Regex to extract table name from ALTER TABLE
31/// Supports: `table` (MySQL), "table" (PostgreSQL), [table] (MSSQL), table (SQLite/unquoted), schema.table
32static ALTER_TABLE_NAME_RE: Lazy<Regex> = Lazy::new(|| {
33    Regex::new(
34        r#"(?ix)
35        ALTER\s+TABLE\s+(?:ONLY\s+)?
36        (
37            (?:(?:\[(?:[^\]]|\]\])*\]|`(?:[^`]|``)*`|"(?:[^"]|"")*"|[^\s().,;]+)\s*\.\s*)*
38            (?:\[(?:[^\]]|\]\])*\]|`(?:[^`]|``)*`|"(?:[^"]|"")*"|[^\s().,;]+)
39        )
40        "#,
41    )
42    .unwrap()
43});
44
45/// Regex for column definition
46/// Supports: `column` (MySQL), "column" (PostgreSQL), [column] (MSSQL), column (unquoted)
47static COLUMN_DEF_RE: Lazy<Regex> = Lazy::new(|| {
48    Regex::new(r#"^\s*[\[`"]?([^\[\]`"\s,]+)[\]`"]?\s+(\w+(?:\([^)]+\))?(?:\s+unsigned)?)"#)
49        .unwrap()
50});
51
52/// Regex for PRIMARY KEY constraint
53/// Supports MSSQL CLUSTERED/NONCLUSTERED keywords: PRIMARY KEY CLUSTERED ([col])
54static PRIMARY_KEY_RE: Lazy<Regex> = Lazy::new(|| {
55    Regex::new(r"(?i)PRIMARY\s+KEY\s*(?:CLUSTERED\s+|NONCLUSTERED\s+)?\(([^)]+)\)").unwrap()
56});
57
58/// Regex for inline PRIMARY KEY on column
59static INLINE_PRIMARY_KEY_RE: Lazy<Regex> =
60    Lazy::new(|| Regex::new(r"(?i)\bPRIMARY\s+KEY\b").unwrap());
61
62/// Regex for FOREIGN KEY constraint with optional constraint name
63/// Supports: `name` (MySQL), "name" (PostgreSQL), [name] (MSSQL), name (unquoted)
64static FOREIGN_KEY_RE: Lazy<Regex> = Lazy::new(|| {
65    Regex::new(
66        r#"(?ix)
67        (?:CONSTRAINT\s+[\[`"]?([^\[\]`"\s]+)[\]`"]?\s+)?
68        FOREIGN\s+KEY\s*\(([^)]+)\)\s*REFERENCES\s+
69        (
70            (?:(?:\[(?:[^\]]|\]\])*\]|`(?:[^`]|``)*`|"(?:[^"]|"")*"|[^\s().,;]+)\s*\.\s*)*
71            (?:\[(?:[^\]]|\]\])*\]|`(?:[^`]|``)*`|"(?:[^"]|"")*"|[^\s().,;]+)
72        )\s*\(([^)]+)\)
73        "#,
74    )
75    .unwrap()
76});
77
78/// Regex to detect NOT NULL constraint
79static NOT_NULL_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bNOT\s+NULL\b").unwrap());
80
81/// Regex for inline INDEX/KEY in CREATE TABLE
82/// Matches: INDEX idx_name (col1, col2), KEY idx_name (col1), UNIQUE INDEX idx_name (col1)
83/// Supports MSSQL bracket quoting: INDEX [idx_name] ([col])
84static INLINE_INDEX_RE: Lazy<Regex> = Lazy::new(|| {
85    Regex::new(r#"(?i)(?:(UNIQUE)\s+)?(?:INDEX|KEY)\s+[\[`"]?(\w+)[\]`"]?\s*\(([^)]+)\)"#).unwrap()
86});
87
88/// Regex for CREATE INDEX statement
89/// Matches: CREATE [UNIQUE] [CLUSTERED|NONCLUSTERED] INDEX [IF NOT EXISTS] idx_name ON table [USING method] (columns)
90/// Supports MSSQL bracket quoting and schema prefixes
91static CREATE_INDEX_RE: Lazy<Regex> = Lazy::new(|| {
92    Regex::new(
93        r#"(?ix)
94        CREATE\s+(UNIQUE\s+)?(?:CLUSTERED\s+|NONCLUSTERED\s+)?INDEX\s+
95        (?:IF\s+NOT\s+EXISTS\s+)?[\[`"]?(\w+)[\]`"]?\s+ON\s+
96        (
97            (?:(?:\[(?:[^\]]|\]\])*\]|`(?:[^`]|``)*`|"(?:[^"]|"")*"|[^\s().,;]+)\s*\.\s*)*
98            (?:\[(?:[^\]]|\]\])*\]|`(?:[^`]|``)*`|"(?:[^"]|"")*"|[^\s().,;]+)
99        )\s*(?:USING\s+(\w+)\s*)?\(([^)]+)\)
100        "#,
101    )
102    .unwrap()
103});
104
105/// Builder for constructing schema from DDL statements
106#[derive(Debug, Default)]
107pub struct SchemaBuilder {
108    schema: Schema,
109}
110
111impl SchemaBuilder {
112    /// Create a new schema builder
113    pub fn new() -> Self {
114        Self {
115            schema: Schema::new(),
116        }
117    }
118
119    /// Parse a CREATE TABLE statement and add to schema
120    pub fn parse_create_table(&mut self, stmt: &str) -> Option<TableId> {
121        let table_name = extract_create_table_name(stmt)?;
122
123        // Check if table already exists
124        if self.schema.get_table_id(&table_name).is_some() {
125            return self.schema.get_table_id(&table_name);
126        }
127
128        let mut table = TableSchema::new(table_name, TableId(0));
129        table.create_statement = Some(stmt.to_string());
130
131        // Extract the body after the CREATE TABLE identifier.
132        let body = extract_table_body(stmt)?;
133
134        // Parse columns and constraints
135        parse_table_body(&body, &mut table);
136
137        // Add table to schema
138        Some(self.schema.add_table(table))
139    }
140
141    /// Parse an ALTER TABLE statement and update existing table
142    pub fn parse_alter_table(&mut self, stmt: &str) -> Option<TableId> {
143        let table_name = extract_alter_table_name(stmt)?;
144        let table_id = self.schema.get_table_id(&table_name)?;
145
146        // Parse any FK constraints added by ALTER TABLE
147        for fk in parse_foreign_keys(stmt) {
148            if let Some(table) = self.schema.table_mut(table_id) {
149                // Resolve column names to IDs
150                let mut resolved_fk = fk;
151                resolved_fk.columns = resolved_fk
152                    .column_names
153                    .iter()
154                    .filter_map(|name| table.get_column_id(name))
155                    .collect();
156                table.foreign_keys.push(resolved_fk);
157            }
158        }
159
160        Some(table_id)
161    }
162
163    /// Parse a CREATE INDEX statement and add to the appropriate table
164    pub fn parse_create_index(&mut self, stmt: &str) -> Option<TableId> {
165        let caps = CREATE_INDEX_RE.captures(stmt)?;
166
167        let is_unique = caps.get(1).is_some();
168        let index_name = caps.get(2)?.as_str().to_string();
169        let table_name = normalize_qualified_identifier(caps.get(3)?.as_str())?;
170        let index_type = caps.get(4).map(|m| m.as_str().to_uppercase());
171        let columns_str = caps.get(5)?.as_str();
172        let columns = parse_column_list(columns_str);
173
174        let table_id = self.schema.get_table_id(&table_name)?;
175
176        if let Some(table) = self.schema.table_mut(table_id) {
177            table.indexes.push(IndexDef {
178                name: index_name,
179                columns,
180                is_unique,
181                index_type,
182            });
183        }
184
185        Some(table_id)
186    }
187
188    /// Finalize the schema, resolving all FK references
189    pub fn build(mut self) -> Schema {
190        self.schema.resolve_foreign_keys();
191        self.schema
192    }
193
194    /// Get current schema (for inspection during building)
195    pub fn schema(&self) -> &Schema {
196        &self.schema
197    }
198}
199
200/// Extract table name from CREATE TABLE statement
201pub fn extract_create_table_name(stmt: &str) -> Option<String> {
202    CREATE_TABLE_NAME_RE
203        .captures(stmt)
204        .and_then(|c| c.get(1))
205        .and_then(|m| normalize_qualified_identifier(m.as_str()))
206}
207
208/// Extract table name from ALTER TABLE statement
209pub fn extract_alter_table_name(stmt: &str) -> Option<String> {
210    ALTER_TABLE_NAME_RE
211        .captures(stmt)
212        .and_then(|c| c.get(1))
213        .and_then(|m| normalize_qualified_identifier(m.as_str()))
214}
215
216/// Normalize a SQL table reference into a dotted, unquoted identity.
217///
218/// The schema graph uses this representation consistently for DDL, INSERT,
219/// and COPY routing, so `tenant_a.users` and `tenant_b.users` remain distinct.
220fn normalize_qualified_identifier(value: &str) -> Option<String> {
221    let bytes = value.as_bytes();
222    let mut i = 0;
223    let mut parts = Vec::new();
224
225    loop {
226        while bytes.get(i).is_some_and(u8::is_ascii_whitespace) {
227            i += 1;
228        }
229        if i >= bytes.len() {
230            break;
231        }
232
233        let (quote, close) = match bytes[i] {
234            b'`' => (Some(b'`'), b'`'),
235            b'"' => (Some(b'"'), b'"'),
236            b'[' => (Some(b'['), b']'),
237            _ => (None, 0),
238        };
239        if quote.is_some() {
240            i += 1;
241        }
242
243        let mut part = Vec::new();
244        let mut terminated = quote.is_none();
245        while i < bytes.len() {
246            let byte = bytes[i];
247            if let Some(open) = quote {
248                if byte == close {
249                    if bytes.get(i + 1) == Some(&close) {
250                        part.push(close);
251                        i += 2;
252                        continue;
253                    }
254                    i += 1;
255                    terminated = true;
256                    break;
257                }
258                // A backtick doubled inside an identifier and a doubled double
259                // quote both use the same close-byte escape handled above.
260                debug_assert!(open == b'`' || open == b'"' || open == b'[');
261                part.push(byte);
262                i += 1;
263            } else if byte == b'.' || byte.is_ascii_whitespace() {
264                break;
265            } else {
266                part.push(byte);
267                i += 1;
268            }
269        }
270
271        if !terminated || part.is_empty() {
272            return None;
273        }
274        parts.push(canonicalize_qualified_part(
275            String::from_utf8_lossy(&part).into_owned(),
276            quote.is_some(),
277        ));
278
279        while bytes.get(i).is_some_and(u8::is_ascii_whitespace) {
280            i += 1;
281        }
282        if bytes.get(i) == Some(&b'.') {
283            i += 1;
284            continue;
285        }
286        break;
287    }
288
289    (!parts.is_empty()).then(|| parts.join("."))
290}
291
292/// Preserve a quoted table-reference component containing a dot. The dotted
293/// schema identity uses unquoted dots as separators, so this marker lets the
294/// writer reconstruct `public."user.log"` without changing its meaning.
295fn canonicalize_qualified_part(part: String, was_quoted: bool) -> String {
296    if was_quoted && part.contains('.') {
297        format!("\"{}\"", part.replace('"', "\"\""))
298    } else {
299        part
300    }
301}
302
303/// Extract the body of a CREATE TABLE statement.
304///
305/// Start after the matched table name rather than at the first opening
306/// parenthesis in the statement. Dump comments commonly precede DDL and can
307/// themselves contain parentheses, for example `NVARCHAR(MAX)`.
308fn extract_table_body(stmt: &str) -> Option<String> {
309    let bytes = stmt.as_bytes();
310    let mut open = CREATE_TABLE_NAME_RE.find(stmt)?.end();
311
312    loop {
313        while bytes.get(open).is_some_and(u8::is_ascii_whitespace) {
314            open += 1;
315        }
316
317        if bytes.get(open..open + 2) == Some(b"--") {
318            open = bytes[open + 2..]
319                .iter()
320                .position(|&byte| byte == b'\n')
321                .map_or(bytes.len(), |offset| open + 2 + offset + 1);
322            continue;
323        }
324
325        if bytes.get(open..open + 2) == Some(b"/*") {
326            let end = bytes[open + 2..]
327                .windows(2)
328                .position(|window| window == b"*/")?;
329            open += end + 4;
330            continue;
331        }
332
333        break;
334    }
335
336    if bytes.get(open) != Some(&b'(') {
337        return None;
338    }
339
340    let start = open + 1;
341    let mut depth = 1i32;
342    let mut in_string = false;
343    let mut escape_next = false;
344
345    for (i, &b) in bytes.iter().enumerate().skip(start) {
346        if escape_next {
347            escape_next = false;
348            continue;
349        }
350
351        if b == b'\\' && in_string {
352            escape_next = true;
353            continue;
354        }
355
356        if b == b'\'' {
357            in_string = !in_string;
358            continue;
359        }
360
361        if in_string {
362            continue;
363        }
364
365        if b == b'(' {
366            depth += 1;
367        } else if b == b')' {
368            depth -= 1;
369            if depth == 0 {
370                return Some(stmt[start..i].to_string());
371            }
372        }
373    }
374
375    None
376}
377
378/// Parse the body of a CREATE TABLE to extract columns and constraints
379fn parse_table_body(body: &str, table: &mut TableSchema) {
380    // Split by commas, but respect nested parentheses
381    let parts = split_table_body(body);
382
383    for part in parts {
384        let trimmed = part.trim();
385        if trimmed.is_empty() {
386            continue;
387        }
388
389        // Check if this is a constraint or a column
390        let upper = trimmed.to_uppercase();
391        if upper.starts_with("PRIMARY KEY")
392            || upper.starts_with("CONSTRAINT")
393            || upper.starts_with("FOREIGN KEY")
394            || upper.starts_with("KEY ")
395            || upper.starts_with("INDEX ")
396            || upper.starts_with("UNIQUE ")
397            || upper.starts_with("FULLTEXT ")
398            || upper.starts_with("SPATIAL ")
399            || upper.starts_with("CHECK ")
400        {
401            // Parse constraints
402            if let Some(pk_cols) = parse_primary_key_constraint(trimmed) {
403                for col_name in pk_cols {
404                    if let Some(col) = table
405                        .columns
406                        .iter_mut()
407                        .find(|c| c.name.eq_ignore_ascii_case(&col_name))
408                    {
409                        col.is_primary_key = true;
410                        if !table.primary_key.contains(&col.ordinal) {
411                            table.primary_key.push(col.ordinal);
412                        }
413                    }
414                }
415            }
416
417            for fk in parse_foreign_keys(trimmed) {
418                let mut resolved_fk = fk;
419                resolved_fk.columns = resolved_fk
420                    .column_names
421                    .iter()
422                    .filter_map(|name| table.get_column_id(name))
423                    .collect();
424                table.foreign_keys.push(resolved_fk);
425            }
426
427            // Parse inline indexes (INDEX, KEY, UNIQUE INDEX, UNIQUE KEY)
428            if let Some(idx) = parse_inline_index(trimmed) {
429                table.indexes.push(idx);
430            }
431
432            // Parse a bare table-level UNIQUE (col, ...) constraint, marking a
433            // single covered column as unique too.
434            if let Some(uc) = parse_unique_constraint(trimmed) {
435                if let [only_column] = uc.columns.as_slice() {
436                    if let Some(col) = table
437                        .columns
438                        .iter_mut()
439                        .find(|c| c.name.eq_ignore_ascii_case(only_column))
440                    {
441                        col.is_unique = true;
442                    }
443                }
444                table.unique_constraints.push(uc);
445            }
446
447            // Parse a table-level CHECK (...) constraint
448            if let Some(cc) = parse_check_constraint(trimmed) {
449                table.check_constraints.push(cc);
450            }
451        } else {
452            // Parse column definition
453            if let Some((col, inline_check)) =
454                parse_column_def(trimmed, ColumnId(table.columns.len() as u16))
455            {
456                if let Some(expression) = inline_check {
457                    table.check_constraints.push(CheckConstraint {
458                        name: None,
459                        expression,
460                    });
461                }
462
463                // Check for inline PRIMARY KEY
464                if INLINE_PRIMARY_KEY_RE.is_match(trimmed) {
465                    let mut col = col;
466                    col.is_primary_key = true;
467                    table.primary_key.push(col.ordinal);
468                    table.columns.push(col);
469                } else {
470                    table.columns.push(col);
471                }
472            }
473        }
474    }
475}
476
477/// Split table body by commas, respecting nested parentheses
478pub fn split_table_body(body: &str) -> Vec<String> {
479    let mut parts = Vec::new();
480    let mut current = String::new();
481    let mut depth = 0;
482    let mut in_string = false;
483    let mut escape_next = false;
484
485    for ch in body.chars() {
486        if escape_next {
487            current.push(ch);
488            escape_next = false;
489            continue;
490        }
491
492        if ch == '\\' && in_string {
493            current.push(ch);
494            escape_next = true;
495            continue;
496        }
497
498        if ch == '\'' {
499            in_string = !in_string;
500            current.push(ch);
501            continue;
502        }
503
504        if in_string {
505            current.push(ch);
506            continue;
507        }
508
509        match ch {
510            '(' => {
511                depth += 1;
512                current.push(ch);
513            }
514            ')' => {
515                depth -= 1;
516                current.push(ch);
517            }
518            ',' if depth == 0 => {
519                parts.push(current.trim().to_string());
520                current = String::new();
521            }
522            _ => {
523                current.push(ch);
524            }
525        }
526    }
527
528    if !current.trim().is_empty() {
529        parts.push(current.trim().to_string());
530    }
531
532    parts
533}
534
535/// Parse a column definition, returning the column plus any inline
536/// column-level CHECK expression found among its modifiers (callers attach
537/// that to the table's check constraints, since `Column` has no such field).
538fn parse_column_def(def: &str, ordinal: ColumnId) -> Option<(Column, Option<String>)> {
539    let caps = COLUMN_DEF_RE.captures(def)?;
540    let whole = caps.get(0)?;
541    let name = caps.get(1)?.as_str().to_string();
542    let type_str = parse_column_type(caps.get(2)?.as_str(), &def[whole.end()..]);
543
544    let col_type = ColumnType::from_mysql_type(&type_str);
545    let is_nullable = !NOT_NULL_RE.is_match(def);
546
547    let remainder = &def[whole.end()..];
548    let modifiers = parse_column_modifiers(remainder);
549    // PostgreSQL `serial`/`bigserial`/`smallserial` columns are backed by an
550    // implicit sequence, so they carry identity semantics even without an
551    // explicit IDENTITY/AUTO_INCREMENT modifier.
552    let is_identity = modifiers.is_identity || type_str.to_lowercase().contains("serial");
553
554    let column = Column {
555        name,
556        col_type,
557        source_type: type_str,
558        ordinal,
559        is_primary_key: false,
560        is_nullable,
561        is_unique: modifiers.is_unique,
562        default_sql: modifiers.default_sql,
563        is_generated: modifiers.is_generated,
564        is_identity,
565        collation: modifiers.collation,
566    };
567
568    Some((column, modifiers.inline_check))
569}
570
571/// Extend the first type token captured by [`COLUMN_DEF_RE`] through any
572/// following type words. The DDL tokenizer keeps parameter lists atomic, so
573/// this preserves types such as `DOUBLE PRECISION`, `CHARACTER VARYING(42)`,
574/// and `TIMESTAMP(6) WITH TIME ZONE` without consuming column modifiers.
575fn parse_column_type(first: &str, remainder: &str) -> String {
576    let tokens = tokenize_ddl(remainder);
577    let mut parts = vec![first];
578    for (index, token) in tokens.iter().enumerate() {
579        if starts_column_modifier(&tokens, index) {
580            break;
581        }
582        parts.push(token);
583    }
584    parts.join(" ")
585}
586
587fn starts_column_modifier(tokens: &[String], index: usize) -> bool {
588    let token = tokens[index].to_ascii_uppercase();
589    if token == "CHARACTER"
590        && tokens
591            .get(index + 1)
592            .is_some_and(|next| next.eq_ignore_ascii_case("SET"))
593    {
594        return true;
595    }
596
597    matches!(
598        token.as_str(),
599        "NOT"
600            | "NULL"
601            | "PRIMARY"
602            | "UNIQUE"
603            | "DEFAULT"
604            | "CHECK"
605            | "GENERATED"
606            | "AS"
607            | "AUTO_INCREMENT"
608            | "AUTOINCREMENT"
609            | "AUTO_RANDOM"
610            | "IDENTITY"
611            | "COLLATE"
612            | "CONSTRAINT"
613            | "REFERENCES"
614            | "COMMENT"
615            | "ON"
616            | "BINARY"
617            | "ASCII"
618            | "UNICODE"
619            | "BYTE"
620            | "VISIBLE"
621            | "INVISIBLE"
622            | "COLUMN_FORMAT"
623            | "ENGINE_ATTRIBUTE"
624            | "SECONDARY_ENGINE_ATTRIBUTE"
625            | "STORAGE"
626            | "SRID"
627            | "SPARSE"
628            | "FILESTREAM"
629            | "ROWGUIDCOL"
630            | "HIDDEN"
631            | "MASKED"
632            | "PERSISTED"
633            | "ENCRYPTED"
634            | "COMPRESSION"
635            | "KEY"
636    ) || token.starts_with("IDENTITY(")
637}
638
639/// Modifiers found after a column's name and type: UNIQUE, DEFAULT,
640/// GENERATED .. AS (...), IDENTITY/AUTO_INCREMENT, COLLATE, and inline CHECK.
641#[derive(Debug, Default)]
642struct ColumnModifiers {
643    is_unique: bool,
644    default_sql: Option<String>,
645    is_generated: bool,
646    is_identity: bool,
647    collation: Option<String>,
648    inline_check: Option<String>,
649}
650
651/// Parse the column modifiers following the name/type, using
652/// [`tokenize_ddl`] so that quoted defaults and parenthesized expressions
653/// (e.g. `DEFAULT 'active'`, `CHECK (a > 0 AND (b < 1))`) are kept intact
654/// rather than split on whitespace.
655fn parse_column_modifiers(remainder: &str) -> ColumnModifiers {
656    let tokens = tokenize_ddl(remainder);
657    let mut modifiers = ColumnModifiers::default();
658    let mut i = 0;
659
660    while i < tokens.len() {
661        let upper = tokens[i].to_uppercase();
662        match upper.as_str() {
663            "UNIQUE" => {
664                modifiers.is_unique = true;
665                i += 1;
666            }
667            "DEFAULT" => {
668                if let Some(value) = tokens.get(i + 1) {
669                    modifiers.default_sql = Some(value.clone());
670                    i += 2;
671                } else {
672                    i += 1;
673                }
674            }
675            "COLLATE" => {
676                if let Some(value) = tokens.get(i + 1) {
677                    modifiers.collation = Some(strip_quotes(value));
678                    i += 2;
679                } else {
680                    i += 1;
681                }
682            }
683            "CHECK" => {
684                if let Some(expr) = tokens.get(i + 1) {
685                    modifiers.inline_check = Some(strip_outer_parens(expr));
686                    i += 2;
687                } else {
688                    i += 1;
689                }
690            }
691            "GENERATED" => {
692                // Skip ALWAYS/BY/DEFAULT until AS, then inspect what follows:
693                // `AS (expr)` is a computed column, `AS IDENTITY` is identity.
694                let mut j = i + 1;
695                while j < tokens.len() && !tokens[j].eq_ignore_ascii_case("AS") {
696                    j += 1;
697                }
698                if let Some(as_expr) = tokens.get(j + 1) {
699                    if as_expr.starts_with('(') {
700                        modifiers.is_generated = true;
701                    } else if as_expr.eq_ignore_ascii_case("IDENTITY") {
702                        modifiers.is_identity = true;
703                    }
704                }
705                i = j + 2;
706            }
707            "AS" => {
708                if tokens
709                    .get(i + 1)
710                    .is_some_and(|expression| expression.starts_with('('))
711                {
712                    modifiers.is_generated = true;
713                    i += 2;
714                } else {
715                    i += 1;
716                }
717            }
718            "AUTO_INCREMENT" | "AUTOINCREMENT" => {
719                modifiers.is_identity = true;
720                i += 1;
721            }
722            _ if upper.starts_with("IDENTITY(") || upper == "IDENTITY" => {
723                modifiers.is_identity = true;
724                i += 1;
725            }
726            _ => {
727                i += 1;
728            }
729        }
730    }
731
732    modifiers
733}
734
735/// Split a fragment of DDL into whitespace-separated tokens, treating
736/// single-quoted strings and parenthesized groups (including nested
737/// parentheses) as atomic units. This lets callers pull out `DEFAULT`,
738/// `CHECK`, and `GENERATED ... AS (...)` values without splitting the SQL
739/// expressions they contain on internal whitespace.
740fn tokenize_ddl(s: &str) -> Vec<String> {
741    let mut tokens = Vec::new();
742    let mut current = String::new();
743    let mut depth = 0u32;
744    let mut in_string = false;
745    let mut escape_next = false;
746
747    for ch in s.chars() {
748        if escape_next {
749            current.push(ch);
750            escape_next = false;
751            continue;
752        }
753
754        if ch == '\\' && in_string {
755            current.push(ch);
756            escape_next = true;
757            continue;
758        }
759
760        if ch == '\'' {
761            in_string = !in_string;
762            current.push(ch);
763            continue;
764        }
765
766        if in_string {
767            current.push(ch);
768            continue;
769        }
770
771        match ch {
772            '(' => {
773                depth += 1;
774                current.push(ch);
775            }
776            ')' => {
777                depth = depth.saturating_sub(1);
778                current.push(ch);
779            }
780            c if c.is_whitespace() && depth == 0 => {
781                if !current.is_empty() {
782                    tokens.push(std::mem::take(&mut current));
783                }
784            }
785            _ => current.push(ch),
786        }
787    }
788
789    if !current.is_empty() {
790        tokens.push(current);
791    }
792
793    tokens
794}
795
796/// Strip surrounding quote/bracket characters from an identifier-like token
797fn strip_quotes(s: &str) -> String {
798    s.trim_matches('\'')
799        .trim_matches('"')
800        .trim_matches('`')
801        .trim_matches('[')
802        .trim_matches(']')
803        .to_string()
804}
805
806/// Strip a single layer of enclosing parentheses from an expression token,
807/// if present (used to store CHECK expressions without the outer parens).
808fn strip_outer_parens(s: &str) -> String {
809    let trimmed = s.trim();
810    match trimmed
811        .strip_prefix('(')
812        .and_then(|rest| rest.strip_suffix(')'))
813    {
814        Some(inner) => inner.trim().to_string(),
815        None => trimmed.to_string(),
816    }
817}
818
819/// Parse a table-level UNIQUE constraint: `[CONSTRAINT name] UNIQUE (cols)`.
820/// Does not match `UNIQUE INDEX`/`UNIQUE KEY` forms, which are handled by
821/// [`parse_inline_index`].
822fn parse_unique_constraint(constraint: &str) -> Option<UniqueConstraint> {
823    let tokens = tokenize_ddl(constraint);
824    let mut i = 0;
825    let mut name = None;
826
827    if tokens.first()?.eq_ignore_ascii_case("CONSTRAINT") {
828        name = tokens.get(1).map(|s| strip_quotes(s));
829        i = 2;
830    }
831
832    if !tokens.get(i)?.eq_ignore_ascii_case("UNIQUE") {
833        return None;
834    }
835
836    let cols_token = tokens.get(i + 1)?;
837    if !cols_token.starts_with('(') {
838        // Not a bare `UNIQUE (cols)` constraint (e.g. `UNIQUE INDEX ...` or
839        // `UNIQUE KEY ...`, handled separately by `parse_inline_index`).
840        return None;
841    }
842    let columns = parse_column_list(strip_outer_parens(cols_token).as_str());
843    if columns.is_empty() {
844        return None;
845    }
846
847    Some(UniqueConstraint { name, columns })
848}
849
850/// Parse a table-level CHECK constraint: `[CONSTRAINT name] CHECK (expr)`.
851fn parse_check_constraint(constraint: &str) -> Option<CheckConstraint> {
852    let tokens = tokenize_ddl(constraint);
853    let mut i = 0;
854    let mut name = None;
855
856    if tokens.first()?.eq_ignore_ascii_case("CONSTRAINT") {
857        name = tokens.get(1).map(|s| strip_quotes(s));
858        i = 2;
859    }
860
861    if !tokens.get(i)?.eq_ignore_ascii_case("CHECK") {
862        return None;
863    }
864
865    let expr_token = tokens.get(i + 1)?;
866    if !expr_token.starts_with('(') {
867        return None;
868    }
869
870    Some(CheckConstraint {
871        name,
872        expression: strip_outer_parens(expr_token),
873    })
874}
875
876/// Parse PRIMARY KEY constraint, returns column names
877fn parse_primary_key_constraint(constraint: &str) -> Option<Vec<String>> {
878    let caps = PRIMARY_KEY_RE.captures(constraint)?;
879    let cols_str = caps.get(1)?.as_str();
880    Some(parse_column_list(cols_str))
881}
882
883/// Parse inline INDEX/KEY constraint from CREATE TABLE body
884fn parse_inline_index(constraint: &str) -> Option<IndexDef> {
885    let caps = INLINE_INDEX_RE.captures(constraint)?;
886
887    let is_unique = caps.get(1).is_some();
888    let index_name = caps.get(2)?.as_str().to_string();
889    let columns_str = caps.get(3)?.as_str();
890    let columns = parse_column_list(columns_str);
891
892    Some(IndexDef {
893        name: index_name,
894        columns,
895        is_unique,
896        index_type: None, // Inline indexes don't specify type
897    })
898}
899
900/// Parse FOREIGN KEY constraints from a statement
901fn parse_foreign_keys(stmt: &str) -> Vec<ForeignKey> {
902    let mut fks = Vec::new();
903
904    for caps in FOREIGN_KEY_RE.captures_iter(stmt) {
905        let name = caps.get(1).map(|m| m.as_str().to_string());
906        let local_cols = caps
907            .get(2)
908            .map(|m| parse_column_list(m.as_str()))
909            .unwrap_or_default();
910        let ref_table = caps
911            .get(3)
912            .and_then(|m| normalize_qualified_identifier(m.as_str()))
913            .unwrap_or_default();
914        let ref_cols = caps
915            .get(4)
916            .map(|m| parse_column_list(m.as_str()))
917            .unwrap_or_default();
918
919        if !local_cols.is_empty() && !ref_table.is_empty() && !ref_cols.is_empty() {
920            fks.push(ForeignKey {
921                name,
922                columns: Vec::new(), // Will be resolved later
923                column_names: local_cols,
924                referenced_table: ref_table,
925                referenced_columns: ref_cols,
926                referenced_table_id: None,
927            });
928        }
929    }
930
931    fks
932}
933
934/// Parse a comma-separated column list, stripping quotes (backticks, double quotes, brackets)
935pub fn parse_column_list(s: &str) -> Vec<String> {
936    s.split(',')
937        .map(|c| {
938            c.trim()
939                .trim_matches('`')
940                .trim_matches('"')
941                .trim_matches('[')
942                .trim_matches(']')
943                .to_string()
944        })
945        .filter(|c| !c.is_empty())
946        .collect()
947}
948
949#[cfg(test)]
950mod tests {
951    use super::*;
952
953    #[test]
954    fn preserves_qualified_table_names_in_schema() {
955        let mut builder = SchemaBuilder::new();
956        builder.parse_create_table("CREATE TABLE tenant_a.users (id INT PRIMARY KEY);");
957        builder.parse_create_table("CREATE TABLE tenant_b.users (id INT PRIMARY KEY);");
958        let schema = builder.build();
959
960        assert_eq!(schema.len(), 2);
961        assert!(schema.get_table("tenant_a.users").is_some());
962        assert!(schema.get_table("tenant_b.users").is_some());
963    }
964
965    #[test]
966    fn resolves_qualified_foreign_keys_and_indexes() {
967        let mut builder = SchemaBuilder::new();
968        builder.parse_create_table("CREATE TABLE \"tenant_a\".\"parents\" (id INT PRIMARY KEY);");
969        builder.parse_create_table(
970            "CREATE TABLE \"tenant_a\".\"children\" (\
971                id INT PRIMARY KEY, parent_id INT, \
972                FOREIGN KEY (parent_id) REFERENCES \"tenant_a\".\"parents\" (id)\
973            );",
974        );
975        builder.parse_create_index(
976            "CREATE INDEX children_parent_idx ON \"tenant_a\".\"children\" (parent_id);",
977        );
978        let schema = builder.build();
979
980        let parent = schema.get_table_id("tenant_a.parents").unwrap();
981        let child = schema.get_table("tenant_a.children").unwrap();
982        assert_eq!(child.foreign_keys[0].referenced_table, "tenant_a.parents");
983        assert_eq!(child.foreign_keys[0].referenced_table_id, Some(parent));
984        assert_eq!(child.indexes[0].name, "children_parent_idx");
985    }
986
987    #[test]
988    fn extracts_quoted_qualified_table_names() {
989        assert_eq!(
990            extract_create_table_name("CREATE TABLE \"tenant_a\".\"users\" (id INT);"),
991            Some("tenant_a.users".to_string())
992        );
993        assert_eq!(
994            extract_alter_table_name("ALTER TABLE [tenant_a].[users] ADD COLUMN email TEXT;"),
995            Some("tenant_a.users".to_string())
996        );
997        assert_eq!(
998            extract_create_table_name("CREATE TABLE public.\"user.log\" (id INT);"),
999            Some("public.\"user.log\"".to_string())
1000        );
1001    }
1002
1003    #[test]
1004    fn parses_ddl_after_parenthesized_leading_comment() {
1005        let mut builder = SchemaBuilder::new();
1006        builder.parse_create_table(
1007            "-- Converted type: NVARCHAR(MAX)\n\
1008             CREATE TABLE users (\n\
1009               id INTEGER NOT NULL,\n\
1010               PRIMARY KEY (id)\n\
1011             );",
1012        );
1013
1014        let schema = builder.build();
1015        let users = schema.get_table("users").expect("users table");
1016        assert_eq!(users.primary_key.len(), 1);
1017        assert_eq!(users.columns[0].name, "id");
1018    }
1019}