1mod build;
10mod ddl;
11mod graph;
12
13pub use ddl::*;
14pub use graph::*;
15
16use ahash::AHashMap;
17use std::fmt;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub struct TableId(pub u32);
22
23impl fmt::Display for TableId {
24 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25 write!(f, "TableId({})", self.0)
26 }
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
31pub struct ColumnId(pub u16);
32
33impl fmt::Display for ColumnId {
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 write!(f, "ColumnId({})", self.0)
36 }
37}
38
39#[derive(Debug, Clone, PartialEq, Eq)]
41pub enum ColumnType {
42 Int,
44 BigInt,
46 Text,
48 Uuid,
50 Decimal,
52 DateTime,
54 Bool,
56 Other(String),
58}
59
60impl ColumnType {
61 pub fn from_sql_type(type_str: &str) -> Self {
64 let type_lower = type_str.to_lowercase();
65 let base_type = type_lower.split('(').next().unwrap_or(&type_lower).trim();
66
67 let mut base_words: Vec<_> = base_type.split_whitespace().collect();
72 while base_words
73 .last()
74 .is_some_and(|word| matches!(*word, "unsigned" | "signed" | "zerofill"))
75 {
76 base_words.pop();
77 }
78 let base_type = base_words.join(" ");
79
80 match base_type.as_str() {
81 "int" | "integer" | "tinyint" | "smallint" | "mediumint" | "int4" | "int2" => {
83 ColumnType::Int
84 }
85 "serial" | "smallserial" => ColumnType::Int,
87 "bigint" | "int8" | "bigserial" => ColumnType::BigInt,
88 "char"
90 | "varchar"
91 | "text"
92 | "tinytext"
93 | "mediumtext"
94 | "longtext"
95 | "enum"
96 | "set"
97 | "character"
98 | "character varying"
99 | "char varying"
100 | "national character"
101 | "national character varying"
102 | "national char"
103 | "national char varying"
104 | "nchar"
105 | "nvarchar"
106 | "ntext" => ColumnType::Text,
107 "decimal" | "numeric" | "float" | "double" | "double precision" | "real" | "float4"
109 | "float8" | "money" => ColumnType::Decimal,
110 "date"
112 | "datetime"
113 | "timestamp"
114 | "time"
115 | "year"
116 | "timestamptz"
117 | "timetz"
118 | "interval"
119 | "timestamp with time zone"
120 | "timestamp without time zone"
121 | "time with time zone"
122 | "time without time zone" => ColumnType::DateTime,
123 interval if interval.starts_with("interval ") => ColumnType::DateTime,
124 "bool" | "boolean" => ColumnType::Bool,
127 "bit" if type_lower.trim() == "bit" => ColumnType::Bool,
132 "binary" | "varbinary" | "blob" | "bytea" => {
134 if type_lower.contains("16") {
136 ColumnType::Uuid
137 } else {
138 ColumnType::Other(type_str.to_string())
139 }
140 }
141 "uuid" => ColumnType::Uuid,
142 _ => ColumnType::Other(type_str.to_string()),
143 }
144 }
145
146 pub fn from_mysql_type(type_str: &str) -> Self {
148 Self::from_sql_type(type_str)
149 }
150}
151
152#[derive(Debug, Clone)]
154pub struct Column {
155 pub name: String,
157 pub col_type: ColumnType,
159 pub source_type: String,
161 pub ordinal: ColumnId,
163 pub is_primary_key: bool,
165 pub is_nullable: bool,
167 pub is_unique: bool,
169 pub default_sql: Option<String>,
171 pub is_generated: bool,
173 pub is_identity: bool,
175 pub collation: Option<String>,
177}
178
179#[derive(Debug, Clone, PartialEq, Eq)]
181pub struct IndexDef {
182 pub name: String,
184 pub columns: Vec<String>,
186 pub is_unique: bool,
188 pub index_type: Option<String>,
190}
191
192#[derive(Debug, Clone, PartialEq, Eq)]
194pub struct UniqueConstraint {
195 pub name: Option<String>,
197 pub columns: Vec<String>,
199}
200
201#[derive(Debug, Clone, PartialEq, Eq)]
203pub struct CheckConstraint {
204 pub name: Option<String>,
206 pub expression: String,
208}
209
210#[derive(Debug, Clone)]
212pub struct ForeignKey {
213 pub name: Option<String>,
215 pub columns: Vec<ColumnId>,
217 pub column_names: Vec<String>,
219 pub referenced_table: String,
221 pub referenced_columns: Vec<String>,
223 pub referenced_table_id: Option<TableId>,
225}
226
227#[derive(Debug, Clone)]
229pub struct TableSchema {
230 pub name: String,
232 pub id: TableId,
234 pub columns: Vec<Column>,
236 pub primary_key: Vec<ColumnId>,
238 pub foreign_keys: Vec<ForeignKey>,
240 pub unique_constraints: Vec<UniqueConstraint>,
242 pub check_constraints: Vec<CheckConstraint>,
244 pub indexes: Vec<IndexDef>,
246 pub create_statement: Option<String>,
248}
249
250impl TableSchema {
251 pub fn new(name: String, id: TableId) -> Self {
253 Self {
254 name,
255 id,
256 columns: Vec::new(),
257 primary_key: Vec::new(),
258 foreign_keys: Vec::new(),
259 unique_constraints: Vec::new(),
260 check_constraints: Vec::new(),
261 indexes: Vec::new(),
262 create_statement: None,
263 }
264 }
265
266 pub fn get_column(&self, name: &str) -> Option<&Column> {
268 self.columns
269 .iter()
270 .find(|c| c.name.eq_ignore_ascii_case(name))
271 }
272
273 pub fn get_column_id(&self, name: &str) -> Option<ColumnId> {
275 self.get_column(name).map(|c| c.ordinal)
276 }
277
278 pub fn column(&self, id: ColumnId) -> Option<&Column> {
280 self.columns.get(id.0 as usize)
281 }
282
283 pub fn is_pk_column(&self, col_id: ColumnId) -> bool {
285 self.primary_key.contains(&col_id)
286 }
287}
288
289#[derive(Debug)]
291pub struct Schema {
292 pub tables: AHashMap<String, TableId>,
294 pub table_schemas: Vec<TableSchema>,
296}
297
298impl Schema {
299 pub fn new() -> Self {
301 Self {
302 tables: AHashMap::new(),
303 table_schemas: Vec::new(),
304 }
305 }
306
307 pub fn get_table_id(&self, name: &str) -> Option<TableId> {
309 if let Some(&id) = self.tables.get(name) {
311 return Some(id);
312 }
313 let name_lower = name.to_lowercase();
315 self.tables
316 .iter()
317 .find(|(k, _)| k.to_lowercase() == name_lower)
318 .map(|(_, &id)| id)
319 }
320
321 pub fn table(&self, id: TableId) -> Option<&TableSchema> {
323 self.table_schemas.get(id.0 as usize)
324 }
325
326 pub fn table_mut(&mut self, id: TableId) -> Option<&mut TableSchema> {
328 self.table_schemas.get_mut(id.0 as usize)
329 }
330
331 pub fn get_table(&self, name: &str) -> Option<&TableSchema> {
333 self.get_table_id(name).and_then(|id| self.table(id))
334 }
335
336 pub fn add_table(&mut self, mut schema: TableSchema) -> TableId {
338 let id = TableId(self.table_schemas.len() as u32);
339 schema.id = id;
340 self.tables.insert(schema.name.clone(), id);
341 self.table_schemas.push(schema);
342 id
343 }
344
345 pub fn resolve_foreign_keys(&mut self) {
347 let table_ids: AHashMap<String, TableId> = self.tables.clone();
348
349 for table in &mut self.table_schemas {
350 for fk in &mut table.foreign_keys {
351 fk.referenced_table_id = table_ids
352 .get(&fk.referenced_table)
353 .or_else(|| {
354 let lower = fk.referenced_table.to_lowercase();
356 table_ids
357 .iter()
358 .find(|(k, _)| k.to_lowercase() == lower)
359 .map(|(_, v)| v)
360 })
361 .copied();
362 }
363 }
364 }
365
366 pub fn len(&self) -> usize {
368 self.table_schemas.len()
369 }
370
371 pub fn is_empty(&self) -> bool {
373 self.table_schemas.is_empty()
374 }
375
376 pub fn iter(&self) -> impl Iterator<Item = &TableSchema> {
378 self.table_schemas.iter()
379 }
380}
381
382impl Default for Schema {
383 fn default() -> Self {
384 Self::new()
385 }
386}