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 base_type = match base_type.split_whitespace().next() {
74 Some(first)
75 if base_type
76 .split_whitespace()
77 .skip(1)
78 .all(|word| matches!(word, "unsigned" | "signed" | "zerofill")) =>
79 {
80 first
81 }
82 _ => base_type,
83 };
84
85 match base_type {
86 "int" | "integer" | "tinyint" | "smallint" | "mediumint" | "int4" | "int2" => {
88 ColumnType::Int
89 }
90 "serial" | "smallserial" => ColumnType::Int,
92 "bigint" | "int8" | "bigserial" => ColumnType::BigInt,
93 "char" | "varchar" | "text" | "tinytext" | "mediumtext" | "longtext" | "enum"
95 | "set" | "character" | "nchar" | "nvarchar" | "ntext" => ColumnType::Text,
96 "decimal" | "numeric" | "float" | "double" | "real" | "float4" | "float8" | "money" => {
98 ColumnType::Decimal
99 }
100 "date" | "datetime" | "timestamp" | "time" | "year" | "timestamptz" | "timetz"
102 | "interval" => ColumnType::DateTime,
103 "bool" | "boolean" => ColumnType::Bool,
106 "bit" if type_lower.trim() == "bit" => ColumnType::Bool,
111 "binary" | "varbinary" | "blob" | "bytea" => {
113 if type_lower.contains("16") {
115 ColumnType::Uuid
116 } else {
117 ColumnType::Other(type_str.to_string())
118 }
119 }
120 "uuid" => ColumnType::Uuid,
121 _ => ColumnType::Other(type_str.to_string()),
122 }
123 }
124
125 pub fn from_mysql_type(type_str: &str) -> Self {
127 Self::from_sql_type(type_str)
128 }
129}
130
131#[derive(Debug, Clone)]
133pub struct Column {
134 pub name: String,
136 pub col_type: ColumnType,
138 pub source_type: String,
140 pub ordinal: ColumnId,
142 pub is_primary_key: bool,
144 pub is_nullable: bool,
146 pub is_unique: bool,
148 pub default_sql: Option<String>,
150 pub is_generated: bool,
152 pub is_identity: bool,
154 pub collation: Option<String>,
156}
157
158#[derive(Debug, Clone, PartialEq, Eq)]
160pub struct IndexDef {
161 pub name: String,
163 pub columns: Vec<String>,
165 pub is_unique: bool,
167 pub index_type: Option<String>,
169}
170
171#[derive(Debug, Clone, PartialEq, Eq)]
173pub struct UniqueConstraint {
174 pub name: Option<String>,
176 pub columns: Vec<String>,
178}
179
180#[derive(Debug, Clone, PartialEq, Eq)]
182pub struct CheckConstraint {
183 pub name: Option<String>,
185 pub expression: String,
187}
188
189#[derive(Debug, Clone)]
191pub struct ForeignKey {
192 pub name: Option<String>,
194 pub columns: Vec<ColumnId>,
196 pub column_names: Vec<String>,
198 pub referenced_table: String,
200 pub referenced_columns: Vec<String>,
202 pub referenced_table_id: Option<TableId>,
204}
205
206#[derive(Debug, Clone)]
208pub struct TableSchema {
209 pub name: String,
211 pub id: TableId,
213 pub columns: Vec<Column>,
215 pub primary_key: Vec<ColumnId>,
217 pub foreign_keys: Vec<ForeignKey>,
219 pub unique_constraints: Vec<UniqueConstraint>,
221 pub check_constraints: Vec<CheckConstraint>,
223 pub indexes: Vec<IndexDef>,
225 pub create_statement: Option<String>,
227}
228
229impl TableSchema {
230 pub fn new(name: String, id: TableId) -> Self {
232 Self {
233 name,
234 id,
235 columns: Vec::new(),
236 primary_key: Vec::new(),
237 foreign_keys: Vec::new(),
238 unique_constraints: Vec::new(),
239 check_constraints: Vec::new(),
240 indexes: Vec::new(),
241 create_statement: None,
242 }
243 }
244
245 pub fn get_column(&self, name: &str) -> Option<&Column> {
247 self.columns
248 .iter()
249 .find(|c| c.name.eq_ignore_ascii_case(name))
250 }
251
252 pub fn get_column_id(&self, name: &str) -> Option<ColumnId> {
254 self.get_column(name).map(|c| c.ordinal)
255 }
256
257 pub fn column(&self, id: ColumnId) -> Option<&Column> {
259 self.columns.get(id.0 as usize)
260 }
261
262 pub fn is_pk_column(&self, col_id: ColumnId) -> bool {
264 self.primary_key.contains(&col_id)
265 }
266}
267
268#[derive(Debug)]
270pub struct Schema {
271 pub tables: AHashMap<String, TableId>,
273 pub table_schemas: Vec<TableSchema>,
275}
276
277impl Schema {
278 pub fn new() -> Self {
280 Self {
281 tables: AHashMap::new(),
282 table_schemas: Vec::new(),
283 }
284 }
285
286 pub fn get_table_id(&self, name: &str) -> Option<TableId> {
288 if let Some(&id) = self.tables.get(name) {
290 return Some(id);
291 }
292 let name_lower = name.to_lowercase();
294 self.tables
295 .iter()
296 .find(|(k, _)| k.to_lowercase() == name_lower)
297 .map(|(_, &id)| id)
298 }
299
300 pub fn table(&self, id: TableId) -> Option<&TableSchema> {
302 self.table_schemas.get(id.0 as usize)
303 }
304
305 pub fn table_mut(&mut self, id: TableId) -> Option<&mut TableSchema> {
307 self.table_schemas.get_mut(id.0 as usize)
308 }
309
310 pub fn get_table(&self, name: &str) -> Option<&TableSchema> {
312 self.get_table_id(name).and_then(|id| self.table(id))
313 }
314
315 pub fn add_table(&mut self, mut schema: TableSchema) -> TableId {
317 let id = TableId(self.table_schemas.len() as u32);
318 schema.id = id;
319 self.tables.insert(schema.name.clone(), id);
320 self.table_schemas.push(schema);
321 id
322 }
323
324 pub fn resolve_foreign_keys(&mut self) {
326 let table_ids: AHashMap<String, TableId> = self.tables.clone();
327
328 for table in &mut self.table_schemas {
329 for fk in &mut table.foreign_keys {
330 fk.referenced_table_id = table_ids
331 .get(&fk.referenced_table)
332 .or_else(|| {
333 let lower = fk.referenced_table.to_lowercase();
335 table_ids
336 .iter()
337 .find(|(k, _)| k.to_lowercase() == lower)
338 .map(|(_, v)| v)
339 })
340 .copied();
341 }
342 }
343 }
344
345 pub fn len(&self) -> usize {
347 self.table_schemas.len()
348 }
349
350 pub fn is_empty(&self) -> bool {
352 self.table_schemas.is_empty()
353 }
354
355 pub fn iter(&self) -> impl Iterator<Item = &TableSchema> {
357 self.table_schemas.iter()
358 }
359}
360
361impl Default for Schema {
362 fn default() -> Self {
363 Self::new()
364 }
365}