From ce1af934e894ec8bc1ed103b85d0fb2d354ac19f Mon Sep 17 00:00:00 2001 From: Fedomn Date: Sat, 8 Oct 2022 18:11:48 +0800 Subject: [PATCH] feat(alias): support alias subquery Signed-off-by: Fedomn --- src/binder/table/mod.rs | 18 +++++++++++++++++- src/catalog/mod.rs | 15 +++++++++++++++ tests/slt/alias.slt | 11 +++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) diff --git a/src/binder/table/mod.rs b/src/binder/table/mod.rs index da626fe..8128f6f 100644 --- a/src/binder/table/mod.rs +++ b/src/binder/table/mod.rs @@ -4,6 +4,7 @@ pub use join::*; use sqlparser::ast::{TableFactor, TableWithJoins}; use super::{BindError, Binder, BoundSelect}; +use crate::binder::BoundExpr::ColumnRef; use crate::catalog::{ColumnCatalog, ColumnId, TableCatalog, TableId}; pub static DEFAULT_DATABASE_NAME: &str = "postgres"; @@ -131,9 +132,24 @@ impl Binder { subquery, alias, } => { + // handle subquery table let table = self.bind_select(subquery)?; if let Some(alias) = alias { - todo!("alias for subquery {}", alias) + // add subquery into context + let columns = table + .select_list + .iter() + .map(|expr| match expr { + ColumnRef(col) => col.column_catalog.clone(), + _ => { + unreachable!("subquery select list should only contains column ref") + } + }) + .collect::>(); + let table_alias = alias.to_string().to_lowercase(); + let table_catalog = + TableCatalog::new_from_columns(table_alias.clone(), columns); + self.context.tables.insert(table_alias, table_catalog); } Ok(BoundTableRef::Subquery(Box::new(table))) } diff --git a/src/catalog/mod.rs b/src/catalog/mod.rs index af3a2ed..1258a45 100644 --- a/src/catalog/mod.rs +++ b/src/catalog/mod.rs @@ -52,6 +52,21 @@ impl TableCatalog { .map(|id| self.columns.get(id).cloned().unwrap()) .collect() } + + pub fn new_from_columns(table_id: String, columns: Vec) -> Self { + let mut columns_tree = BTreeMap::new(); + let mut column_ids = Vec::new(); + for c in columns { + column_ids.push(c.column_id.clone()); + columns_tree.insert(c.column_id.clone(), c); + } + TableCatalog { + id: table_id.to_string(), + name: table_id, + column_ids, + columns: columns_tree, + } + } } /// use column name as id for simplicity diff --git a/tests/slt/alias.slt b/tests/slt/alias.slt index 620044b..e087982 100644 --- a/tests/slt/alias.slt +++ b/tests/slt/alias.slt @@ -40,3 +40,14 @@ select t_1.a from t1 t_1 left join t2 t_2 on t_1.a=t_2.b and t_1.c > t_2.c; 0 1 2 + +# subquery alias +query I +select t.a from (select * from t1 where a > 1) t where t.b > 7; +---- +2 + +query III +select t.* from (select * from t1 where a > 1) t where t.b > 7; +---- +2 8 1