Skip to content

feat: delete support table alias #13360

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/doc/14-sql-commands/10-dml/dml-delete-from.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Databend ensures data integrity with atomic operations. Inserts, updates, replac
## Syntax

```sql
DELETE FROM <table_name>
DELETE FROM <table_name> [[AS] alias]
[WHERE <condition>]
```

Expand Down
10 changes: 3 additions & 7 deletions src/query/ast/src/ast/format/ast_format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1062,15 +1062,11 @@ impl<'ast> Visitor<'ast> for AstFormatVisitor {
self.children.push(node);
}

fn visit_delete(
&mut self,
table_reference: &'ast TableReference,
selection: &'ast Option<Expr>,
) {
fn visit_delete(&mut self, delete: &'ast DeleteStmt) {
let mut children = Vec::new();
self.visit_table_reference(table_reference);
self.visit_table_reference(&delete.table);
children.push(self.children.pop().unwrap());
if let Some(selection) = selection {
if let Some(selection) = &delete.selection {
self.visit_expr(selection);
children.push(self.children.pop().unwrap());
}
Expand Down
13 changes: 8 additions & 5 deletions src/query/ast/src/ast/format/syntax/dml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,9 @@ use crate::ast::CopyIntoLocationSource;
use crate::ast::CopyIntoLocationStmt;
use crate::ast::CopyIntoTableSource;
use crate::ast::CopyIntoTableStmt;
use crate::ast::Expr;
use crate::ast::DeleteStmt;
use crate::ast::InsertSource;
use crate::ast::InsertStmt;
use crate::ast::TableReference;
use crate::ast::UpdateExpr;
use crate::ast::UpdateStmt;

Expand Down Expand Up @@ -125,10 +124,14 @@ fn pretty_source(source: InsertSource) -> RcDoc<'static> {
})
}

pub(crate) fn pretty_delete(table: TableReference, selection: Option<Expr>) -> RcDoc<'static> {
pub(crate) fn pretty_delete(delete_stmt: DeleteStmt) -> RcDoc<'static> {
RcDoc::text("DELETE FROM")
.append(RcDoc::line().nest(NEST_FACTOR).append(pretty_table(table)))
.append(if let Some(selection) = selection {
.append(
RcDoc::line()
.nest(NEST_FACTOR)
.append(pretty_table(delete_stmt.table)),
)
.append(if let Some(selection) = delete_stmt.selection {
RcDoc::line().append(RcDoc::text("WHERE")).append(
RcDoc::line()
.nest(NEST_FACTOR)
Expand Down
6 changes: 1 addition & 5 deletions src/query/ast/src/ast/format/syntax/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,7 @@ pub fn pretty_statement(stmt: Statement, max_width: usize) -> Result<String> {
// Format and beautify large SQL statements to make them easy to read.
Statement::Query(query) => pretty_query(*query),
Statement::Insert(insert_stmt) => pretty_insert(insert_stmt),
Statement::Delete {
table_reference,
selection,
..
} => pretty_delete(table_reference, selection),
Statement::Delete(delete_stmt) => pretty_delete(delete_stmt),
Statement::CopyIntoTable(copy_stmt) => pretty_copy_into_table(copy_stmt),
Statement::CopyIntoLocation(copy_stmt) => pretty_copy_into_location(copy_stmt),
Statement::Update(update_stmt) => pretty_update(update_stmt),
Expand Down
41 changes: 41 additions & 0 deletions src/query/ast/src/ast/statements/delete.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright 2021 Datafuse Labs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::fmt::Display;
use std::fmt::Formatter;

use crate::ast::Expr;
use crate::ast::Hint;
use crate::ast::TableReference;

#[derive(Debug, Clone, PartialEq)]
pub struct DeleteStmt {
pub hints: Option<Hint>,
pub table: TableReference,
pub selection: Option<Expr>,
}

impl Display for DeleteStmt {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
write!(f, "DELETE ")?;
if let Some(hints) = &self.hints {
write!(f, "{} ", hints)?;
}
write!(f, "FROM {}", self.table)?;
if let Some(conditions) = &self.selection {
write!(f, " WHERE {conditions}")?;
}
Ok(())
}
}
2 changes: 2 additions & 0 deletions src/query/ast/src/ast/statements/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ mod columns;
mod copy;
mod data_mask;
mod database;
mod delete;
mod explain;
mod hint;
mod index;
Expand Down Expand Up @@ -46,6 +47,7 @@ pub use columns::*;
pub use copy::*;
pub use data_mask::*;
pub use database::*;
pub use delete::*;
pub use explain::*;
pub use hint::*;
pub use index::*;
Expand Down
21 changes: 2 additions & 19 deletions src/query/ast/src/ast/statements/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ use crate::ast::statements::task::CreateTaskStmt;
use crate::ast::Expr;
use crate::ast::Identifier;
use crate::ast::Query;
use crate::ast::TableReference;

// SQL statement
#[allow(clippy::large_enum_variant)]
Expand Down Expand Up @@ -80,11 +79,7 @@ pub enum Statement {
Insert(InsertStmt),
Replace(ReplaceStmt),
MergeInto(MergeIntoStmt),
Delete {
hints: Option<Hint>,
table_reference: TableReference,
selection: Option<Expr>,
},
Delete(DeleteStmt),

Update(UpdateStmt),

Expand Down Expand Up @@ -305,19 +300,7 @@ impl Display for Statement {
Statement::Insert(insert) => write!(f, "{insert}")?,
Statement::Replace(replace) => write!(f, "{replace}")?,
Statement::MergeInto(merge_into) => write!(f, "{merge_into}")?,
Statement::Delete {
table_reference,
selection,
hints,
} => {
write!(f, "DELETE FROM {table_reference} ")?;
if let Some(hints) = hints {
write!(f, "{} ", hints)?;
}
if let Some(conditions) = selection {
write!(f, "WHERE {conditions} ")?;
}
}
Statement::Delete(delete) => write!(f, "{delete}")?,
Statement::Update(update) => write!(f, "{update}")?,
Statement::CopyIntoTable(stmt) => write!(f, "{stmt}")?,
Statement::CopyIntoLocation(stmt) => write!(f, "{stmt}")?,
Expand Down
37 changes: 30 additions & 7 deletions src/query/ast/src/parser/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,13 +278,15 @@ pub fn statement(i: Input) -> IResult<StatementMsg> {

let delete = map(
rule! {
DELETE ~ #hint? ~ FROM ~ #table_reference_only
DELETE ~ #hint? ~ FROM ~ #table_reference_with_alias
~ ( WHERE ~ ^#expr )?
},
|(_, opt_hints, _, table_reference, opt_selection)| Statement::Delete {
hints: opt_hints,
table_reference,
selection: opt_selection.map(|(_, selection)| selection),
|(_, hints, _, table, opt_selection)| {
Statement::Delete(DeleteStmt {
hints,
table,
selection: opt_selection.map(|(_, selection)| selection),
})
},
);

Expand All @@ -294,9 +296,9 @@ pub fn statement(i: Input) -> IResult<StatementMsg> {
~ SET ~ ^#comma_separated_list1(update_expr)
~ ( WHERE ~ ^#expr )?
},
|(_, opt_hints, table, _, update_list, opt_selection)| {
|(_, hints, table, _, update_list, opt_selection)| {
Statement::Update(UpdateStmt {
hints: opt_hints,
hints,
table,
update_list,
selection: opt_selection.map(|(_, selection)| selection),
Expand Down Expand Up @@ -2747,6 +2749,27 @@ pub fn presign_option(i: Input) -> IResult<PresignOption> {
))(i)
}

pub fn table_reference_with_alias(i: Input) -> IResult<TableReference> {
map(
consumed(rule! {
#dot_separated_idents_1_to_3 ~ #alias_name?
}),
|(span, ((catalog, database, table), alias))| TableReference::Table {
span: transform_span(span.0),
catalog,
database,
table,
alias: alias.map(|v| TableAlias {
name: v,
columns: vec![],
}),
travel_point: None,
pivot: None,
unpivot: None,
},
)(i)
}

pub fn table_reference_only(i: Input) -> IResult<TableReference> {
map(
consumed(rule! {
Expand Down
7 changes: 1 addition & 6 deletions src/query/ast/src/visitors/visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -406,12 +406,7 @@ pub trait Visitor<'ast>: Sized {
fn visit_merge_into(&mut self, _merge_into: &'ast MergeIntoStmt) {}
fn visit_insert_source(&mut self, _insert_source: &'ast InsertSource) {}

fn visit_delete(
&mut self,
_table_reference: &'ast TableReference,
_selection: &'ast Option<Expr>,
) {
}
fn visit_delete(&mut self, _delete: &'ast DeleteStmt) {}

fn visit_update(&mut self, _update: &'ast UpdateStmt) {}

Expand Down
7 changes: 1 addition & 6 deletions src/query/ast/src/visitors/visitor_mut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -421,12 +421,7 @@ pub trait VisitorMut: Sized {
fn visit_merge_into(&mut self, _merge_into: &mut MergeIntoStmt) {}
fn visit_insert_source(&mut self, _insert_source: &mut InsertSource) {}

fn visit_delete(
&mut self,
_table_reference: &mut TableReference,
_selection: &mut Option<Expr>,
) {
}
fn visit_delete(&mut self, _delete: &mut DeleteStmt) {}

fn visit_update(&mut self, _update: &mut UpdateStmt) {}

Expand Down
6 changes: 1 addition & 5 deletions src/query/ast/src/visitors/walk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -338,11 +338,7 @@ pub fn walk_statement<'a, V: Visitor<'a>>(visitor: &mut V, statement: &'a Statem
Statement::Insert(insert) => visitor.visit_insert(insert),
Statement::Replace(replace) => visitor.visit_replace(replace),
Statement::MergeInto(merge_into) => visitor.visit_merge_into(merge_into),
Statement::Delete {
table_reference,
selection,
..
} => visitor.visit_delete(table_reference, selection),
Statement::Delete(delete) => visitor.visit_delete(delete),
Statement::Update(update) => visitor.visit_update(update),
Statement::CopyIntoTable(stmt) => visitor.visit_copy_into_table(stmt),
Statement::CopyIntoLocation(stmt) => visitor.visit_copy_into_location(stmt),
Expand Down
6 changes: 1 addition & 5 deletions src/query/ast/src/visitors/walk_mut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -313,11 +313,7 @@ pub fn walk_statement_mut<V: VisitorMut>(visitor: &mut V, statement: &mut Statem
Statement::Insert(insert) => visitor.visit_insert(insert),
Statement::Replace(replace) => visitor.visit_replace(replace),
Statement::MergeInto(merge_into) => visitor.visit_merge_into(merge_into),
Statement::Delete {
table_reference,
selection,
..
} => visitor.visit_delete(table_reference, selection),
Statement::Delete(delete) => visitor.visit_delete(delete),
Statement::Update(update) => visitor.visit_update(update),
Statement::CopyIntoLocation(stmt) => visitor.visit_copy_into_location(stmt),
Statement::CopyIntoTable(stmt) => visitor.visit_copy_into_table(stmt),
Expand Down
10 changes: 3 additions & 7 deletions src/query/sql/src/planner/binder/binder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -401,17 +401,13 @@ impl<'a> Binder {
}
self.bind_merge_into(bind_context, stmt).await?
}
Statement::Delete {
hints,
table_reference,
selection,
} => {
if let Some(hints) = hints {
Statement::Delete(stmt) => {
if let Some(hints) = &stmt.hints {
if let Some(e) = self.opt_hints_set_var(bind_context, hints).await.err() {
warn!("In DELETE resolve optimize hints {:?} failed, err: {:?}", hints, e);
}
}
self.bind_delete(bind_context, table_reference, selection)
self.bind_delete(bind_context, stmt)
.await?
}
Statement::Update(stmt) => {
Expand Down
16 changes: 9 additions & 7 deletions src/query/sql/src/planner/binder/delete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

use std::sync::Arc;

use common_ast::ast::DeleteStmt;
use common_ast::ast::Expr;
use common_ast::ast::TableReference;
use common_exception::ErrorCode;
Expand Down Expand Up @@ -59,15 +60,18 @@ impl<'a> Binder {
pub(in crate::planner::binder) async fn bind_delete(
&mut self,
bind_context: &mut BindContext,
table_reference: &'a TableReference,
filter: &'a Option<Expr>,
stamt: &DeleteStmt,
) -> Result<Plan> {
let DeleteStmt {
table, selection, ..
} = stamt;

let (catalog_name, database_name, table_name) = if let TableReference::Table {
catalog,
database,
table,
..
} = table_reference
} = table
{
self.normalize_object_identifier_triple(catalog, database, table)
} else {
Expand All @@ -77,9 +81,7 @@ impl<'a> Binder {
));
};

let (table_expr, mut context) = self
.bind_table_reference(bind_context, table_reference)
.await?;
let (table_expr, mut context) = self.bind_single_table(bind_context, table).await?;

context.allow_internal_columns(false);
let mut scalar_binder = ScalarBinder::new(
Expand All @@ -93,7 +95,7 @@ impl<'a> Binder {
);

let (selection, subquery_desc) = self
.process_selection(filter, table_expr, &mut scalar_binder)
.process_selection(selection, table_expr, &mut scalar_binder)
.await?;

let plan = DeletePlan {
Expand Down
2 changes: 1 addition & 1 deletion src/query/sql/src/planner/binder/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ impl Binder {
));
};

let (table_expr, mut context) = self.bind_table_reference(bind_context, table).await?;
let (table_expr, mut context) = self.bind_single_table(bind_context, table).await?;

let table = self
.ctx
Expand Down
Loading