use super::{
CheckConstraint, Column, ColumnId, ColumnType, ForeignKey, IndexDef, Schema, TableId,
TableSchema, UniqueConstraint,
};
use once_cell::sync::Lazy;
use regex::Regex;
static CREATE_TABLE_NAME_RE: Lazy<Regex> = Lazy::new(|| {
Regex::new(
r#"(?ix)
CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?
(
(?:(?:\[(?:[^\]]|\]\])*\]|`(?:[^`]|``)*`|"(?:[^"]|"")*"|[^\s().,;]+)\s*\.\s*)*
(?:\[(?:[^\]]|\]\])*\]|`(?:[^`]|``)*`|"(?:[^"]|"")*"|[^\s().,;]+)
)
"#,
)
.unwrap()
});
static ALTER_TABLE_NAME_RE: Lazy<Regex> = Lazy::new(|| {
Regex::new(
r#"(?ix)
ALTER\s+TABLE\s+(?:ONLY\s+)?
(
(?:(?:\[(?:[^\]]|\]\])*\]|`(?:[^`]|``)*`|"(?:[^"]|"")*"|[^\s().,;]+)\s*\.\s*)*
(?:\[(?:[^\]]|\]\])*\]|`(?:[^`]|``)*`|"(?:[^"]|"")*"|[^\s().,;]+)
)
"#,
)
.unwrap()
});
static COLUMN_DEF_RE: Lazy<Regex> = Lazy::new(|| {
Regex::new(r#"^\s*[\[`"]?([^\[\]`"\s,]+)[\]`"]?\s+(\w+(?:\([^)]+\))?(?:\s+unsigned)?)"#)
.unwrap()
});
static PRIMARY_KEY_RE: Lazy<Regex> = Lazy::new(|| {
Regex::new(r"(?i)PRIMARY\s+KEY\s*(?:CLUSTERED\s+|NONCLUSTERED\s+)?\(([^)]+)\)").unwrap()
});
static INLINE_PRIMARY_KEY_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r"(?i)\bPRIMARY\s+KEY\b").unwrap());
static FOREIGN_KEY_RE: Lazy<Regex> = Lazy::new(|| {
Regex::new(
r#"(?ix)
(?:CONSTRAINT\s+[\[`"]?([^\[\]`"\s]+)[\]`"]?\s+)?
FOREIGN\s+KEY\s*\(([^)]+)\)\s*REFERENCES\s+
(
(?:(?:\[(?:[^\]]|\]\])*\]|`(?:[^`]|``)*`|"(?:[^"]|"")*"|[^\s().,;]+)\s*\.\s*)*
(?:\[(?:[^\]]|\]\])*\]|`(?:[^`]|``)*`|"(?:[^"]|"")*"|[^\s().,;]+)
)\s*\(([^)]+)\)
"#,
)
.unwrap()
});
static NOT_NULL_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\bNOT\s+NULL\b").unwrap());
static INLINE_INDEX_RE: Lazy<Regex> = Lazy::new(|| {
Regex::new(r#"(?i)(?:(UNIQUE)\s+)?(?:INDEX|KEY)\s+[\[`"]?(\w+)[\]`"]?\s*\(([^)]+)\)"#).unwrap()
});
static CREATE_INDEX_RE: Lazy<Regex> = Lazy::new(|| {
Regex::new(
r#"(?ix)
CREATE\s+(UNIQUE\s+)?(?:CLUSTERED\s+|NONCLUSTERED\s+)?INDEX\s+
(?:IF\s+NOT\s+EXISTS\s+)?[\[`"]?(\w+)[\]`"]?\s+ON\s+
(
(?:(?:\[(?:[^\]]|\]\])*\]|`(?:[^`]|``)*`|"(?:[^"]|"")*"|[^\s().,;]+)\s*\.\s*)*
(?:\[(?:[^\]]|\]\])*\]|`(?:[^`]|``)*`|"(?:[^"]|"")*"|[^\s().,;]+)
)\s*(?:USING\s+(\w+)\s*)?\(([^)]+)\)
"#,
)
.unwrap()
});
#[derive(Debug, Default)]
pub struct SchemaBuilder {
schema: Schema,
}
impl SchemaBuilder {
pub fn new() -> Self {
Self {
schema: Schema::new(),
}
}
pub fn parse_create_table(&mut self, stmt: &str) -> Option<TableId> {
let table_name = extract_create_table_name(stmt)?;
if self.schema.get_table_id(&table_name).is_some() {
return self.schema.get_table_id(&table_name);
}
let mut table = TableSchema::new(table_name, TableId(0));
table.create_statement = Some(stmt.to_string());
let body = extract_table_body(stmt)?;
parse_table_body(&body, &mut table);
Some(self.schema.add_table(table))
}
pub fn parse_alter_table(&mut self, stmt: &str) -> Option<TableId> {
let table_name = extract_alter_table_name(stmt)?;
let table_id = self.schema.get_table_id(&table_name)?;
for fk in parse_foreign_keys(stmt) {
if let Some(table) = self.schema.table_mut(table_id) {
let mut resolved_fk = fk;
resolved_fk.columns = resolved_fk
.column_names
.iter()
.filter_map(|name| table.get_column_id(name))
.collect();
table.foreign_keys.push(resolved_fk);
}
}
Some(table_id)
}
pub fn parse_create_index(&mut self, stmt: &str) -> Option<TableId> {
let caps = CREATE_INDEX_RE.captures(stmt)?;
let is_unique = caps.get(1).is_some();
let index_name = caps.get(2)?.as_str().to_string();
let table_name = normalize_qualified_identifier(caps.get(3)?.as_str())?;
let index_type = caps.get(4).map(|m| m.as_str().to_uppercase());
let columns_str = caps.get(5)?.as_str();
let columns = parse_column_list(columns_str);
let table_id = self.schema.get_table_id(&table_name)?;
if let Some(table) = self.schema.table_mut(table_id) {
table.indexes.push(IndexDef {
name: index_name,
columns,
is_unique,
index_type,
});
}
Some(table_id)
}
pub fn build(mut self) -> Schema {
self.schema.resolve_foreign_keys();
self.schema
}
pub fn schema(&self) -> &Schema {
&self.schema
}
}
pub fn extract_create_table_name(stmt: &str) -> Option<String> {
CREATE_TABLE_NAME_RE
.captures(stmt)
.and_then(|c| c.get(1))
.and_then(|m| normalize_qualified_identifier(m.as_str()))
}
pub fn extract_alter_table_name(stmt: &str) -> Option<String> {
ALTER_TABLE_NAME_RE
.captures(stmt)
.and_then(|c| c.get(1))
.and_then(|m| normalize_qualified_identifier(m.as_str()))
}
fn normalize_qualified_identifier(value: &str) -> Option<String> {
let bytes = value.as_bytes();
let mut i = 0;
let mut parts = Vec::new();
loop {
while bytes.get(i).is_some_and(u8::is_ascii_whitespace) {
i += 1;
}
if i >= bytes.len() {
break;
}
let (quote, close) = match bytes[i] {
b'`' => (Some(b'`'), b'`'),
b'"' => (Some(b'"'), b'"'),
b'[' => (Some(b'['), b']'),
_ => (None, 0),
};
if quote.is_some() {
i += 1;
}
let mut part = Vec::new();
let mut terminated = quote.is_none();
while i < bytes.len() {
let byte = bytes[i];
if let Some(open) = quote {
if byte == close {
if bytes.get(i + 1) == Some(&close) {
part.push(close);
i += 2;
continue;
}
i += 1;
terminated = true;
break;
}
debug_assert!(open == b'`' || open == b'"' || open == b'[');
part.push(byte);
i += 1;
} else if byte == b'.' || byte.is_ascii_whitespace() {
break;
} else {
part.push(byte);
i += 1;
}
}
if !terminated || part.is_empty() {
return None;
}
parts.push(canonicalize_qualified_part(
String::from_utf8_lossy(&part).into_owned(),
quote.is_some(),
));
while bytes.get(i).is_some_and(u8::is_ascii_whitespace) {
i += 1;
}
if bytes.get(i) == Some(&b'.') {
i += 1;
continue;
}
break;
}
(!parts.is_empty()).then(|| parts.join("."))
}
fn canonicalize_qualified_part(part: String, was_quoted: bool) -> String {
if was_quoted && part.contains('.') {
format!("\"{}\"", part.replace('"', "\"\""))
} else {
part
}
}
fn extract_table_body(stmt: &str) -> Option<String> {
let bytes = stmt.as_bytes();
let mut open = CREATE_TABLE_NAME_RE.find(stmt)?.end();
loop {
while bytes.get(open).is_some_and(u8::is_ascii_whitespace) {
open += 1;
}
if bytes.get(open..open + 2) == Some(b"--") {
open = bytes[open + 2..]
.iter()
.position(|&byte| byte == b'\n')
.map_or(bytes.len(), |offset| open + 2 + offset + 1);
continue;
}
if bytes.get(open..open + 2) == Some(b"/*") {
let end = bytes[open + 2..]
.windows(2)
.position(|window| window == b"*/")?;
open += end + 4;
continue;
}
break;
}
if bytes.get(open) != Some(&b'(') {
return None;
}
let start = open + 1;
let mut depth = 1i32;
let mut in_string = false;
let mut escape_next = false;
for (i, &b) in bytes.iter().enumerate().skip(start) {
if escape_next {
escape_next = false;
continue;
}
if b == b'\\' && in_string {
escape_next = true;
continue;
}
if b == b'\'' {
in_string = !in_string;
continue;
}
if in_string {
continue;
}
if b == b'(' {
depth += 1;
} else if b == b')' {
depth -= 1;
if depth == 0 {
return Some(stmt[start..i].to_string());
}
}
}
None
}
fn parse_table_body(body: &str, table: &mut TableSchema) {
let parts = split_table_body(body);
for part in parts {
let trimmed = part.trim();
if trimmed.is_empty() {
continue;
}
let upper = trimmed.to_uppercase();
if upper.starts_with("PRIMARY KEY")
|| upper.starts_with("CONSTRAINT")
|| upper.starts_with("FOREIGN KEY")
|| upper.starts_with("KEY ")
|| upper.starts_with("INDEX ")
|| upper.starts_with("UNIQUE ")
|| upper.starts_with("FULLTEXT ")
|| upper.starts_with("SPATIAL ")
|| upper.starts_with("CHECK ")
{
if let Some(pk_cols) = parse_primary_key_constraint(trimmed) {
for col_name in pk_cols {
if let Some(col) = table
.columns
.iter_mut()
.find(|c| c.name.eq_ignore_ascii_case(&col_name))
{
col.is_primary_key = true;
if !table.primary_key.contains(&col.ordinal) {
table.primary_key.push(col.ordinal);
}
}
}
}
for fk in parse_foreign_keys(trimmed) {
let mut resolved_fk = fk;
resolved_fk.columns = resolved_fk
.column_names
.iter()
.filter_map(|name| table.get_column_id(name))
.collect();
table.foreign_keys.push(resolved_fk);
}
if let Some(idx) = parse_inline_index(trimmed) {
table.indexes.push(idx);
}
if let Some(uc) = parse_unique_constraint(trimmed) {
if let [only_column] = uc.columns.as_slice() {
if let Some(col) = table
.columns
.iter_mut()
.find(|c| c.name.eq_ignore_ascii_case(only_column))
{
col.is_unique = true;
}
}
table.unique_constraints.push(uc);
}
if let Some(cc) = parse_check_constraint(trimmed) {
table.check_constraints.push(cc);
}
} else {
if let Some((col, inline_check)) =
parse_column_def(trimmed, ColumnId(table.columns.len() as u16))
{
if let Some(expression) = inline_check {
table.check_constraints.push(CheckConstraint {
name: None,
expression,
});
}
if INLINE_PRIMARY_KEY_RE.is_match(trimmed) {
let mut col = col;
col.is_primary_key = true;
table.primary_key.push(col.ordinal);
table.columns.push(col);
} else {
table.columns.push(col);
}
}
}
}
}
pub fn split_table_body(body: &str) -> Vec<String> {
let mut parts = Vec::new();
let mut current = String::new();
let mut depth = 0;
let mut in_string = false;
let mut escape_next = false;
for ch in body.chars() {
if escape_next {
current.push(ch);
escape_next = false;
continue;
}
if ch == '\\' && in_string {
current.push(ch);
escape_next = true;
continue;
}
if ch == '\'' {
in_string = !in_string;
current.push(ch);
continue;
}
if in_string {
current.push(ch);
continue;
}
match ch {
'(' => {
depth += 1;
current.push(ch);
}
')' => {
depth -= 1;
current.push(ch);
}
',' if depth == 0 => {
parts.push(current.trim().to_string());
current = String::new();
}
_ => {
current.push(ch);
}
}
}
if !current.trim().is_empty() {
parts.push(current.trim().to_string());
}
parts
}
fn parse_column_def(def: &str, ordinal: ColumnId) -> Option<(Column, Option<String>)> {
let caps = COLUMN_DEF_RE.captures(def)?;
let whole = caps.get(0)?;
let name = caps.get(1)?.as_str().to_string();
let type_str = parse_column_type(caps.get(2)?.as_str(), &def[whole.end()..]);
let col_type = ColumnType::from_mysql_type(&type_str);
let is_nullable = !NOT_NULL_RE.is_match(def);
let remainder = &def[whole.end()..];
let modifiers = parse_column_modifiers(remainder);
let is_identity = modifiers.is_identity || type_str.to_lowercase().contains("serial");
let column = Column {
name,
col_type,
source_type: type_str,
ordinal,
is_primary_key: false,
is_nullable,
is_unique: modifiers.is_unique,
default_sql: modifiers.default_sql,
is_generated: modifiers.is_generated,
is_identity,
collation: modifiers.collation,
};
Some((column, modifiers.inline_check))
}
fn parse_column_type(first: &str, remainder: &str) -> String {
let tokens = tokenize_ddl(remainder);
let mut parts = vec![first];
for (index, token) in tokens.iter().enumerate() {
if starts_column_modifier(&tokens, index) {
break;
}
parts.push(token);
}
parts.join(" ")
}
fn starts_column_modifier(tokens: &[String], index: usize) -> bool {
let token = tokens[index].to_ascii_uppercase();
if token == "CHARACTER"
&& tokens
.get(index + 1)
.is_some_and(|next| next.eq_ignore_ascii_case("SET"))
{
return true;
}
matches!(
token.as_str(),
"NOT"
| "NULL"
| "PRIMARY"
| "UNIQUE"
| "DEFAULT"
| "CHECK"
| "GENERATED"
| "AS"
| "AUTO_INCREMENT"
| "AUTOINCREMENT"
| "AUTO_RANDOM"
| "IDENTITY"
| "COLLATE"
| "CONSTRAINT"
| "REFERENCES"
| "COMMENT"
| "ON"
| "BINARY"
| "ASCII"
| "UNICODE"
| "BYTE"
| "VISIBLE"
| "INVISIBLE"
| "COLUMN_FORMAT"
| "ENGINE_ATTRIBUTE"
| "SECONDARY_ENGINE_ATTRIBUTE"
| "STORAGE"
| "SRID"
| "SPARSE"
| "FILESTREAM"
| "ROWGUIDCOL"
| "HIDDEN"
| "MASKED"
| "PERSISTED"
| "ENCRYPTED"
| "COMPRESSION"
| "KEY"
) || token.starts_with("IDENTITY(")
}
#[derive(Debug, Default)]
struct ColumnModifiers {
is_unique: bool,
default_sql: Option<String>,
is_generated: bool,
is_identity: bool,
collation: Option<String>,
inline_check: Option<String>,
}
fn parse_column_modifiers(remainder: &str) -> ColumnModifiers {
let tokens = tokenize_ddl(remainder);
let mut modifiers = ColumnModifiers::default();
let mut i = 0;
while i < tokens.len() {
let upper = tokens[i].to_uppercase();
match upper.as_str() {
"UNIQUE" => {
modifiers.is_unique = true;
i += 1;
}
"DEFAULT" => {
if let Some(value) = tokens.get(i + 1) {
modifiers.default_sql = Some(value.clone());
i += 2;
} else {
i += 1;
}
}
"COLLATE" => {
if let Some(value) = tokens.get(i + 1) {
modifiers.collation = Some(strip_quotes(value));
i += 2;
} else {
i += 1;
}
}
"CHECK" => {
if let Some(expr) = tokens.get(i + 1) {
modifiers.inline_check = Some(strip_outer_parens(expr));
i += 2;
} else {
i += 1;
}
}
"GENERATED" => {
let mut j = i + 1;
while j < tokens.len() && !tokens[j].eq_ignore_ascii_case("AS") {
j += 1;
}
if let Some(as_expr) = tokens.get(j + 1) {
if as_expr.starts_with('(') {
modifiers.is_generated = true;
} else if as_expr.eq_ignore_ascii_case("IDENTITY") {
modifiers.is_identity = true;
}
}
i = j + 2;
}
"AS" => {
if tokens
.get(i + 1)
.is_some_and(|expression| expression.starts_with('('))
{
modifiers.is_generated = true;
i += 2;
} else {
i += 1;
}
}
"AUTO_INCREMENT" | "AUTOINCREMENT" => {
modifiers.is_identity = true;
i += 1;
}
_ if upper.starts_with("IDENTITY(") || upper == "IDENTITY" => {
modifiers.is_identity = true;
i += 1;
}
_ => {
i += 1;
}
}
}
modifiers
}
fn tokenize_ddl(s: &str) -> Vec<String> {
let mut tokens = Vec::new();
let mut current = String::new();
let mut depth = 0u32;
let mut in_string = false;
let mut escape_next = false;
for ch in s.chars() {
if escape_next {
current.push(ch);
escape_next = false;
continue;
}
if ch == '\\' && in_string {
current.push(ch);
escape_next = true;
continue;
}
if ch == '\'' {
in_string = !in_string;
current.push(ch);
continue;
}
if in_string {
current.push(ch);
continue;
}
match ch {
'(' => {
depth += 1;
current.push(ch);
}
')' => {
depth = depth.saturating_sub(1);
current.push(ch);
}
c if c.is_whitespace() && depth == 0 => {
if !current.is_empty() {
tokens.push(std::mem::take(&mut current));
}
}
_ => current.push(ch),
}
}
if !current.is_empty() {
tokens.push(current);
}
tokens
}
fn strip_quotes(s: &str) -> String {
s.trim_matches('\'')
.trim_matches('"')
.trim_matches('`')
.trim_matches('[')
.trim_matches(']')
.to_string()
}
fn strip_outer_parens(s: &str) -> String {
let trimmed = s.trim();
match trimmed
.strip_prefix('(')
.and_then(|rest| rest.strip_suffix(')'))
{
Some(inner) => inner.trim().to_string(),
None => trimmed.to_string(),
}
}
fn parse_unique_constraint(constraint: &str) -> Option<UniqueConstraint> {
let tokens = tokenize_ddl(constraint);
let mut i = 0;
let mut name = None;
if tokens.first()?.eq_ignore_ascii_case("CONSTRAINT") {
name = tokens.get(1).map(|s| strip_quotes(s));
i = 2;
}
if !tokens.get(i)?.eq_ignore_ascii_case("UNIQUE") {
return None;
}
let cols_token = tokens.get(i + 1)?;
if !cols_token.starts_with('(') {
return None;
}
let columns = parse_column_list(strip_outer_parens(cols_token).as_str());
if columns.is_empty() {
return None;
}
Some(UniqueConstraint { name, columns })
}
fn parse_check_constraint(constraint: &str) -> Option<CheckConstraint> {
let tokens = tokenize_ddl(constraint);
let mut i = 0;
let mut name = None;
if tokens.first()?.eq_ignore_ascii_case("CONSTRAINT") {
name = tokens.get(1).map(|s| strip_quotes(s));
i = 2;
}
if !tokens.get(i)?.eq_ignore_ascii_case("CHECK") {
return None;
}
let expr_token = tokens.get(i + 1)?;
if !expr_token.starts_with('(') {
return None;
}
Some(CheckConstraint {
name,
expression: strip_outer_parens(expr_token),
})
}
fn parse_primary_key_constraint(constraint: &str) -> Option<Vec<String>> {
let caps = PRIMARY_KEY_RE.captures(constraint)?;
let cols_str = caps.get(1)?.as_str();
Some(parse_column_list(cols_str))
}
fn parse_inline_index(constraint: &str) -> Option<IndexDef> {
let caps = INLINE_INDEX_RE.captures(constraint)?;
let is_unique = caps.get(1).is_some();
let index_name = caps.get(2)?.as_str().to_string();
let columns_str = caps.get(3)?.as_str();
let columns = parse_column_list(columns_str);
Some(IndexDef {
name: index_name,
columns,
is_unique,
index_type: None, })
}
fn parse_foreign_keys(stmt: &str) -> Vec<ForeignKey> {
let mut fks = Vec::new();
for caps in FOREIGN_KEY_RE.captures_iter(stmt) {
let name = caps.get(1).map(|m| m.as_str().to_string());
let local_cols = caps
.get(2)
.map(|m| parse_column_list(m.as_str()))
.unwrap_or_default();
let ref_table = caps
.get(3)
.and_then(|m| normalize_qualified_identifier(m.as_str()))
.unwrap_or_default();
let ref_cols = caps
.get(4)
.map(|m| parse_column_list(m.as_str()))
.unwrap_or_default();
if !local_cols.is_empty() && !ref_table.is_empty() && !ref_cols.is_empty() {
fks.push(ForeignKey {
name,
columns: Vec::new(), column_names: local_cols,
referenced_table: ref_table,
referenced_columns: ref_cols,
referenced_table_id: None,
});
}
}
fks
}
pub fn parse_column_list(s: &str) -> Vec<String> {
s.split(',')
.map(|c| {
c.trim()
.trim_matches('`')
.trim_matches('"')
.trim_matches('[')
.trim_matches(']')
.to_string()
})
.filter(|c| !c.is_empty())
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn preserves_qualified_table_names_in_schema() {
let mut builder = SchemaBuilder::new();
builder.parse_create_table("CREATE TABLE tenant_a.users (id INT PRIMARY KEY);");
builder.parse_create_table("CREATE TABLE tenant_b.users (id INT PRIMARY KEY);");
let schema = builder.build();
assert_eq!(schema.len(), 2);
assert!(schema.get_table("tenant_a.users").is_some());
assert!(schema.get_table("tenant_b.users").is_some());
}
#[test]
fn resolves_qualified_foreign_keys_and_indexes() {
let mut builder = SchemaBuilder::new();
builder.parse_create_table("CREATE TABLE \"tenant_a\".\"parents\" (id INT PRIMARY KEY);");
builder.parse_create_table(
"CREATE TABLE \"tenant_a\".\"children\" (\
id INT PRIMARY KEY, parent_id INT, \
FOREIGN KEY (parent_id) REFERENCES \"tenant_a\".\"parents\" (id)\
);",
);
builder.parse_create_index(
"CREATE INDEX children_parent_idx ON \"tenant_a\".\"children\" (parent_id);",
);
let schema = builder.build();
let parent = schema.get_table_id("tenant_a.parents").unwrap();
let child = schema.get_table("tenant_a.children").unwrap();
assert_eq!(child.foreign_keys[0].referenced_table, "tenant_a.parents");
assert_eq!(child.foreign_keys[0].referenced_table_id, Some(parent));
assert_eq!(child.indexes[0].name, "children_parent_idx");
}
#[test]
fn extracts_quoted_qualified_table_names() {
assert_eq!(
extract_create_table_name("CREATE TABLE \"tenant_a\".\"users\" (id INT);"),
Some("tenant_a.users".to_string())
);
assert_eq!(
extract_alter_table_name("ALTER TABLE [tenant_a].[users] ADD COLUMN email TEXT;"),
Some("tenant_a.users".to_string())
);
assert_eq!(
extract_create_table_name("CREATE TABLE public.\"user.log\" (id INT);"),
Some("public.\"user.log\"".to_string())
);
}
#[test]
fn parses_ddl_after_parenthesized_leading_comment() {
let mut builder = SchemaBuilder::new();
builder.parse_create_table(
"-- Converted type: NVARCHAR(MAX)\n\
CREATE TABLE users (\n\
id INTEGER NOT NULL,\n\
PRIMARY KEY (id)\n\
);",
);
let schema = builder.build();
let users = schema.get_table("users").expect("users table");
assert_eq!(users.primary_key.len(), 1);
assert_eq!(users.columns[0].name, "id");
}
}