Skip to main content

codeint_lang_sql/schema/
types.rs

1use std::collections::{BTreeMap, BTreeSet};
2
3use sqlparser::ast::{Ident, ObjectName};
4
5use crate::SqlDialect;
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
8pub enum ColumnTypeClass {
9    Text,
10    Numeric,
11    Boolean,
12    Temporal,
13    Binary,
14    Other,
15}
16
17#[derive(Clone, Debug, PartialEq, Eq)]
18pub struct IndexSchema {
19    pub name: Option<String>,
20    pub columns: Vec<String>,
21}
22
23#[derive(Clone, Debug, PartialEq, Eq)]
24pub struct TableSchema {
25    pub schema: Option<String>,
26    pub name: String,
27    pub columns: BTreeMap<String, ColumnTypeClass>,
28    pub primary_key: Vec<String>,
29    pub indexes: Vec<IndexSchema>,
30}
31
32impl TableSchema {
33    pub fn has_column(&self, column: &str) -> bool {
34        self.columns.contains_key(column)
35    }
36
37    pub fn column_type(&self, column: &str) -> Option<ColumnTypeClass> {
38        self.columns.get(column).copied()
39    }
40
41    pub fn is_indexed_column(&self, column: &str) -> bool {
42        self.primary_key.first().map(String::as_str) == Some(column)
43            || self
44                .indexes
45                .iter()
46                .any(|idx| idx.columns.first().map(String::as_str) == Some(column))
47    }
48
49    pub(crate) fn is_covered_by_prefix(
50        &self,
51        column: &str,
52        prefix_cols: &BTreeSet<String>,
53    ) -> bool {
54        index_covers_with_prefix(&self.primary_key, column, prefix_cols)
55            || self
56                .indexes
57                .iter()
58                .any(|idx| index_covers_with_prefix(&idx.columns, column, prefix_cols))
59    }
60
61    pub(crate) fn has_leading_indexed_in(&self, cols: &BTreeSet<String>) -> bool {
62        self.primary_key.first().is_some_and(|pk| cols.contains(pk))
63            || self
64                .indexes
65                .iter()
66                .any(|idx| idx.columns.first().is_some_and(|c| cols.contains(c)))
67    }
68}
69
70fn index_covers_with_prefix(cols: &[String], target: &str, prefix_cols: &BTreeSet<String>) -> bool {
71    for col in cols {
72        if col == target {
73            return true;
74        }
75        if !prefix_cols.contains(col) {
76            return false;
77        }
78    }
79    false
80}
81
82pub(crate) type TableKey = (Option<String>, String);
83
84#[derive(Clone, Debug, Default, PartialEq, Eq)]
85pub struct SqlSchema {
86    pub(crate) dialect: SqlDialect,
87    pub(crate) tables: BTreeMap<TableKey, TableSchema>,
88}
89
90impl SqlSchema {
91    pub(crate) fn with_dialect(dialect: SqlDialect) -> SqlSchema {
92        SqlSchema {
93            dialect,
94            tables: BTreeMap::new(),
95        }
96    }
97
98    pub fn table_count(&self) -> usize {
99        self.tables.len()
100    }
101
102    pub fn is_empty(&self) -> bool {
103        self.tables.is_empty()
104    }
105
106    pub fn get_table(&self, schema: Option<&str>, name: &str) -> Option<&TableSchema> {
107        let key = self.resolve_table_key(schema, name)?;
108        self.tables.get(&key)
109    }
110
111    pub(crate) fn resolve_table_key(&self, schema: Option<&str>, name: &str) -> Option<TableKey> {
112        let (norm_schema, norm_name) = if self.dialect == SqlDialect::Postgresql {
113            (schema.map(str::to_owned), name.to_owned())
114        } else {
115            (
116                schema.map(str::to_ascii_lowercase),
117                name.to_ascii_lowercase(),
118            )
119        };
120        let exact = (norm_schema.clone(), norm_name.clone());
121        if self.tables.contains_key(&exact) {
122            return Some(exact);
123        }
124        if norm_schema.is_some() {
125            return None;
126        }
127        let mut matches = self
128            .tables
129            .keys()
130            .filter(|(_, table_name)| table_name == &norm_name);
131        let first = matches.next()?;
132        if matches.next().is_some() {
133            return None;
134        }
135        Some(first.clone())
136    }
137}
138
139pub(crate) fn normalize_ident(ident: &Ident, dialect: SqlDialect) -> String {
140    if dialect == SqlDialect::Postgresql && ident.quote_style.is_some() {
141        ident.value.clone()
142    } else {
143        ident.value.to_ascii_lowercase()
144    }
145}
146
147pub(crate) fn split_object_name(
148    name: &ObjectName,
149    dialect: SqlDialect,
150) -> Option<(Option<String>, String)> {
151    let parts: Vec<String> = name
152        .0
153        .iter()
154        .filter_map(|part| part.as_ident().map(|ident| normalize_ident(ident, dialect)))
155        .collect();
156    match parts.as_slice() {
157        [] => None,
158        [table] => Some((None, table.clone())),
159        [.., schema, table] => Some((Some(schema.clone()), table.clone())),
160    }
161}
162
163pub(crate) fn object_name_last_ident(name: &ObjectName, dialect: SqlDialect) -> Option<String> {
164    name.0
165        .last()
166        .and_then(|part| part.as_ident())
167        .map(|ident| normalize_ident(ident, dialect))
168}