|
| 1 | +use std::slice; |
| 2 | +use sqlparser::ast::{Assignment, Expr, TableFactor, TableWithJoins}; |
| 3 | +use crate::binder::{Binder, BindError, lower_case_name, split_name}; |
| 4 | +use crate::expression::ScalarExpression; |
| 5 | +use crate::planner::LogicalPlan; |
| 6 | +use crate::planner::operator::Operator; |
| 7 | +use crate::planner::operator::update::UpdateOperator; |
| 8 | +use crate::types::value::ValueRef; |
| 9 | + |
| 10 | +impl Binder { |
| 11 | + pub(crate) fn bind_update( |
| 12 | + &mut self, |
| 13 | + to: &TableWithJoins, |
| 14 | + selection: &Option<Expr>, |
| 15 | + assignments: &[Assignment] |
| 16 | + ) -> Result<LogicalPlan, BindError> { |
| 17 | + if let TableFactor::Table { name, .. } = &to.relation { |
| 18 | + let name = lower_case_name(&name); |
| 19 | + let (_, table_name) = split_name(&name)?; |
| 20 | + |
| 21 | + let mut plan = self.bind_table_ref(slice::from_ref(to))?; |
| 22 | + |
| 23 | + if let Some(predicate) = selection { |
| 24 | + plan = self.bind_where(plan, predicate)?; |
| 25 | + } |
| 26 | + |
| 27 | + if let Some(table) = self.context.catalog.get_table_by_name(table_name) { |
| 28 | + let table_id = table.id; |
| 29 | + let bind_table_name = Some(table_name.to_string()); |
| 30 | + |
| 31 | + let mut columns = Vec::with_capacity(assignments.len()); |
| 32 | + let mut row = Vec::with_capacity(assignments.len()); |
| 33 | + |
| 34 | + |
| 35 | + for assignment in assignments { |
| 36 | + let value = match self.bind_expr(&assignment.value)? { |
| 37 | + ScalarExpression::Constant(value) => Ok::<ValueRef, BindError>(value), |
| 38 | + _ => unreachable!(), |
| 39 | + }?; |
| 40 | + |
| 41 | + for ident in &assignment.id { |
| 42 | + match self.bind_column_ref_from_identifiers( |
| 43 | + slice::from_ref(&ident), |
| 44 | + bind_table_name.as_ref() |
| 45 | + )? { |
| 46 | + ScalarExpression::ColumnRef(catalog) => { |
| 47 | + columns.push(catalog); |
| 48 | + row.push(value.clone()); |
| 49 | + }, |
| 50 | + _ => unreachable!() |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + let values_plan = self.bind_values(vec![row], columns); |
| 56 | + |
| 57 | + Ok(LogicalPlan { |
| 58 | + operator: Operator::Update( |
| 59 | + UpdateOperator { |
| 60 | + table_id, |
| 61 | + } |
| 62 | + ), |
| 63 | + childrens: vec![plan, values_plan], |
| 64 | + }) |
| 65 | + } else { |
| 66 | + Err(BindError::InvalidTable(format!("not found table {}", table_name))) |
| 67 | + } |
| 68 | + } else { |
| 69 | + unreachable!("only table") |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments