Skip to main content

codeint_lang_sql/schema/
builder.rs

1use std::collections::BTreeMap;
2
3use sqlparser::ast::{
4    AlterColumnOperation, AlterTable, AlterTableOperation, ColumnDef, ColumnOption, CreateIndex,
5    CreateTable, DataType, Expr, Ident, IndexColumn, ObjectName, ObjectType, RenameTableNameKind,
6    Statement, TableConstraint,
7};
8
9use crate::schema::artifact::{AlterOp, ColumnAlterOp, DdlOp, TableAlterOp};
10use crate::schema::types::{
11    ColumnTypeClass, IndexSchema, SqlSchema, TableKey, TableSchema, normalize_ident,
12    object_name_last_ident, split_object_name,
13};
14use crate::{ParsedSqlStatement, SqlDialect};
15
16impl SqlSchema {
17    pub fn build<'a>(
18        files_in_path_order: impl IntoIterator<Item = &'a [ParsedSqlStatement]>,
19    ) -> SqlSchema {
20        SqlSchema::build_for_dialect(SqlDialect::Generic, files_in_path_order)
21    }
22
23    pub fn build_for_dialect<'a>(
24        dialect: SqlDialect,
25        files_in_path_order: impl IntoIterator<Item = &'a [ParsedSqlStatement]>,
26    ) -> SqlSchema {
27        let mut schema = SqlSchema::with_dialect(dialect);
28        for statements in files_in_path_order {
29            let ops = extract_ddl_ops(statements, dialect);
30            schema.apply_ddl_ops(&ops);
31        }
32        schema
33    }
34
35    pub(crate) fn apply_ddl_ops(&mut self, ops: &[DdlOp]) {
36        for op in ops {
37            apply_ddl_op(self, op);
38        }
39    }
40}
41
42pub(crate) fn extract_ddl_ops(
43    statements: &[ParsedSqlStatement],
44    dialect: SqlDialect,
45) -> Vec<DdlOp> {
46    let mut ops = Vec::new();
47    for parsed in statements {
48        extract_statement_ddl(&parsed.statement, dialect, &mut ops);
49    }
50    ops
51}
52
53fn extract_statement_ddl(stmt: &Statement, dialect: SqlDialect, out: &mut Vec<DdlOp>) {
54    match stmt {
55        Statement::CreateTable(create_table) => {
56            if let Some(op) = extract_create_table(create_table, dialect) {
57                out.push(op);
58            }
59        }
60        Statement::CreateIndex(create_index) => {
61            if let Some(op) = extract_create_index(create_index, dialect) {
62                out.push(op);
63            }
64        }
65        Statement::AlterTable(alter_table) => {
66            if let Some(op) = extract_alter_table(alter_table, dialect) {
67                out.push(op);
68            }
69        }
70        Statement::Drop {
71            object_type,
72            names,
73            table,
74            ..
75        } => extract_drop(*object_type, names, table.as_ref(), dialect, out),
76        _ => {}
77    }
78}
79
80fn extract_create_table(create: &CreateTable, dialect: SqlDialect) -> Option<DdlOp> {
81    if create.temporary || (create.columns.is_empty() && create.query.is_some()) {
82        return None;
83    }
84    let (table_schema, table_name) = split_object_name(&create.name, dialect)?;
85    let mut table = TableSchema {
86        schema: table_schema,
87        name: table_name,
88        columns: BTreeMap::new(),
89        primary_key: Vec::new(),
90        indexes: Vec::new(),
91    };
92    for column in &create.columns {
93        apply_column_def(&mut table, column, dialect);
94    }
95    for constraint in &create.constraints {
96        apply_table_constraint(&mut table, constraint, dialect);
97    }
98    if table.primary_key.is_empty()
99        && let Some(expr) = &create.primary_key
100    {
101        table.primary_key = extract_pk_expr_columns(expr, dialect);
102    }
103    Some(DdlOp::CreateTable {
104        if_not_exists: create.if_not_exists,
105        table,
106    })
107}
108
109fn extract_create_index(create: &CreateIndex, dialect: SqlDialect) -> Option<DdlOp> {
110    let (table_schema, table_name) = split_object_name(&create.table_name, dialect)?;
111    let columns = extract_index_columns(&create.columns, dialect);
112    if columns.is_empty() {
113        return None;
114    }
115    let name = create
116        .name
117        .as_ref()
118        .and_then(|obj| object_name_last_ident(obj, dialect));
119    Some(DdlOp::CreateIndex {
120        table_schema,
121        table_name,
122        index: IndexSchema { name, columns },
123    })
124}
125
126fn extract_alter_table(alter: &AlterTable, dialect: SqlDialect) -> Option<DdlOp> {
127    let (table_schema, table_name) = split_object_name(&alter.name, dialect)?;
128    let mut ops = Vec::new();
129    for operation in &alter.operations {
130        extract_alter_operation(operation, dialect, &mut ops);
131    }
132    (!ops.is_empty()).then_some(DdlOp::AlterTable {
133        table_schema,
134        table_name,
135        ops,
136    })
137}
138
139fn extract_column_flags(
140    options: &[ColumnOption],
141    constraint_names: &[Option<String>],
142    dialect: SqlDialect,
143) -> (bool, Option<Option<String>>) {
144    let mut is_pk = false;
145    let mut unique_index = None;
146    for (idx, option) in options.iter().enumerate() {
147        match option {
148            ColumnOption::PrimaryKey(_) => is_pk = true,
149            ColumnOption::Unique(unique) => {
150                let name = unique
151                    .name
152                    .as_ref()
153                    .or(unique.index_name.as_ref())
154                    .map(|ident| normalize_ident(ident, dialect))
155                    .or_else(|| constraint_names.get(idx).cloned().flatten());
156                unique_index = Some(name);
157            }
158            _ => {}
159        }
160    }
161    (is_pk, unique_index)
162}
163
164fn extract_alter_operation(
165    operation: &AlterTableOperation,
166    dialect: SqlDialect,
167    out: &mut Vec<AlterOp>,
168) {
169    match operation {
170        AlterTableOperation::RenameTable { table_name } => {
171            let target_name = match table_name {
172                RenameTableNameKind::As(name) | RenameTableNameKind::To(name) => name,
173            };
174            if let Some((new_schema, new_name)) = split_object_name(target_name, dialect) {
175                out.push(AlterOp::Table(TableAlterOp::RenameTable {
176                    new_schema,
177                    new_name,
178                }));
179            }
180        }
181        AlterTableOperation::AddColumn { column_def, .. } => {
182            let opts: Vec<ColumnOption> = column_def
183                .options
184                .iter()
185                .map(|o| o.option.clone())
186                .collect();
187            let cnames: Vec<Option<String>> = column_def
188                .options
189                .iter()
190                .map(|o| o.name.as_ref().map(|ident| normalize_ident(ident, dialect)))
191                .collect();
192            let (is_pk, unique_index) = extract_column_flags(&opts, &cnames, dialect);
193            out.push(AlterOp::Column(ColumnAlterOp::AddColumn {
194                name: normalize_ident(&column_def.name, dialect),
195                ty: classify_data_type(&column_def.data_type),
196                is_pk,
197                unique_index,
198            }));
199        }
200        AlterTableOperation::DropColumn { column_names, .. } => {
201            for ident in column_names {
202                out.push(AlterOp::Column(ColumnAlterOp::DropColumn {
203                    name: normalize_ident(ident, dialect),
204                }));
205            }
206        }
207        AlterTableOperation::RenameColumn {
208            old_column_name,
209            new_column_name,
210        } => out.push(AlterOp::Column(ColumnAlterOp::RenameColumn {
211            old: normalize_ident(old_column_name, dialect),
212            new: normalize_ident(new_column_name, dialect),
213        })),
214        AlterTableOperation::ChangeColumn {
215            old_name,
216            new_name,
217            data_type,
218            options,
219            ..
220        } => {
221            let (is_pk, unique_index) = extract_column_flags(options, &[], dialect);
222            out.push(AlterOp::Column(ColumnAlterOp::ChangeColumn {
223                old: normalize_ident(old_name, dialect),
224                new: normalize_ident(new_name, dialect),
225                ty: classify_data_type(data_type),
226                is_pk,
227                unique_index,
228            }));
229        }
230        AlterTableOperation::ModifyColumn {
231            col_name,
232            data_type,
233            options,
234            ..
235        } => {
236            let (is_pk, unique_index) = extract_column_flags(options, &[], dialect);
237            out.push(AlterOp::Column(ColumnAlterOp::ModifyColumn {
238                name: normalize_ident(col_name, dialect),
239                ty: classify_data_type(data_type),
240                is_pk,
241                unique_index,
242            }));
243        }
244        AlterTableOperation::AlterColumn {
245            column_name,
246            op: AlterColumnOperation::SetDataType { data_type, .. },
247        } => out.push(AlterOp::Column(ColumnAlterOp::SetColumnType {
248            name: normalize_ident(column_name, dialect),
249            ty: classify_data_type(data_type),
250        })),
251        _ => extract_constraint_alter(operation, dialect, out),
252    }
253}
254
255fn extract_constraint_alter(
256    operation: &AlterTableOperation,
257    dialect: SqlDialect,
258    out: &mut Vec<AlterOp>,
259) {
260    match operation {
261        AlterTableOperation::AddConstraint { constraint, .. } => {
262            extract_table_constraint_alter(constraint, dialect, out);
263        }
264        AlterTableOperation::DropConstraint { name, .. }
265        | AlterTableOperation::DropIndex { name } => {
266            out.push(AlterOp::Table(TableAlterOp::DropNamedIndex {
267                name: normalize_ident(name, dialect),
268            }))
269        }
270        AlterTableOperation::DropPrimaryKey { .. } => {
271            out.push(AlterOp::Table(TableAlterOp::DropPrimaryKey))
272        }
273        _ => {}
274    }
275}
276
277fn extract_table_constraint_alter(
278    constraint: &TableConstraint,
279    dialect: SqlDialect,
280    out: &mut Vec<AlterOp>,
281) {
282    match constraint {
283        TableConstraint::PrimaryKey(pk) => {
284            let columns = extract_index_columns(&pk.columns, dialect);
285            if !columns.is_empty() {
286                out.push(AlterOp::Table(TableAlterOp::SetPrimaryKey { columns }));
287            }
288        }
289        TableConstraint::Unique(unique) => {
290            let columns = extract_index_columns(&unique.columns, dialect);
291            if !columns.is_empty() {
292                let name = unique
293                    .name
294                    .as_ref()
295                    .or(unique.index_name.as_ref())
296                    .map(|ident| normalize_ident(ident, dialect));
297                out.push(AlterOp::Table(TableAlterOp::AddIndex {
298                    index: IndexSchema { name, columns },
299                }));
300            }
301        }
302        TableConstraint::Index(index) => {
303            let columns = extract_index_columns(&index.columns, dialect);
304            if !columns.is_empty() {
305                out.push(AlterOp::Table(TableAlterOp::AddIndex {
306                    index: IndexSchema {
307                        name: index
308                            .name
309                            .as_ref()
310                            .map(|ident| normalize_ident(ident, dialect)),
311                        columns,
312                    },
313                }));
314            }
315        }
316        TableConstraint::FulltextOrSpatial(index) => {
317            let columns = extract_index_columns(&index.columns, dialect);
318            if !columns.is_empty() {
319                out.push(AlterOp::Table(TableAlterOp::AddIndex {
320                    index: IndexSchema {
321                        name: index
322                            .opt_index_name
323                            .as_ref()
324                            .map(|ident| normalize_ident(ident, dialect)),
325                        columns,
326                    },
327                }));
328            }
329        }
330        TableConstraint::PrimaryKeyUsingIndex(using_idx) => {
331            out.push(AlterOp::Table(TableAlterOp::PromoteIndexToPk {
332                index_name: normalize_ident(&using_idx.index_name, dialect),
333            }));
334        }
335        _ => {}
336    }
337}
338
339fn extract_drop(
340    object_type: ObjectType,
341    names: &[ObjectName],
342    table_target: Option<&ObjectName>,
343    dialect: SqlDialect,
344    out: &mut Vec<DdlOp>,
345) {
346    match object_type {
347        ObjectType::Table => extract_drop_tables(names, dialect, out),
348        ObjectType::Index => extract_drop_indexes(names, table_target, dialect, out),
349        _ => {}
350    }
351}
352
353fn extract_drop_tables(names: &[ObjectName], dialect: SqlDialect, out: &mut Vec<DdlOp>) {
354    for (schema, name) in names
355        .iter()
356        .filter_map(|obj| split_object_name(obj, dialect))
357    {
358        out.push(DdlOp::DropTable { schema, name });
359    }
360}
361
362fn extract_drop_indexes(
363    names: &[ObjectName],
364    table_target: Option<&ObjectName>,
365    dialect: SqlDialect,
366    out: &mut Vec<DdlOp>,
367) {
368    if let Some(target) = table_target {
369        let Some((table_schema, table_name)) = split_object_name(target, dialect) else {
370            return;
371        };
372        for index_name in names
373            .iter()
374            .filter_map(|obj| object_name_last_ident(obj, dialect))
375        {
376            out.push(DdlOp::DropIndexOnTable {
377                table_schema: table_schema.clone(),
378                table_name: table_name.clone(),
379                index_name,
380            });
381        }
382        return;
383    }
384    for (index_schema, index_name) in names
385        .iter()
386        .filter_map(|obj| split_object_name(obj, dialect))
387    {
388        out.push(DdlOp::DropIndexAcrossTables {
389            index_schema,
390            index_name,
391        });
392    }
393}
394
395fn apply_ddl_op(schema: &mut SqlSchema, op: &DdlOp) {
396    match op {
397        DdlOp::CreateTable {
398            if_not_exists,
399            table,
400        } => apply_create_table_op(schema, *if_not_exists, table),
401        DdlOp::CreateIndex {
402            table_schema,
403            table_name,
404            index,
405        } => apply_create_index_op(schema, table_schema.as_deref(), table_name, index),
406        DdlOp::AlterTable {
407            table_schema,
408            table_name,
409            ops,
410        } => apply_alter_table_op(schema, table_schema.as_deref(), table_name, ops),
411        DdlOp::DropTable { schema: s, name } => apply_drop_table_op(schema, s.as_deref(), name),
412        DdlOp::DropIndexOnTable {
413            table_schema,
414            table_name,
415            index_name,
416        } => apply_drop_index_on_table_op(schema, table_schema.as_deref(), table_name, index_name),
417        DdlOp::DropIndexAcrossTables {
418            index_schema,
419            index_name,
420        } => apply_drop_index_across_tables_op(schema, index_schema, index_name),
421    }
422}
423
424fn apply_create_table_op(schema: &mut SqlSchema, if_not_exists: bool, table: &TableSchema) {
425    let key = (table.schema.clone(), table.name.clone());
426    if !(if_not_exists && schema.tables.contains_key(&key)) {
427        schema.tables.insert(key, table.clone());
428    }
429}
430
431fn apply_create_index_op(
432    schema: &mut SqlSchema,
433    table_schema: Option<&str>,
434    table_name: &str,
435    index: &IndexSchema,
436) {
437    if let Some(key) = schema.resolve_table_key(table_schema, table_name)
438        && let Some(table) = schema.tables.get_mut(&key)
439    {
440        upsert_index(&mut table.indexes, index.clone());
441    }
442}
443
444fn apply_alter_table_op(
445    schema: &mut SqlSchema,
446    table_schema: Option<&str>,
447    table_name: &str,
448    ops: &[AlterOp],
449) {
450    let Some(mut key) = schema.resolve_table_key(table_schema, table_name) else {
451        return;
452    };
453    for alter_op in ops {
454        key = apply_extracted_alter(schema, key, alter_op);
455    }
456}
457
458fn apply_drop_table_op(schema: &mut SqlSchema, table_schema: Option<&str>, name: &str) {
459    if let Some(key) = schema.resolve_table_key(table_schema, name) {
460        schema.tables.remove(&key);
461    }
462}
463
464fn apply_drop_index_on_table_op(
465    schema: &mut SqlSchema,
466    table_schema: Option<&str>,
467    table_name: &str,
468    index_name: &str,
469) {
470    if let Some(key) = schema.resolve_table_key(table_schema, table_name)
471        && let Some(table) = schema.tables.get_mut(&key)
472    {
473        remove_named_index(table, index_name);
474    }
475}
476
477fn apply_drop_index_across_tables_op(
478    schema: &mut SqlSchema,
479    index_schema: &Option<String>,
480    index_name: &str,
481) {
482    for table in schema.tables.values_mut() {
483        if index_schema.is_none() || table.schema == *index_schema {
484            remove_named_index(table, index_name);
485        }
486    }
487}
488
489fn apply_extracted_alter(schema: &mut SqlSchema, key: TableKey, op: &AlterOp) -> TableKey {
490    if let AlterOp::Table(TableAlterOp::RenameTable {
491        new_schema,
492        new_name,
493    }) = op
494    {
495        let Some(mut table) = schema.tables.remove(&key) else {
496            return key;
497        };
498        let effective_schema = new_schema.clone().or(table.schema.clone());
499        table.schema = effective_schema.clone();
500        table.name = new_name.clone();
501        let new_key = (effective_schema, new_name.clone());
502        schema.tables.insert(new_key.clone(), table);
503        return new_key;
504    }
505    let Some(table) = schema.tables.get_mut(&key) else {
506        return key;
507    };
508    match op {
509        AlterOp::Column(col_op) => apply_column_alter_op(table, col_op),
510        AlterOp::Table(table_op) => apply_table_alter_op(table, table_op),
511    }
512    key
513}
514
515fn apply_column_flags(
516    table: &mut TableSchema,
517    col: &str,
518    ty: ColumnTypeClass,
519    is_pk: bool,
520    unique_index: &Option<Option<String>>,
521) {
522    table.columns.insert(col.to_owned(), ty);
523    if is_pk {
524        table.primary_key = vec![col.to_owned()];
525    }
526    if let Some(name) = unique_index {
527        upsert_index(
528            &mut table.indexes,
529            IndexSchema {
530                name: name.clone(),
531                columns: vec![col.to_owned()],
532            },
533        );
534    }
535}
536
537fn apply_column_alter_op(table: &mut TableSchema, op: &ColumnAlterOp) {
538    match op {
539        ColumnAlterOp::AddColumn {
540            name,
541            ty,
542            is_pk,
543            unique_index,
544        }
545        | ColumnAlterOp::ModifyColumn {
546            name,
547            ty,
548            is_pk,
549            unique_index,
550        } => apply_column_flags(table, name, *ty, *is_pk, unique_index),
551        ColumnAlterOp::DropColumn { name } => drop_column_from_table(table, name),
552        ColumnAlterOp::RenameColumn { old, new } => rename_column_in_table(table, old, new),
553        ColumnAlterOp::ChangeColumn {
554            old,
555            new,
556            ty,
557            is_pk,
558            unique_index,
559        } => {
560            rename_column_in_table(table, old, new);
561            apply_column_flags(table, new, *ty, *is_pk, unique_index);
562        }
563        ColumnAlterOp::SetColumnType { name, ty } => {
564            if table.columns.contains_key(name) {
565                table.columns.insert(name.clone(), *ty);
566            }
567        }
568    }
569}
570
571fn apply_table_alter_op(table: &mut TableSchema, op: &TableAlterOp) {
572    match op {
573        TableAlterOp::SetPrimaryKey { columns } => table.primary_key = columns.clone(),
574        TableAlterOp::AddIndex { index } => upsert_index(&mut table.indexes, index.clone()),
575        TableAlterOp::PromoteIndexToPk { index_name } => promote_index_to_pk(table, index_name),
576        TableAlterOp::DropNamedIndex { name } => remove_named_index(table, name),
577        TableAlterOp::DropPrimaryKey => table.primary_key.clear(),
578        TableAlterOp::RenameTable { .. } => {}
579    }
580}
581
582fn apply_column_def(table: &mut TableSchema, column: &ColumnDef, dialect: SqlDialect) {
583    let col_name = normalize_ident(&column.name, dialect);
584    table
585        .columns
586        .insert(col_name.clone(), classify_data_type(&column.data_type));
587    for opt_def in &column.options {
588        apply_column_option(
589            table,
590            &col_name,
591            opt_def
592                .name
593                .as_ref()
594                .map(|ident| normalize_ident(ident, dialect)),
595            &opt_def.option,
596            dialect,
597        );
598    }
599}
600
601fn apply_column_option(
602    table: &mut TableSchema,
603    col_name: &str,
604    constraint_name: Option<String>,
605    option: &ColumnOption,
606    dialect: SqlDialect,
607) {
608    match option {
609        ColumnOption::PrimaryKey(_) => {
610            table.primary_key = vec![col_name.to_owned()];
611        }
612        ColumnOption::Unique(unique) => {
613            let name = unique
614                .name
615                .as_ref()
616                .or(unique.index_name.as_ref())
617                .map(|ident| normalize_ident(ident, dialect))
618                .or(constraint_name);
619            upsert_index(
620                &mut table.indexes,
621                IndexSchema {
622                    name,
623                    columns: vec![col_name.to_owned()],
624                },
625            );
626        }
627        _ => {}
628    }
629}
630
631fn apply_table_constraint(
632    table: &mut TableSchema,
633    constraint: &TableConstraint,
634    dialect: SqlDialect,
635) {
636    match constraint {
637        TableConstraint::PrimaryKey(pk) => {
638            set_primary_key_from_columns(table, &pk.columns, dialect)
639        }
640        TableConstraint::Unique(unique) => {
641            let name = unique.name.as_ref().or(unique.index_name.as_ref());
642            add_index_from_columns(table, name, &unique.columns, dialect);
643        }
644        TableConstraint::Index(index) => {
645            add_index_from_columns(table, index.name.as_ref(), &index.columns, dialect);
646        }
647        TableConstraint::FulltextOrSpatial(index) => {
648            add_index_from_columns(
649                table,
650                index.opt_index_name.as_ref(),
651                &index.columns,
652                dialect,
653            );
654        }
655        TableConstraint::PrimaryKeyUsingIndex(using_idx) => {
656            promote_index_to_pk(table, &normalize_ident(&using_idx.index_name, dialect));
657        }
658        _ => {}
659    }
660}
661
662fn set_primary_key_from_columns(
663    table: &mut TableSchema,
664    columns: &[IndexColumn],
665    dialect: SqlDialect,
666) {
667    let cols = extract_index_columns(columns, dialect);
668    if !cols.is_empty() {
669        table.primary_key = cols;
670    }
671}
672
673fn add_index_from_columns(
674    table: &mut TableSchema,
675    name: Option<&Ident>,
676    columns: &[IndexColumn],
677    dialect: SqlDialect,
678) {
679    let cols = extract_index_columns(columns, dialect);
680    if !cols.is_empty() {
681        upsert_index(
682            &mut table.indexes,
683            IndexSchema {
684                name: name.map(|ident| normalize_ident(ident, dialect)),
685                columns: cols,
686            },
687        );
688    }
689}
690
691fn promote_index_to_pk(table: &mut TableSchema, idx_name: &str) {
692    if let Some(found) = table
693        .indexes
694        .iter()
695        .find(|idx| idx.name.as_deref() == Some(idx_name))
696    {
697        table.primary_key = found.columns.clone();
698    }
699}
700
701fn remove_named_index(table: &mut TableSchema, target: &str) {
702    table
703        .indexes
704        .retain(|idx| idx.name.as_deref() != Some(target));
705}
706
707fn drop_column_from_table(table: &mut TableSchema, col: &str) {
708    table.columns.remove(col);
709    table.primary_key.retain(|c| c != col);
710    for idx in &mut table.indexes {
711        idx.columns.retain(|c| c != col);
712    }
713    table.indexes.retain(|idx| !idx.columns.is_empty());
714}
715
716fn rename_column_in_table(table: &mut TableSchema, old: &str, new: &str) {
717    if let Some(ty) = table.columns.remove(old) {
718        table.columns.insert(new.to_owned(), ty);
719    }
720    for col in &mut table.primary_key {
721        if col == old {
722            *col = new.to_owned();
723        }
724    }
725    for idx in &mut table.indexes {
726        for col in &mut idx.columns {
727            if col == old {
728                *col = new.to_owned();
729            }
730        }
731    }
732}
733
734fn upsert_index(indexes: &mut Vec<IndexSchema>, entry: IndexSchema) {
735    if let Some(ref name) = entry.name
736        && let Some(existing) = indexes
737            .iter_mut()
738            .find(|idx| idx.name.as_deref() == Some(name.as_str()))
739    {
740        *existing = entry;
741        return;
742    }
743    indexes.push(entry);
744}
745
746fn extract_index_columns(columns: &[IndexColumn], dialect: SqlDialect) -> Vec<String> {
747    let mut out = Vec::with_capacity(columns.len());
748    for col in columns {
749        let Some(name) = extract_expr_column_ident(&col.column.expr, dialect) else {
750            break;
751        };
752        out.push(name);
753    }
754    out
755}
756
757fn extract_pk_expr_columns(expr: &Expr, dialect: SqlDialect) -> Vec<String> {
758    match expr {
759        Expr::Tuple(items) => items
760            .iter()
761            .filter_map(|item| extract_expr_column_ident(item, dialect))
762            .collect(),
763        _ => extract_expr_column_ident(expr, dialect)
764            .into_iter()
765            .collect(),
766    }
767}
768
769fn extract_expr_column_ident(mut expr: &Expr, dialect: SqlDialect) -> Option<String> {
770    loop {
771        match expr {
772            Expr::Nested(inner) | Expr::Collate { expr: inner, .. } => expr = inner,
773            Expr::Identifier(ident) => return Some(normalize_ident(ident, dialect)),
774            Expr::CompoundIdentifier(idents) => {
775                return idents.last().map(|ident| normalize_ident(ident, dialect));
776            }
777            _ => return None,
778        }
779    }
780}
781
782pub(crate) fn classify_data_type(data_type: &DataType) -> ColumnTypeClass {
783    match data_type {
784        DataType::Nullable(inner)
785        | DataType::LowCardinality(inner)
786        | DataType::Collate(inner, _)
787        | DataType::Zerofill(inner) => classify_data_type(inner),
788        DataType::Character(_)
789        | DataType::Char(_)
790        | DataType::CharacterVarying(_)
791        | DataType::CharVarying(_)
792        | DataType::Varchar(_)
793        | DataType::Nvarchar(_)
794        | DataType::CharacterLargeObject(_)
795        | DataType::CharLargeObject(_)
796        | DataType::Clob(_)
797        | DataType::Text
798        | DataType::TinyText
799        | DataType::MediumText
800        | DataType::LongText
801        | DataType::String(_)
802        | DataType::FixedString(_) => ColumnTypeClass::Text,
803        DataType::Bool | DataType::Boolean => ColumnTypeClass::Boolean,
804        DataType::Date
805        | DataType::Date32
806        | DataType::Time(_, _)
807        | DataType::Datetime(_)
808        | DataType::Datetime64(_, _)
809        | DataType::Timestamp(_, _)
810        | DataType::TimestampNtz(_)
811        | DataType::Interval { .. } => ColumnTypeClass::Temporal,
812        DataType::Binary(_)
813        | DataType::Varbinary(_)
814        | DataType::Blob(_)
815        | DataType::TinyBlob
816        | DataType::MediumBlob
817        | DataType::LongBlob
818        | DataType::Bytes(_)
819        | DataType::Bytea => ColumnTypeClass::Binary,
820        DataType::Custom(name, _) => classify_custom_type(name),
821        other if is_numeric_data_type(other) => ColumnTypeClass::Numeric,
822        _ => ColumnTypeClass::Other,
823    }
824}
825
826fn is_numeric_data_type(data_type: &DataType) -> bool {
827    matches!(
828        data_type,
829        DataType::Numeric(_)
830            | DataType::Decimal(_)
831            | DataType::DecimalUnsigned(_)
832            | DataType::BigNumeric(_)
833            | DataType::BigDecimal(_)
834            | DataType::Dec(_)
835            | DataType::DecUnsigned(_)
836            | DataType::Float(_)
837            | DataType::FloatUnsigned(_)
838            | DataType::Float4
839            | DataType::Float32
840            | DataType::Float64
841            | DataType::Float8
842            | DataType::Real
843            | DataType::RealUnsigned
844            | DataType::Double(_)
845            | DataType::DoubleUnsigned(_)
846            | DataType::DoublePrecision
847            | DataType::DoublePrecisionUnsigned
848            | DataType::TinyInt(_)
849            | DataType::TinyIntUnsigned(_)
850            | DataType::UTinyInt
851            | DataType::Int2(_)
852            | DataType::Int2Unsigned(_)
853            | DataType::SmallInt(_)
854            | DataType::SmallIntUnsigned(_)
855            | DataType::USmallInt
856            | DataType::MediumInt(_)
857            | DataType::MediumIntUnsigned(_)
858            | DataType::Int(_)
859            | DataType::IntUnsigned(_)
860            | DataType::Int4(_)
861            | DataType::Int4Unsigned(_)
862            | DataType::Integer(_)
863            | DataType::IntegerUnsigned(_)
864            | DataType::Int8(_)
865            | DataType::Int8Unsigned(_)
866            | DataType::Int16
867            | DataType::Int32
868            | DataType::Int64
869            | DataType::Int128
870            | DataType::Int256
871            | DataType::HugeInt
872            | DataType::UHugeInt
873            | DataType::UInt8
874            | DataType::UInt16
875            | DataType::UInt32
876            | DataType::UInt64
877            | DataType::UInt128
878            | DataType::UInt256
879            | DataType::BigInt(_)
880            | DataType::BigIntUnsigned(_)
881            | DataType::UBigInt
882            | DataType::Signed
883            | DataType::SignedInteger
884            | DataType::Unsigned
885            | DataType::UnsignedInteger
886    )
887}
888
889fn classify_custom_type(name: &ObjectName) -> ColumnTypeClass {
890    let Some(last) = object_name_last_ident(name, SqlDialect::Generic) else {
891        return ColumnTypeClass::Other;
892    };
893    match last.as_str() {
894        "citext" | "bpchar" | "varchar2" | "nvarchar2" | "nchar" | "ntext" | "tinytext"
895        | "mediumtext" | "longtext" | "text" | "string" | "varchar" | "char" | "character"
896        | "clob" => ColumnTypeClass::Text,
897        "serial" | "bigserial" | "smallserial" | "serial2" | "serial4" | "serial8" | "money"
898        | "smallmoney" | "number" | "int" | "integer" | "bigint" | "smallint" | "tinyint"
899        | "mediumint" | "decimal" | "numeric" | "float" | "double" | "real" => {
900            ColumnTypeClass::Numeric
901        }
902        "bool" | "boolean" => ColumnTypeClass::Boolean,
903        "date" | "time" | "timetz" | "timestamp" | "timestamptz" | "datetime" | "smalldatetime"
904        | "interval" | "year" => ColumnTypeClass::Temporal,
905        "blob" | "bytea" | "binary" | "varbinary" | "tinyblob" | "mediumblob" | "longblob" => {
906            ColumnTypeClass::Binary
907        }
908        _ => ColumnTypeClass::Other,
909    }
910}