|
| 1 | +use crate::binder::BindError; |
1 | 2 | use anyhow::Result; |
2 | | -use sqlparser::ast::Expr; |
| 3 | +use itertools::Itertools; |
| 4 | +use sqlparser::ast::{Expr, Ident}; |
| 5 | +use std::slice; |
3 | 6 |
|
4 | 7 | use super::Binder; |
5 | 8 | use crate::expression::ScalarExpression; |
6 | 9 |
|
7 | 10 | impl Binder { |
8 | 11 | pub(crate) fn bind_expr(&mut self, expr: &Expr) -> Result<ScalarExpression> { |
9 | | - todo!() |
| 12 | + match expr { |
| 13 | + Expr::Identifier(ident) => { |
| 14 | + self.bind_column_ref_from_identifiers(slice::from_ref(ident)) |
| 15 | + } |
| 16 | + _ => { |
| 17 | + todo!() |
| 18 | + } |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + pub fn bind_column_ref_from_identifiers( |
| 23 | + &mut self, |
| 24 | + idents: &[Ident], |
| 25 | + ) -> Result<ScalarExpression> { |
| 26 | + let idents = idents |
| 27 | + .iter() |
| 28 | + .map(|ident| Ident::new(ident.value.to_lowercase())) |
| 29 | + .collect_vec(); |
| 30 | + let (_schema_name, table_name, column_name) = match idents.as_slice() { |
| 31 | + [column] => (None, None, &column.value), |
| 32 | + [table, column] => (None, Some(&table.value), &column.value), |
| 33 | + [schema, table, column] => (Some(&schema.value), Some(&table.value), &column.value), |
| 34 | + _ => { |
| 35 | + return Err(BindError::InvalidColumn( |
| 36 | + idents |
| 37 | + .iter() |
| 38 | + .map(|ident| ident.value.clone()) |
| 39 | + .join(".") |
| 40 | + .to_string(), |
| 41 | + ) |
| 42 | + .into()) |
| 43 | + } |
| 44 | + }; |
| 45 | + |
| 46 | + if let Some(table) = table_name { |
| 47 | + let table_catalog = self |
| 48 | + .context |
| 49 | + .catalog |
| 50 | + .get_table_by_name(table) |
| 51 | + .ok_or_else(|| BindError::InvalidTable(table.to_string()))?; |
| 52 | + |
| 53 | + let column_catalog = table_catalog |
| 54 | + .get_column_by_name(column_name) |
| 55 | + .ok_or_else(|| BindError::InvalidColumn(column_name.to_string()))?; |
| 56 | + Ok(ScalarExpression::ColumnRef(column_catalog.clone())) |
| 57 | + } else { |
| 58 | + // handle col syntax |
| 59 | + let mut got_column = None; |
| 60 | + for table_catalog in self.context.catalog.tables.values() { |
| 61 | + if let Some(column_catalog) = table_catalog.get_column_by_name(column_name) { |
| 62 | + if got_column.is_some() { |
| 63 | + return Err(BindError::InvalidColumn(column_name.to_string()).into()); |
| 64 | + } |
| 65 | + got_column = Some(column_catalog); |
| 66 | + } |
| 67 | + } |
| 68 | + if got_column.is_none() { |
| 69 | + if let Some(expr) = self.context.aliases.get(column_name) { |
| 70 | + return Ok(expr.clone()); |
| 71 | + } |
| 72 | + } |
| 73 | + let column_catalog = |
| 74 | + got_column.ok_or_else(|| BindError::InvalidColumn(column_name.to_string()))?; |
| 75 | + Ok(ScalarExpression::ColumnRef(column_catalog.clone())) |
| 76 | + } |
10 | 77 | } |
11 | 78 | } |
0 commit comments