Skip to content
Open
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
3 changes: 3 additions & 0 deletions docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,10 @@ The `SqlDialect` trait methods:
- `parse()` — Parses SQL text into KiteSQL statements; the dialect rejects syntax it does not support and may rewrite the statements
- `comparison_type()` — Optional hook to pick the type both operands of a comparison (`=`, `<>`, `<`, `<=`, `>`, `>=`, `IN`, `BETWEEN`) are cast to
- `boolean_text()` — Optional hook to choose the text of a boolean in `CAST(.. AS CHAR)` or `CAST(.. AS VARCHAR)` (default `'true'`/`'false'`)
- `upsert_affected_rows()` — Optional hook to choose the affected rows `INSERT ... ON DUPLICATE KEY UPDATE` reports for an inserted, changed or unchanged row (default: 1 each)

`DataTypeMapper::map_data_type()` maps types inside expressions (`CAST`, typed literals); `map_column_type()` maps the types of column definitions and defaults to `map_data_type()`.

`SqlParser::with_on_duplicate_key_update()` accepts `INSERT ... ON DUPLICATE KEY UPDATE`, which updates the row a primary or unique key conflicts with instead of inserting; assignments read the proposed row through `VALUES(col)` or a row alias (`INSERT ... AS new ON DUPLICATE KEY UPDATE v = new.v`). Without it the clause is rejected, as it is by `GenericSqlDialect`.

By default, the `GenericSqlDialect` is used, which provides standard SQL behavior with no custom transformations.
10 changes: 10 additions & 0 deletions src/ast/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,16 @@ pub struct Insert {
/// `INSERT OVERWRITE` or `REPLACE INTO`: rows replace those with the same primary key.
pub overwrite: bool,
pub source: Box<Query>,
pub on_duplicate_key_update: Option<OnDuplicateKeyUpdate>,
}

/// `[AS row_alias] ON DUPLICATE KEY UPDATE assignments`: a row whose primary or unique key
/// already exists updates that row instead of being inserted.
#[derive(Debug, Clone, PartialEq)]
pub struct OnDuplicateKeyUpdate {
/// Names the proposed row in `assignments`, as `VALUES(col)` does.
pub row_alias: Option<Ident>,
pub assignments: Vec<Assignment>,
}

#[derive(Debug, Clone, PartialEq)]
Expand Down
47 changes: 37 additions & 10 deletions src/binder/insert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use crate::catalog::table::DmlTable;
use crate::catalog::ColumnRef;
use crate::errors::DatabaseError;
use crate::expression::ScalarExpression;
use crate::planner::operator::insert::InsertOperator;
use crate::planner::operator::insert::{InsertOperator, OnDuplicateKeyUpdate};
use crate::planner::operator::values::ValuesOperator;
use crate::planner::operator::Operator;
use crate::planner::{Childrens, ExprRef, LogicalPlan, PlanArena};
Expand All @@ -26,6 +26,23 @@ use crate::types::tuple::Schema;
use crate::types::value::DataValue;
use crate::types::LogicalType;

pub(crate) struct InsertValuesParams<'a> {
pub table_name: &'a str,
pub targets: Schema,
pub rows: Vec<ExprRef>,
pub row_count: usize,
pub is_overwrite: bool,
pub on_duplicate_key_update: Option<OnDuplicateKeyUpdate>,
}

pub(crate) struct InsertQueryParams<'a> {
pub table_name: &'a str,
pub input_plan: LogicalPlan,
pub targets: &'a [ColumnRef],
pub is_overwrite: bool,
pub on_duplicate_key_update: Option<OnDuplicateKeyUpdate>,
}

