sql_splitter/schema/
ddl.rs1use super::{
9 CheckConstraint, Column, ColumnId, ColumnType, ForeignKey, IndexDef, Schema, TableId,
10 TableSchema, UniqueConstraint,
11};
12use once_cell::sync::Lazy;
13use regex::Regex;
14
15static CREATE_TABLE_NAME_RE: Lazy<Regex> = Lazy::new(|| {
18 Regex::new(r#"(?i)CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:[\[\]`"\w]+\s*\.\s*)*[\[`"]?([^\[\]`"\s(]+)[\]`"]?"#)
21 .unwrap()
22});
23
24static 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
33static COLUMN_DEF_RE: Lazy<Regex> = Lazy::new(|| {
36 Regex::new(r#"^\s*[\[`"]?([^\[\]`"\s,]+)[\]`"]?\s+(\w+(?:\([^)]+\))?(?:\s+unsigned)?)"#)
37 .unwrap()
38});
39
40static PRIMARY_KEY_RE: Lazy<Regex> = Lazy::new(|| {
43 Regex::new(r"(?i)PRIMARY\s+KEY\s*(?:CLUSTERED\s+|NONCLUSTERED\s+)?\(([^)]+)\)").unwrap()
44});
45
46static INLINE_PRIMARY_KEY_RE: Lazy<Regex> =
48 Lazy::new(|| Regex::new(r"(?i)\bPRIMARY\s+KEY\b").unwrap());
49
50static 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
59static NOT_NULL_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bNOT\s+NULL\b").unwrap());
61
62static INLINE_INDEX_RE: Lazy<Regex> = Lazy::new(|| {
66 Regex::new(r#"(?i)(?:(UNIQUE)\s+)?(?:INDEX|KEY)\s+[\[`"]?(\w+)[\]`"]?\s*\(([^)]+)\)"#).unwrap()
67});
68
69static 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#[derive(Debug, Default)]
81pub struct SchemaBuilder {
82 schema: Schema,
83}
84
85impl SchemaBuilder {
86 pub fn new() -> Self {
88 Self {
89 schema: Schema::new(),
90 }
91 }
92
93 pub fn parse_create_table(&mut self, stmt: &str) -> Option<TableId> {
95 let table_name = extract_create_table_name(stmt)?;
96
97 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 let body = extract_table_body(stmt)?;
107
108 parse_table_body(&body, &mut table);
110
111 Some(self.schema.add_table(table))
113 }
114
115 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 for fk in parse_foreign_keys(stmt) {
122 if let Some(table) = self.schema.table_mut(table_id) {
123 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 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 pub fn build(mut self) -> Schema {
164 self.schema.resolve_foreign_keys();
165 self.schema
166 }
167
168 pub fn schema(&self) -> &Schema {
170 &self.schema
171 }
172}
173
174pub 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
182pub 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
190fn 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
236fn parse_table_body(body: &str, table: &mut TableSchema) {
238 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 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 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 if let Some(idx) = parse_inline_index(trimmed) {
287 table.indexes.push(idx);
288 }
289
290 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 if let Some(cc) = parse_check_constraint(trimmed) {
307 table.check_constraints.push(cc);
308 }
309 } else {
310 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 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
335pub 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
393fn 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 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#[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
441fn 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 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
514fn 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
575fn 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
585fn 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
598fn 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 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
629fn 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
655fn 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
662fn 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, })
677}
678
679fn 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(), 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
713pub 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}