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