Skip to main content

codeint_lang_sql/schema/
types.rs

1use std::collections::{BTreeMap, BTreeSet};
2
3use sqlparser::ast::{Ident, ObjectName};
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
6pub enum ColumnTypeClass {
7    Text,
8    Numeric,
9    Boolean,
10    Temporal,
11    Binary,
12    Other,
13}
14
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub struct IndexSchema {
17    pub name: Option<String>,
18    pub columns: Vec<String>,
19}
20
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct TableSchema {
23    pub schema: Option<String>,
24    pub name: String,
25    pub columns: BTreeMap<String, ColumnTypeClass>,
26    pub primary_key: Vec<String>,
27    pub indexes: Vec<IndexSchema>,
28}
29
30impl TableSchema {
31    pub fn has_column(&self, column: &str) -> bool {
32        self.columns.contains_key(&column.to_ascii_lowercase())
33    }
34
35    pub fn column_type(&self, column: &str) -> Option<ColumnTypeClass> {
36        self.columns.get(&column.to_ascii_lowercase()).copied()
37    }
38
39    pub fn is_indexed_column(&self, column: &str) -> bool {
40        let lower = column.to_ascii_lowercase();
41        self.primary_key.first().map(String::as_str) == Some(lower.as_str())
42            || self
43                .indexes
44                .iter()
45                .any(|idx| idx.columns.first().map(String::as_str) == Some(lower.as_str()))
46    }
47
48    pub(crate) fn is_covered_by_prefix(
49        &self,
50        column: &str,
51        prefix_cols: &BTreeSet<String>,
52    ) -> bool {
53        let lower = column.to_ascii_lowercase();
54        index_covers_with_prefix(&self.primary_key, &lower, prefix_cols)
55            || self
56                .indexes
57                .iter()
58                .any(|idx| index_covers_with_prefix(&idx.columns, &lower, 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) tables: BTreeMap<TableKey, TableSchema>,
87}
88
89impl SqlSchema {
90    pub fn table_count(&self) -> usize {
91        self.tables.len()
92    }
93
94    pub fn is_empty(&self) -> bool {
95        self.tables.is_empty()
96    }
97
98    pub fn get_table(&self, schema: Option<&str>, name: &str) -> Option<&TableSchema> {
99        let key = self.resolve_table_key(schema, name)?;
100        self.tables.get(&key)
101    }
102
103    pub(crate) fn resolve_table_key(&self, schema: Option<&str>, name: &str) -> Option<TableKey> {
104        let norm_schema = schema.map(str::to_ascii_lowercase);
105        let norm_name = name.to_ascii_lowercase();
106        let exact = (norm_schema.clone(), norm_name.clone());
107        if self.tables.contains_key(&exact) {
108            return Some(exact);
109        }
110        if norm_schema.is_some() {
111            return None;
112        }
113        let mut matches = self
114            .tables
115            .keys()
116            .filter(|(_, table_name)| table_name == &norm_name);
117        let first = matches.next()?;
118        if matches.next().is_some() {
119            return None;
120        }
121        Some(first.clone())
122    }
123}
124
125pub(crate) fn normalize_ident(ident: &Ident) -> String {
126    ident.value.to_ascii_lowercase()
127}
128
129pub(crate) fn split_object_name(name: &ObjectName) -> Option<(Option<String>, String)> {
130    let parts: Vec<String> = name
131        .0
132        .iter()
133        .filter_map(|part| part.as_ident().map(normalize_ident))
134        .collect();
135    match parts.as_slice() {
136        [] => None,
137        [table] => Some((None, table.clone())),
138        [.., schema, table] => Some((Some(schema.clone()), table.clone())),
139    }
140}
141
142pub(crate) fn object_name_last_ident(name: &ObjectName) -> Option<String> {
143    name.0
144        .last()
145        .and_then(|part| part.as_ident())
146        .map(normalize_ident)
147}