impl<T: StorageTransaction, A: AsRef<[(usize, LogicalType)]>> Binder<'_, '_, T, A> {
fn insert_table(
&self,
Expand All @@ -52,13 +69,17 @@ impl<T: StorageTransaction, A: AsRef<[(usize, LogicalType)]>> Binder<'_, '_, T,

pub(crate) fn bind_insert_values(
&mut self,
table_name: &str,
targets: Schema,
rows: Vec<ExprRef>,
row_count: usize,
is_overwrite: bool,
params: InsertValuesParams<'_>,
arena: &mut PlanArena<'_>,
) -> Result<LogicalPlan, DatabaseError> {
let InsertValuesParams {
table_name,
targets,
rows,
row_count,
is_overwrite,
on_duplicate_key_update,
} = params;
let (table, sources) = self.insert_table(table_name, &targets, arena)?;
let mut values = Vec::with_capacity(row_count * table.columns.len());
for row in rows.chunks(targets.len()) {
Expand All @@ -75,19 +96,24 @@ impl<T: StorageTransaction, A: AsRef<[(usize, LogicalType)]>> Binder<'_, '_, T,
Operator::Insert(InsertOperator {
table,
is_overwrite,
on_duplicate_key_update,
}),
Childrens::Only(Box::new(values_plan)),
))
}

pub(crate) fn bind_insert_query(
&mut self,
table_name: &str,
mut input_plan: LogicalPlan,
targets: &[ColumnRef],
is_overwrite: bool,
params: InsertQueryParams<'_>,
arena: &mut PlanArena<'_>,
) -> Result<LogicalPlan, DatabaseError> {
let InsertQueryParams {
table_name,
mut input_plan,
targets,
is_overwrite,
on_duplicate_key_update,
} = params;
let (table, sources) = self.insert_table(table_name, targets, arena)?;
// Project the input to all columns in table order, filling in defaults.
let mut projection = Vec::with_capacity(table.columns.len());
Expand All @@ -106,6 +132,7 @@ impl<T: StorageTransaction, A: AsRef<[(usize, LogicalType)]>> Binder<'_, '_, T,
Operator::Insert(InsertOperator {
table,
is_overwrite,
on_duplicate_key_update,
}),
Childrens::Only(Box::new(input_plan)),
))
Expand Down
38 changes: 37 additions & 1 deletion src/binder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ mod drop_table;
mod drop_view;
mod explain;
pub mod expr;
mod insert;
pub(crate) mod insert;
mod parser;
mod select;
mod show_table;
Expand Down Expand Up @@ -258,6 +258,31 @@ pub(crate) struct BoundScalarQuery {
param_bindings: Vec<(ScalarQueryRef, ExprRef)>,
}

pub(crate) struct OdkuContext {
pub(crate) original_columns: Vec<ColumnRef>,
pub(crate) excluded_columns: Vec<ColumnRef>,
pub(crate) row_alias: Option<String>,
}

impl OdkuContext {
/// The proposed row's columns follow the existing row's, so column `i` is at `n + i`.
pub(crate) fn proposed_column(
&self,
name: &str,
arena: &PlanArena<'_>,
) -> Result<ScalarExpression, DatabaseError> {
let position = self
.original_columns
.iter()
.position(|column| arena.column(*column).name() == name)
.ok_or_else(|| DatabaseError::column_not_found(name.to_string()))?;
Ok(ScalarExpression::column_expr(
self.excluded_columns[position],
self.original_columns.len() + position,
))
}
}

pub struct BinderContext<'a, T: StorageTransaction> {
pub(crate) scala_functions: &'a ScalaFunctions,
pub(crate) table_functions: &'a TableFunctions,
Expand All @@ -274,6 +299,7 @@ pub struct BinderContext<'a, T: StorageTransaction> {
// and do not share the current FROM namespace.
source_scope_start: usize,
ctes: Vec<CteBinding>,
odku_context: Option<OdkuContext>,
pub(crate) cte_depth: usize,
// alias
expr_aliases: BTreeMap<(Option<String>, String), ExprRef>,
Expand Down Expand Up @@ -352,6 +378,7 @@ impl<'a, T: StorageTransaction> BinderContext<'a, T> {
expr_aliases: Default::default(),
group_by_exprs: vec![],
agg_calls: Default::default(),
odku_context: None,
using: Default::default(),
bind_step: QueryBindStep::From,
sub_queries: Default::default(),
Expand Down Expand Up @@ -384,6 +411,7 @@ impl<'a, T: StorageTransaction> BinderContext<'a, T> {
expr_aliases: self.expr_aliases.clone(),
group_by_exprs: self.group_by_exprs.clone(),
agg_calls: self.agg_calls.clone(),
odku_context: None,
using: self.using.clone(),
bind_step: self.bind_step,
sub_queries: Default::default(),
Expand Down Expand Up @@ -474,6 +502,14 @@ impl<'a, T: StorageTransaction> BinderContext<'a, T> {
self.has_join_outer_ref
}

pub(crate) fn set_odku_context(&mut self, context: Option<OdkuContext>) {
self.odku_context = context;
}

pub(crate) fn odku_context(&self) -> Option<&OdkuContext> {
self.odku_context.as_ref()
}

pub fn table(&self, table_name: &str) -> Result<Option<&'a TableCatalog>, DatabaseError> {
self.transaction
.table(self.names, self.table_cache, table_name)
Expand Down
Loading