|
| 1 | +use crate::binder::{lower_case_name, lower_ident, Binder}; |
| 2 | +use crate::catalog::view::View; |
| 3 | +use crate::catalog::{ColumnCatalog, ColumnRef}; |
| 4 | +use crate::errors::DatabaseError; |
| 5 | +use crate::expression::{AliasType, ScalarExpression}; |
| 6 | +use crate::planner::operator::create_view::CreateViewOperator; |
| 7 | +use crate::planner::operator::Operator; |
| 8 | +use crate::planner::LogicalPlan; |
| 9 | +use crate::storage::Transaction; |
| 10 | +use itertools::Itertools; |
| 11 | +use sqlparser::ast::{Ident, ObjectName, Query}; |
| 12 | +use std::sync::Arc; |
| 13 | +use ulid::Ulid; |
| 14 | + |
| 15 | +impl<'a, 'b, T: Transaction> Binder<'a, 'b, T> { |
| 16 | + pub(crate) fn bind_create_view( |
| 17 | + &mut self, |
| 18 | + or_replace: &bool, |
| 19 | + name: &ObjectName, |
| 20 | + columns: &[Ident], |
| 21 | + query: &Query, |
| 22 | + ) -> Result<LogicalPlan, DatabaseError> { |
| 23 | + let view_name = Arc::new(lower_case_name(name)?); |
| 24 | + let mut plan = self.bind_query(query)?; |
| 25 | + |
| 26 | + if !columns.is_empty() { |
| 27 | + let mapping_schema = plan.output_schema(); |
| 28 | + let exprs = columns |
| 29 | + .iter() |
| 30 | + .enumerate() |
| 31 | + .map(|(i, ident)| { |
| 32 | + let mapping_column = &mapping_schema[i]; |
| 33 | + let mut column = ColumnCatalog::new( |
| 34 | + lower_ident(ident), |
| 35 | + mapping_column.nullable(), |
| 36 | + mapping_column.desc().clone(), |
| 37 | + ); |
| 38 | + column.set_ref_table(view_name.clone(), Ulid::new(), true); |
| 39 | + |
| 40 | + ScalarExpression::Alias { |
| 41 | + expr: Box::new(ScalarExpression::ColumnRef(mapping_column.clone())), |
| 42 | + alias: AliasType::Expr(Box::new(ScalarExpression::ColumnRef( |
| 43 | + ColumnRef::from(column), |
| 44 | + ))), |
| 45 | + } |
| 46 | + }) |
| 47 | + .collect_vec(); |
| 48 | + plan = self.bind_project(plan, exprs)?; |
| 49 | + } |
| 50 | + |
| 51 | + Ok(LogicalPlan::new( |
| 52 | + Operator::CreateView(CreateViewOperator { |
| 53 | + view: View { |
| 54 | + name: view_name, |
| 55 | + plan: Box::new(plan), |
| 56 | + }, |
| 57 | + or_replace: *or_replace, |
| 58 | + }), |
| 59 | + vec![], |
| 60 | + )) |
| 61 | + } |
| 62 | +} |
0 commit comments