Skip to content

Apache DataFusion SQL Query Engine

Add insert/update/delete to LogicalPlan and add SQL planner support (#4902)

Brent Gardneraa8f139dde01
diff --git a/datafusion/core/src/physical_plan/planner.rs b/datafusion/core/src/physical_plan/planner.rs
index 371b27ed7c..f93f875896 100644
--- a/datafusion/core/src/physical_plan/planner.rs
+++ b/datafusion/core/src/physical_plan/planner.rs
@@ -1180,6 +1180,12 @@ impl DefaultPhysicalPlanner {
"Unsupported logical plan: CreateView".to_string(),
))
}
+ LogicalPlan::Dml(_) => {
+ // DataFusion is a read-only query engine, but also a library, so consumers may implement this
+ Err(DataFusionError::Internal(
+ "Unsupported logical plan: Write".to_string(),
+ ))
+ }
LogicalPlan::SetVariable(_) => {
Err(DataFusionError::Internal(
"Unsupported logical plan: SetVariable must be root of the plan".to_string(),
diff --git a/datafusion/expr/src/lib.rs b/datafusion/expr/src/lib.rs
index 0ba332d141..baa8db8cc3 100644
--- a/datafusion/expr/src/lib.rs
+++ b/datafusion/expr/src/lib.rs
@@ -71,11 +71,11 @@ pub use logical_plan::{
build_join_schema, union, wrap_projection_for_join_if_necessary, UNNAMED_TABLE,
},
Aggregate, CreateCatalog, CreateCatalogSchema, CreateExternalTable,
- CreateMemoryTable, CreateView, CrossJoin, Distinct, DropTable, DropView,
- EmptyRelation, Explain, Extension, Filter, Join, JoinConstraint, JoinType, Limit,
- LogicalPlan, LogicalPlanBuilder, Partitioning, PlanType, PlanVisitor, Projection,
- Repartition, SetVariable, Sort, StringifiedPlan, Subquery, SubqueryAlias, TableScan,
- ToStringifiedPlan, Union, UserDefinedLogicalNode, Values, Window,
+ CreateMemoryTable, CreateView, CrossJoin, Distinct, DmlStatement, DropTable,
+ DropView, EmptyRelation, Explain, Extension, Filter, Join, JoinConstraint, JoinType,
+ Limit, LogicalPlan, LogicalPlanBuilder, Partitioning, PlanType, PlanVisitor,
+ Projection, Repartition, SetVariable, Sort, StringifiedPlan, Subquery, SubqueryAlias,
+ TableScan, ToStringifiedPlan, Union, UserDefinedLogicalNode, Values, Window, WriteOp,
};
pub use nullif::SUPPORTED_NULLIF_TYPES;
pub use operator::Operator;
diff --git a/datafusion/expr/src/logical_plan/mod.rs b/datafusion/expr/src/logical_plan/mod.rs
index 9d26d2a655..0e5f3cd51f 100644
--- a/datafusion/expr/src/logical_plan/mod.rs
+++ b/datafusion/expr/src/logical_plan/mod.rs
@@ -23,11 +23,11 @@ mod plan;
pub use builder::{table_scan, LogicalPlanBuilder};
pub use plan::{
Aggregate, Analyze, CreateCatalog, CreateCatalogSchema, CreateExternalTable,
- CreateMemoryTable, CreateView, CrossJoin, Distinct, DropTable, DropView,
- EmptyRelation, Explain, Extension, Filter, Join, JoinConstraint, JoinType, Limit,
- LogicalPlan, Partitioning, PlanType, PlanVisitor, Prepare, Projection, Repartition,
- SetVariable, Sort, StringifiedPlan, Subquery, SubqueryAlias, TableScan,
- ToStringifiedPlan, Union, Values, Window,
+ CreateMemoryTable, CreateView, CrossJoin, Distinct, DmlStatement, DropTable,
+ DropView, EmptyRelation, Explain, Extension, Filter, Join, JoinConstraint, JoinType,
+ Limit, LogicalPlan, Partitioning, PlanType, PlanVisitor, Prepare, Projection,
+ Repartition, SetVariable, Sort, StringifiedPlan, Subquery, SubqueryAlias, TableScan,
+ ToStringifiedPlan, Union, Values, Window, WriteOp,
};
pub use display::display_schema;
diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rs
index 4a86ea0fcc..7c1da30beb 100644
--- a/datafusion/expr/src/logical_plan/plan.rs
+++ b/datafusion/expr/src/logical_plan/plan.rs
@@ -118,6 +118,8 @@ pub enum LogicalPlan {
SetVariable(SetVariable),
/// Prepare a statement
Prepare(Prepare),
+ /// Insert / Update / Delete
+ Dml(DmlStatement),
}
impl LogicalPlan {
@@ -158,6 +160,7 @@ impl LogicalPlan {
LogicalPlan::DropTable(DropTable { schema, .. }) => schema,
LogicalPlan::DropView(DropView { schema, .. }) => schema,
LogicalPlan::SetVariable(SetVariable { schema, .. }) => schema,
+ LogicalPlan::Dml(DmlStatement { table_schema, .. }) => table_schema,
}
}
@@ -218,6 +221,7 @@ impl LogicalPlan {
LogicalPlan::DropTable(_)
| LogicalPlan::DropView(_)
| LogicalPlan::SetVariable(_) => vec![],
+ LogicalPlan::Dml(DmlStatement { table_schema, .. }) => vec![table_schema],
}
}
@@ -316,6 +320,7 @@ impl LogicalPlan {
| LogicalPlan::Explain(_)
| LogicalPlan::Union(_)
| LogicalPlan::Distinct(_)
+ | LogicalPlan::Dml(_)
| LogicalPlan::Prepare(_) => Ok(()),
}
}
@@ -342,6 +347,7 @@ impl LogicalPlan {
LogicalPlan::Distinct(Distinct { input }) => vec![input],
LogicalPlan::Explain(explain) => vec![&explain.plan],
LogicalPlan::Analyze(analyze) => vec![&analyze.input],
+ LogicalPlan::Dml(write) => vec![&write.input],
LogicalPlan::CreateMemoryTable(CreateMemoryTable { input, .. })
| LogicalPlan::CreateView(CreateView { input, .. })
| LogicalPlan::Prepare(Prepare { input, .. }) => {
@@ -544,6 +550,7 @@ impl LogicalPlan {
}
LogicalPlan::Explain(explain) => explain.plan.accept(visitor)?,
LogicalPlan::Analyze(analyze) => analyze.input.accept(visitor)?,
+ LogicalPlan::Dml(write) => write.input.accept(visitor)?,
// plans without inputs
LogicalPlan::TableScan { .. }
| LogicalPlan::EmptyRelation(_)
@@ -929,6 +936,9 @@ impl LogicalPlan {
}
Ok(())
}
+ LogicalPlan::Dml(DmlStatement { table_name, op, .. }) => {
+ write!(f, "Write: op=[{op}] table=[{table_name}]")
+ }
LogicalPlan::Filter(Filter {
predicate: ref expr,
..
@@ -1504,6 +1514,38 @@ pub struct CreateExternalTable {
pub options: HashMap<String, String>,
}
+#[derive(Clone)]
+pub enum WriteOp {
+ Insert,
+ Delete,
+ Update,
+ Ctas,
+}
+
+impl Display for WriteOp {
+ fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
+ match self {
+ WriteOp::Insert => write!(f, "Insert"),
+ WriteOp::Delete => write!(f, "Delete"),
+ WriteOp::Update => write!(f, "Update"),
+ WriteOp::Ctas => write!(f, "Ctas"),
+ }
+ }
+}
+
+/// The operator that modifies the content of a database (adapted from substrait WriteRel)
+#[derive(Clone)]
+pub struct DmlStatement {
+ /// The table name
+ pub table_name: OwnedTableReference,
+ /// The schema of the table (must align with Rel input)
+ pub table_schema: DFSchemaRef,
+ /// The type of operation to perform
+ pub op: WriteOp,
+ /// The relation that determines the tuples to add/remove/modify the schema must match with table_schema
+ pub input: Arc<LogicalPlan>,
+}
+
/// Prepare a statement but do not execute it. Prepare statements can have 0 or more
/// `Expr::Placeholder` expressions that are filled in during execution
#[derive(Clone)]
diff --git a/datafusion/expr/src/utils.rs b/datafusion/expr/src/utils.rs
index e84ba0b6f8..8e22b5a23b 100644
--- a/datafusion/expr/src/utils.rs
+++ b/datafusion/expr/src/utils.rs
@@ -27,8 +27,8 @@ use crate::logical_plan::{
SubqueryAlias, Union, Values, Window,
};
use crate::{
- BinaryExpr, Cast, Expr, ExprSchemable, LogicalPlan, LogicalPlanBuilder, Operator,
- TableScan, TryCast,
+ BinaryExpr, Cast, DmlStatement, Expr, ExprSchemable, LogicalPlan, LogicalPlanBuilder,
+ Operator, TableScan, TryCast,
};
use arrow::datatypes::{DataType, TimeUnit};
use datafusion_common::{
@@ -489,6 +489,17 @@ pub fn from_plan(
schema.clone(),
)?))
}
+ LogicalPlan::Dml(DmlStatement {
+ table_name,
+ table_schema,
+ op,
+ ..
+ }) => Ok(LogicalPlan::Dml(DmlStatement {
+ table_name: table_name.clone(),
+ table_schema: table_schema.clone(),
+ op: op.clone(),
+ input: Arc::new(inputs[0].clone()),
+ })),
LogicalPlan::Values(Values { schema, .. }) => Ok(LogicalPlan::Values(Values {
schema: schema.clone(),
values: expr
diff --git a/datafusion/optimizer/src/common_subexpr_eliminate.rs b/datafusion/optimizer/src/common_subexpr_eliminate.rs
index ba073c988e..2e7004b142 100644
--- a/datafusion/optimizer/src/common_subexpr_eliminate.rs
+++ b/datafusion/optimizer/src/common_subexpr_eliminate.rs
@@ -239,6 +239,7 @@ impl OptimizerRule for CommonSubexprEliminate {
| LogicalPlan::SetVariable(_)
| LogicalPlan::Distinct(_)
| LogicalPlan::Extension(_)
+ | LogicalPlan::Dml(_)
| LogicalPlan::Prepare(_) => {
// apply the optimization to all inputs of the plan
utils::optimize_children(self, plan, config)?
diff --git a/datafusion/optimizer/src/push_down_projection.rs b/datafusion/optimizer/src/push_down_projection.rs
index 21396821c7..6485e0c939 100644
--- a/datafusion/optimizer/src/push_down_projection.rs
+++ b/datafusion/optimizer/src/push_down_projection.rs
@@ -410,6 +410,7 @@ fn optimize_plan(
| LogicalPlan::DropView(_)
| LogicalPlan::SetVariable(_)
| LogicalPlan::CrossJoin(_)
+ | LogicalPlan::Dml(_)
| LogicalPlan::Extension { .. }
| LogicalPlan::Prepare(_) => {
let expr = plan.expressions();
diff --git a/datafusion/proto/src/logical_plan/mod.rs b/datafusion/proto/src/logical_plan/mod.rs
index 78319f4978..dd6207aa44 100644
--- a/datafusion/proto/src/logical_plan/mod.rs
+++ b/datafusion/proto/src/logical_plan/mod.rs
@@ -1345,6 +1345,9 @@ impl AsLogicalPlan for LogicalPlanNode {
LogicalPlan::SetVariable(_) => Err(proto_error(
"LogicalPlan serde is not yet implemented for DropView",
)),
+ LogicalPlan::Dml(_) => Err(proto_error(
+ "LogicalPlan serde is not yet implemented for Write",
+ )),
}
}
}
diff --git a/datafusion/sql/src/select.rs b/datafusion/sql/src/select.rs
index 9056c1d8a8..f23d789325 100644
--- a/datafusion/sql/src/select.rs
+++ b/datafusion/sql/src/select.rs
@@ -272,7 +272,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
}
}
- fn plan_from_tables(
+ pub(crate) fn plan_from_tables(
&self,
mut from: Vec<TableWithJoins>,
planner_context: &mut PlannerContext,
diff --git a/datafusion/sql/src/statement.rs b/datafusion/sql/src/statement.rs
index b6218c5f5b..eaf89afd8b 100644
--- a/datafusion/sql/src/statement.rs
+++ b/datafusion/sql/src/statement.rs
@@ -25,21 +25,27 @@ use crate::planner::{
use arrow_schema::DataType;
use datafusion_common::parsers::CompressionTypeVariant;
use datafusion_common::{
- DFSchema, DFSchemaRef, DataFusionError, OwnedTableReference, Result, TableReference,
- ToDFSchema,
+ Column, DFSchema, DFSchemaRef, DataFusionError, OwnedTableReference, Result,
+ TableReference, ToDFSchema,
};
+use datafusion_expr::expr_rewriter::normalize_col_with_schemas;
+use datafusion_expr::logical_plan::builder::project;
use datafusion_expr::logical_plan::{Analyze, Prepare};
+use datafusion_expr::utils::expr_to_columns;
use datafusion_expr::{
cast, col, CreateCatalog, CreateCatalogSchema,
CreateExternalTable as PlanCreateExternalTable, CreateMemoryTable, CreateView,
- DropTable, DropView, Explain, LogicalPlan, LogicalPlanBuilder, PlanType, SetVariable,
- ToStringifiedPlan,
+ DmlStatement, DropTable, DropView, Explain, Filter, LogicalPlan, LogicalPlanBuilder,
+ PlanType, SetVariable, ToStringifiedPlan, WriteOp,
};
+use sqlparser::ast;
use sqlparser::ast::{
- Expr as SQLExpr, Ident, ObjectName, ObjectType, ShowCreateObject,
- ShowStatementFilter, Statement, UnaryOperator, Value,
+ Assignment, Expr as SQLExpr, Expr, Ident, ObjectName, ObjectType, Query,
+ ShowCreateObject, ShowStatementFilter, Statement, TableFactor, TableWithJoins,
+ UnaryOperator, Value,
};
use sqlparser::parser::ParserError::ParserError;
+use std::collections::{BTreeMap, HashSet};
use std::sync::Arc;
impl<'a, S: ContextProvider> SqlToRel<'a, S> {
@@ -253,6 +259,93 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
table_name,
filter,
} => self.show_columns_to_plan(extended, full, table_name, filter),
+
+ Statement::Insert {
+ or,
+ into,
+ table_name,
+ columns,
+ overwrite,
+ source,
+ partitioned,
+ after_columns,
+ table,
+ on,
+ returning,
+ } => {
+ if or.is_some() {
+ Err(DataFusionError::Plan(
+ "Inserts with or clauses not supported".to_owned(),
+ ))?;
+ }
+ if overwrite {
+ Err(DataFusionError::Plan(
+ "Insert overwrite is not supported".to_owned(),
+ ))?;
+ }
+ if partitioned.is_some() {
+ Err(DataFusionError::Plan(
+ "Partitioned inserts not yet supported".to_owned(),
+ ))?;
+ }
+ if !after_columns.is_empty() {
+ Err(DataFusionError::Plan(
+ "After-columns clause not supported".to_owned(),
+ ))?;
+ }
+ if table {
+ Err(DataFusionError::Plan(
+ "Table clause not supported".to_owned(),
+ ))?;
+ }
+ if on.is_some() {
+ Err(DataFusionError::Plan(
+ "Insert-on clause not supported".to_owned(),
+ ))?;
+ }
+ if returning.is_some() {
+ Err(DataFusionError::Plan(
+ "Insert-returning clause not yet supported".to_owned(),
+ ))?;
+ }
+ let _ = into; // optional keyword doesn't change behavior
+ self.insert_to_plan(table_name, columns, source)
+ }
+
+ Statement::Update {
+ table,
+ assignments,
+ from,
+ selection,
+ returning,
+ } => {
+ if returning.is_some() {
+ Err(DataFusionError::Plan(
+ "Update-returning clause not yet supported".to_owned(),
+ ))?;
+ }
+ self.update_to_plan(table, assignments, from, selection)
+ }
+
+ Statement::Delete {
+ table_name,
+ using,
+ selection,
+ returning,
+ } => {
+ if using.is_some() {
+ Err(DataFusionError::Plan(
+ "Using clause not supported".to_owned(),
+ ))?;
+ }
+ if returning.is_some() {
+ Err(DataFusionError::Plan(
+ "Delete-returning clause not yet supported".to_owned(),
+ ))?;
+ }
+ self.delete_to_plan(table_name, selection)
+ }
+
_ => Err(DataFusionError::NotImplemented(format!(
"Unsupported SQL statement: {sql:?}"
))),
@@ -505,6 +598,181 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
}))
}
+ fn delete_to_plan(
+ &self,
+ table_factor: TableFactor,
+ predicate_expr: Option<Expr>,
+ ) -> Result<LogicalPlan> {
+ let table_name = match &table_factor {
+ TableFactor::Table { name, .. } => name.clone(),
+ _ => Err(DataFusionError::Plan(
+ "Cannot delete from non-table relations!".to_string(),
+ ))?,
+ };
+
+ // Do a table lookup to verify the table exists
+ let table_ref = object_name_to_table_reference(table_name.clone())?;
+ let provider = self
+ .schema_provider
+ .get_table_provider((&table_ref).into())?;
+ let schema = (*provider.schema()).clone();
+ let schema = DFSchema::try_from(schema)?;
+ let scan =
+ LogicalPlanBuilder::scan(table_name.to_string(), provider, None)?.build()?;
+ let mut planner_context = PlannerContext::new();
+
+ let source = match predicate_expr {
+ None => scan,
+ Some(predicate_expr) => {
+ let filter_expr =
+ self.sql_to_expr(predicate_expr, &schema, &mut planner_context)?;
+ let schema = Arc::new(schema.clone());
+ let mut using_columns = HashSet::new();
+ expr_to_columns(&filter_expr, &mut using_columns)?;
+ let filter_expr = normalize_col_with_schemas(
+ filter_expr,
+ &[&schema],
+ &[using_columns],
+ )?;
+ LogicalPlan::Filter(Filter::try_new(filter_expr, Arc::new(scan))?)
+ }
+ };
+
+ let plan = LogicalPlan::Dml(DmlStatement {
+ table_name: table_ref,
+ table_schema: schema.into(),
+ op: WriteOp::Delete,
+ input: Arc::new(source),
+ });
+ Ok(plan)
+ }
+
+ fn update_to_plan(
+ &self,
+ table: TableWithJoins,
+ assignments: Vec<Assignment>,
+ from: Option<TableWithJoins>,
+ predicate_expr: Option<Expr>,
+ ) -> Result<LogicalPlan> {
+ let table_name = match &table.relation {
+ TableFactor::Table { name, .. } => name.clone(),
+ _ => Err(DataFusionError::Plan(
+ "Cannot update non-table relation!".to_string(),
+ ))?,
+ };
+
+ // Do a table lookup to verify the table exists
+ let table_name = object_name_to_table_reference(table_name)?;
+ let provider = self
+ .schema_provider
+ .get_table_provider((&table_name).into())?;
+ let arrow_schema = (*provider.schema()).clone();
+ let table_schema = Arc::new(DFSchema::try_from(arrow_schema)?);
+ let mut values: BTreeMap<_, _> = table_schema
+ .fields()
+ .iter()
+ .map(|f| {
+ (
+ f.name().clone(),
+ ast::Expr::Identifier(ast::Ident::from(f.name().as_str())),
+ )
+ })
+ .collect();
+
+ // Overwrite with assignment expressions
+ let mut planner_context = PlannerContext::new();
+ for assign in assignments.iter() {
+ let col_name: &Ident = assign
+ .id
+ .iter()
+ .last()
+ .ok_or(DataFusionError::Plan("Empty column id".to_string()))?;
+ let _ = values.insert(col_name.value.clone(), assign.value.clone());
+ }
+
+ // Build scan
+ let from = from.unwrap_or(table);
+ let scan = self.plan_from_tables(vec![from], &mut planner_context)?;
+
+ // Filter
+ let source = match predicate_expr {
+ None => scan,
+ Some(predicate_expr) => {
+ let filter_expr = self.sql_to_expr(
+ predicate_expr,
+ &table_schema,
+ &mut planner_context,
+ )?;
+ let mut using_columns = HashSet::new();
+ expr_to_columns(&filter_expr, &mut using_columns)?;
+ let filter_expr = normalize_col_with_schemas(
+ filter_expr,
+ &[&table_schema],
+ &[using_columns],
+ )?;
+ LogicalPlan::Filter(Filter::try_new(filter_expr, Arc::new(scan))?)
+ }
+ };
+
+ // Projection
+ let mut exprs = vec![];
+ for (col_name, expr) in values.into_iter() {
+ let expr = self.sql_to_expr(expr, &table_schema, &mut planner_context)?;
+ let expr = expr.alias(col_name);
+ exprs.push(expr);
+ }
+ let source = project(source, exprs)?;
+
+ let plan = LogicalPlan::Dml(DmlStatement {
+ table_name,
+ table_schema,
+ op: WriteOp::Update,
+ input: Arc::new(source),
+ });
+ Ok(plan)
+ }
+
+ fn insert_to_plan(
+ &self,
+ table_name: ObjectName,
+ columns: Vec<Ident>,
+ source: Box<Query>,
+ ) -> Result<LogicalPlan> {
+ // Do a table lookup to verify the table exists
+ let table_name = object_name_to_table_reference(table_name)?;
+ let provider = self
+ .schema_provider
+ .get_table_provider((&table_name).into())?;
+ let arrow_schema = (*provider.schema()).clone();
+ let table_schema = Arc::new(DFSchema::try_from(arrow_schema)?);
+
+ // Projection
+ let mut planner_context = PlannerContext::new();
+ let source = self.query_to_plan(*source, &mut planner_context)?;
+ if columns.len() != source.schema().fields().len() {
+ Err(DataFusionError::Plan(
+ "Column count doesn't match insert query!".to_owned(),
+ ))?;
+ }
+ let exprs: Vec<_> = columns
+ .iter()
+ .zip(source.schema().fields().iter())
+ .map(|(c, f)| {
+ datafusion_expr::Expr::Column(Column::from(f.name().clone()))
+ .alias(c.value.clone())
+ })
+ .collect();
+ let source = project(source, exprs)?;
+
+ let plan = LogicalPlan::Dml(DmlStatement {
+ table_name,
+ table_schema,
+ op: WriteOp::Insert,
+ input: Arc::new(source),
+ });
+ Ok(plan)
+ }
+
fn show_columns_to_plan(
&self,
extended: bool,
diff --git a/datafusion/sql/tests/integration_test.rs b/datafusion/sql/tests/integration_test.rs
index 70d5287f31..f0aa614b8b 100644
--- a/datafusion/sql/tests/integration_test.rs
+++ b/datafusion/sql/tests/integration_test.rs
@@ -157,6 +157,44 @@ fn cast_to_invalid_decimal_type() {
}
}
+#[test]
+fn plan_insert() {
+ let sql =
+ "insert into person (id, first_name, last_name) values (1, 'Alan', 'Turing')";
+ let plan = r#"
+Write: op=[Insert] table=[person]
+ Projection: column1 AS id, column2 AS first_name, column3 AS last_name
+ Values: (Int64(1), Utf8("Alan"), Utf8("Turing"))
+ "#
+ .trim();
+ quick_test(sql, plan);
+}
+
+#[test]
+fn plan_update() {
+ let sql = "update person set last_name='Kay' where id=1";
+ let plan = r#"
+Write: op=[Update] table=[person]
+ Projection: person.age AS age, person.birth_date AS birth_date, person.first_name AS first_name, person.id AS id, Utf8("Kay") AS last_name, person.salary AS salary, person.state AS state, person.πŸ˜€ AS πŸ˜€
+ Filter: id = Int64(1)
+ TableScan: person
+ "#
+ .trim();
+ quick_test(sql, plan);
+}
+
+#[test]
+fn plan_delete() {
+ let sql = "delete from person where id=1";
+ let plan = r#"
+Write: op=[Delete] table=[person]
+ Filter: id = Int64(1)
+ TableScan: person
+ "#
+ .trim();
+ quick_test(sql, plan);
+}
+
#[test]
fn select_column_does_not_exist() {
let sql = "SELECT doesnotexist FROM person";