use std::collections::{BTreeMap, BTreeSet};
use crate::ast::{Expr, Name, TableRef};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ColumnClass {
Text,
Numeric,
Boolean,
Other,
Unknown,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Column {
pub class: ColumnClass,
pub collation: Option<String>,
}
impl Column {
pub fn new(class: ColumnClass) -> Self {
Column {
class,
collation: None,
}
}
pub fn text() -> Self {
Column::new(ColumnClass::Text)
}
pub fn numeric() -> Self {
Column::new(ColumnClass::Numeric)
}
pub fn boolean() -> Self {
Column::new(ColumnClass::Boolean)
}
pub fn other() -> Self {
Column::new(ColumnClass::Other)
}
pub fn unknown() -> Self {
Column::new(ColumnClass::Unknown)
}
pub fn with_collation(mut self, collation: impl Into<String>) -> Self {
self.collation = Some(collation.into());
self
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Schema {
tables: BTreeMap<Vec<String>, BTreeMap<String, Column>>,
keys: BTreeMap<Vec<String>, Vec<Vec<String>>>,
keys_unreliable: BTreeSet<Vec<String>>,
columns_complete: BTreeSet<Vec<String>>,
}
impl Schema {
pub fn new() -> Self {
Schema::default()
}
pub fn with_column(self, table: &str, column: &str, c: Column) -> Self {
self.with_qualified_column(&[table], column, c)
}
pub fn with_qualified_column(mut self, table: &[&str], column: &str, c: Column) -> Self {
self.tables
.entry(table.iter().map(|s| s.to_string()).collect())
.or_default()
.insert(column.to_string(), c);
self
}
pub fn set_column(&mut self, table: Vec<String>, column: String, c: Column) {
self.tables.entry(table).or_default().insert(column, c);
}
pub fn drop_column(&mut self, table: &Name, column: &str) {
if let Some(t) = self.tables.get_mut(&table.0) {
t.remove(column);
}
if let Some(ks) = self.keys.get_mut(&table.0) {
ks.retain(|k| !k.iter().any(|c| c == column));
}
}
pub fn drop_table(&mut self, table: &Name) {
self.tables.remove(&table.0);
self.keys.remove(&table.0);
self.keys_unreliable.remove(&table.0);
self.columns_complete.remove(&table.0);
}
pub fn with_unique_key(mut self, table: &str, columns: &[&str]) -> Self {
self.add_unique_key(
vec![table.to_string()],
columns.iter().map(|c| c.to_string()).collect(),
);
self
}
pub fn add_unique_key(&mut self, table: Vec<String>, columns: Vec<String>) {
let ks = self.keys.entry(table).or_default();
if !ks.contains(&columns) {
ks.push(columns);
}
}
pub fn mark_keys_unreliable(&mut self, table: Vec<String>) {
self.keys_unreliable.insert(table);
}
pub fn mark_all_keys_unreliable(&mut self) {
let all: Vec<Vec<String>> = self.keys.keys().cloned().collect();
self.keys_unreliable.extend(all);
}
pub fn mark_columns_complete(&mut self, table: Vec<String>) {
self.columns_complete.insert(table);
}
pub fn complete_columns(&self, table: &Name) -> Option<Vec<&str>> {
if !self.columns_complete.contains(&table.0) {
return None;
}
Some(
self.tables
.get(&table.0)?
.keys()
.map(String::as_str)
.collect(),
)
}
pub fn unique_keys(&self, table: &Name) -> Option<&[Vec<String>]> {
if self.keys_unreliable.contains(&table.0) {
return None;
}
self.keys
.get(&table.0)
.map(Vec::as_slice)
.filter(|k| !k.is_empty())
}
pub fn is_empty(&self) -> bool {
self.tables.is_empty()
}
pub fn get(&self, table: &Name, column: &str) -> Option<&Column> {
self.tables.get(&table.0)?.get(column)
}
fn knows_table(&self, table: &Name) -> bool {
self.tables.contains_key(&table.0)
}
}
#[derive(Clone, Debug, Default)]
pub struct Scopes<'a> {
schema: Option<&'a Schema>,
stack: Vec<Vec<(String, Option<Name>)>>,
}
impl<'a> Scopes<'a> {
pub fn new(schema: Option<&'a Schema>) -> Self {
Scopes {
schema,
stack: Vec::new(),
}
}
pub fn push_from(&mut self, from: &[TableRef]) {
if self.schema.is_none() {
return;
}
let mut scope = Vec::new();
for t in from {
collect(t, &mut scope);
}
self.stack.push(scope);
}
pub fn push_target(&mut self, table: &Name, alias: Option<&str>, from: &[TableRef]) {
if self.schema.is_none() {
return;
}
let binding = alias
.map(str::to_string)
.unwrap_or_else(|| table.last().to_string());
let mut scope = vec![(binding, Some(table.clone()))];
for t in from {
collect(t, &mut scope);
}
self.stack.push(scope);
}
pub fn push_upsert(&mut self, table: &Name) {
if self.schema.is_none() {
return;
}
self.stack.push(vec![
(table.last().to_string(), Some(table.clone())),
("excluded".to_string(), Some(table.clone())),
]);
}
pub fn unique_keys(&self, table: &Name) -> Option<&'a [Vec<String>]> {
self.schema?.unique_keys(table)
}
pub fn complete_columns(&self, table: &Name) -> Option<Vec<&'a str>> {
self.schema?.complete_columns(table)
}
pub fn pop(&mut self) {
if self.schema.is_some() {
self.stack.pop();
}
}
pub fn is_non_text_column(&self, e: &Expr) -> bool {
self.column(e)
.is_some_and(|c| !matches!(c.class, ColumnClass::Text | ColumnClass::Unknown))
}
pub fn non_bytewise_collation(&self, e: &Expr) -> Option<String> {
let c = self.column(e)?;
match (&c.class, &c.collation) {
(ColumnClass::Text, Some(name)) if !is_bytewise_collation(name) => Some(name.clone()),
_ => None,
}
}
fn column(&self, e: &Expr) -> Option<&Column> {
let schema = self.schema?;
match e {
Expr::Nested(x) => self.column(x),
Expr::Column(name) => self.column_of(schema, name),
_ => None,
}
}
fn column_of<'s>(&self, schema: &'s Schema, name: &Name) -> Option<&'s Column> {
match name.0.as_slice() {
[col] => {
for scope in self.stack.iter().rev() {
let mut found: Vec<&'s Column> = Vec::new();
let mut unknown = false;
for (_, table) in scope {
match table {
Some(t) if schema.knows_table(t) => {
if let Some(c) = schema.get(t, col) {
found.push(c);
}
}
_ => unknown = true,
}
}
match (found.first(), unknown) {
(Some(first), false) if found.iter().all(|c| c == first) => {
return Some(*first);
}
(None, false) => continue,
_ => return None,
}
}
None
}
[qual, col] => {
for scope in self.stack.iter().rev() {
if let Some((_, table)) = scope.iter().find(|(b, _)| b == qual) {
return schema.get(table.as_ref()?, col);
}
}
None
}
[s, t, col] => schema.get(&Name(vec![s.clone(), t.clone()]), col),
_ => None,
}
}
}
pub fn is_bytewise_collation(name: &str) -> bool {
let n = name
.trim()
.trim_matches(['"', '`', '\''])
.to_ascii_lowercase();
matches!(n.as_str(), "c" | "posix" | "ucs_basic" | "binary") || n.ends_with("_bin")
}
fn collect(t: &TableRef, out: &mut Vec<(String, Option<Name>)>) {
match t {
TableRef::Table { name, alias } => out.push((
alias.clone().unwrap_or_else(|| name.last().to_string()),
Some(name.clone()),
)),
TableRef::Subquery { alias, .. } => out.push((alias.clone(), None)),
TableRef::Function { name, alias, .. } => {
out.push((alias.clone().unwrap_or_else(|| name.clone()), None))
}
TableRef::Join { left, right, .. } => {
collect(left, out);
collect(right, out);
}
}
}