1use std::collections::{BTreeMap, HashMap, HashSet};
6use std::path::Path;
7use std::str::FromStr;
8use std::sync::Arc;
9
10use crate::parser::{
11 CopyToSource, CopyToStatement, CreateExternalCatalog, CreateExternalTable,
12 ExplainStatement, LexOrdering, ResetStatement, Statement as DFStatement,
13};
14use crate::planner::{ContextProvider, PlannerContext, SqlToRel};
15use crate::utils::normalize_ident;
16
17use arrow::datatypes::{Field, FieldRef, Fields, Metadata};
18use datafusion_common::error::_plan_err;
19use datafusion_common::format::ExplainStatementOptions;
20use datafusion_common::parsers::CompressionTypeVariant;
21use datafusion_common::{
22 Column, Constraint, Constraints, DFSchema, DFSchemaRef, DataFusionError, Result,
23 ScalarValue, SchemaError, SchemaReference, TableReference, ToDFSchema, exec_err,
24 internal_err, not_impl_err, plan_datafusion_err, plan_err, schema_err,
25 unqualified_field_not_found,
26};
27use datafusion_expr::dml::{
28 CopyTo, InsertOp, MergeIntoAction, MergeIntoClause, MergeIntoClauseKind, MergeIntoOp,
29};
30use datafusion_expr::expr_rewriter::normalize_col_with_schemas_and_ambiguity_check;
31use datafusion_expr::logical_plan::DdlStatement;
32use datafusion_expr::logical_plan::builder::project;
33use datafusion_expr::logical_plan::information_schema::ColumnsDetail;
34use datafusion_expr::utils::expr_to_columns;
35use datafusion_expr::{
36 Analyze, Cast, CreateCatalog, CreateCatalogSchema,
37 CreateExternalCatalog as PlanCreateExternalCatalog,
38 CreateExternalTable as PlanCreateExternalTable, CreateFunction, CreateFunctionBody,
39 CreateIndex as PlanCreateIndex, CreateMemoryTable, CreateView, Deallocate,
40 DmlStatement, DropCatalog, DropCatalogSchema, DropFunction, DropTable, DropView,
41 EmptyRelation, Execute, Explain, ExplainFormat, Expr, ExprSchemable, Filter,
42 LogicalPlan, LogicalPlanBuilder, OperateFunctionArg, PlanType, Prepare,
43 ResetVariable, SetVariable, SortExpr, Statement as PlanStatement, ToStringifiedPlan,
44 TransactionAccessMode, TransactionConclusion, TransactionEnd,
45 TransactionIsolationLevel, TransactionStart, Volatility, WriteOp, cast,
46};
47use sqlparser::ast::{
48 self, BeginTransactionKind, CheckConstraint, ForeignKeyConstraint, IndexColumn,
49 IndexType, NullsDistinctOption, OrderByExpr, OrderByOptions, PrimaryKeyConstraint,
50 Set, ShowStatementIn, ShowStatementOptions, SqliteOnConflict, TableObject,
51 UniqueConstraint, Update, UpdateTableFromKind, ValueWithSpan,
52};
53use sqlparser::ast::{
54 Assignment, AssignmentTarget, ColumnDef, CreateIndex, CreateTable,
55 CreateTableOptions, Delete, DescribeAlias, Expr as SQLExpr, FromTable, Ident, Insert,
56 ObjectName, ObjectType, Query, SchemaName, SetExpr, ShowCreateObject,
57 ShowStatementFilter, Statement, TableConstraint, TableFactor, TableWithJoins,
58 TransactionMode, UnaryOperator, Value,
59};
60use sqlparser::parser::ParserError::ParserError;
61
62fn ident_to_string(ident: &Ident) -> String {
63 normalize_ident(ident.to_owned())
64}
65
66fn object_name_to_string(object_name: &ObjectName) -> String {
67 object_name
68 .0
69 .iter()
70 .map(|object_name_part| {
71 object_name_part
72 .as_ident()
73 .map_or_else(String::new, ident_to_string)
76 })
77 .collect::<Vec<String>>()
78 .join(".")
79}
80
81fn get_schema_name(schema_name: &SchemaName) -> String {
82 match schema_name {
83 SchemaName::Simple(schema_name) => object_name_to_string(schema_name),
84 SchemaName::UnnamedAuthorization(auth) => ident_to_string(auth),
85 SchemaName::NamedAuthorization(schema_name, auth) => format!(
86 "{}.{}",
87 object_name_to_string(schema_name),
88 ident_to_string(auth)
89 ),
90 }
91}
92
93fn calc_inline_constraints_from_columns(columns: &[ColumnDef]) -> Vec<TableConstraint> {
96 let mut constraints: Vec<TableConstraint> = vec![];
97 for column in columns {
98 for ast::ColumnOptionDef { name, option } in &column.options {
99 match option {
100 ast::ColumnOption::Unique(UniqueConstraint {
101 characteristics,
102 name,
103 index_name: _index_name,
104 index_type_display: _index_type_display,
105 index_type: _index_type,
106 columns: _column,
107 include: _include,
108 index_options: _index_options,
109 nulls_distinct: _nulls_distinct,
110 }) => constraints.push(TableConstraint::Unique(UniqueConstraint {
111 name: name.clone(),
112 index_name: None,
113 index_type_display: ast::KeyOrIndexDisplay::None,
114 index_type: None,
115 columns: vec![IndexColumn {
116 column: OrderByExpr {
117 expr: SQLExpr::Identifier(column.name.clone()),
118 options: OrderByOptions {
119 sort: None,
120 nulls_first: None,
121 },
122 with_fill: None,
123 },
124 operator_class: None,
125 }],
126 include: vec![],
127 index_options: vec![],
128 characteristics: *characteristics,
129 nulls_distinct: NullsDistinctOption::None,
130 })),
131 ast::ColumnOption::PrimaryKey(PrimaryKeyConstraint {
132 characteristics,
133 name: _name,
134 index_name: _index_name,
135 index_type: _index_type,
136 columns: _columns,
137 include: _include,
138 index_options: _index_options,
139 }) => {
140 constraints.push(TableConstraint::PrimaryKey(PrimaryKeyConstraint {
141 name: name.clone(),
142 index_name: None,
143 index_type: None,
144 columns: vec![IndexColumn {
145 column: OrderByExpr {
146 expr: SQLExpr::Identifier(column.name.clone()),
147 options: OrderByOptions {
148 sort: None,
149 nulls_first: None,
150 },
151 with_fill: None,
152 },
153 operator_class: None,
154 }],
155 include: vec![],
156 index_options: vec![],
157 characteristics: *characteristics,
158 }))
159 }
160 ast::ColumnOption::ForeignKey(ForeignKeyConstraint {
161 foreign_table,
162 referred_columns,
163 on_delete,
164 on_update,
165 characteristics,
166 name: _name,
167 index_name: _index_name,
168 columns: _columns,
169 match_kind: _match_kind,
170 }) => {
171 constraints.push(TableConstraint::ForeignKey(ForeignKeyConstraint {
172 name: name.clone(),
173 index_name: None,
174 columns: vec![],
175 foreign_table: foreign_table.clone(),
176 referred_columns: referred_columns.clone(),
177 on_delete: *on_delete,
178 on_update: *on_update,
179 match_kind: None,
180 characteristics: *characteristics,
181 }))
182 }
183 ast::ColumnOption::Check(CheckConstraint {
184 name,
185 expr,
186 no_inherit: _no_inherit,
187 enforced: _enforced,
188 }) => constraints.push(TableConstraint::Check(CheckConstraint {
189 name: name.clone(),
190 expr: expr.clone(),
191 no_inherit: false,
192 enforced: None,
193 })),
194 ast::ColumnOption::Default(_)
195 | ast::ColumnOption::Null
196 | ast::ColumnOption::NotNull
197 | ast::ColumnOption::DialectSpecific(_)
198 | ast::ColumnOption::CharacterSet(_)
199 | ast::ColumnOption::Generated { .. }
200 | ast::ColumnOption::Comment(_)
201 | ast::ColumnOption::Options(_)
202 | ast::ColumnOption::OnUpdate(_)
203 | ast::ColumnOption::Materialized(_)
204 | ast::ColumnOption::Ephemeral(_)
205 | ast::ColumnOption::Identity(_)
206 | ast::ColumnOption::OnConflict(_)
207 | ast::ColumnOption::Policy(_)
208 | ast::ColumnOption::Tags(_)
209 | ast::ColumnOption::Alias(_)
210 | ast::ColumnOption::Srid(_)
211 | ast::ColumnOption::Collation(_)
212 | ast::ColumnOption::Invisible => {}
213 }
214 }
215 }
216 constraints
217}
218
219impl<S: ContextProvider> SqlToRel<'_, S> {
220 pub fn statement_to_plan(&self, statement: DFStatement) -> Result<LogicalPlan> {
222 let plan = match statement {
223 DFStatement::CreateExternalTable(s) => self.external_table_to_plan(s)?,
224 DFStatement::CreateExternalCatalog(s) => self.external_catalog_to_plan(s)?,
225 DFStatement::Statement(s) => self.sql_statement_to_plan(*s)?,
226 DFStatement::CopyTo(s) => self.copy_to_plan(s)?,
227 DFStatement::Explain(ExplainStatement { options, statement }) => {
228 self.explain_to_plan(options, *statement)?
229 }
230 DFStatement::Reset(statement) => self.reset_statement_to_plan(statement)?,
231 };
232 check_plan(&plan)?;
233 Ok(plan)
234 }
235
236 pub fn sql_statement_to_plan(&self, statement: Statement) -> Result<LogicalPlan> {
238 self.sql_statement_to_plan_with_context(statement, &mut PlannerContext::new())
239 }
240
241 pub fn sql_statement_to_plan_with_context(
243 &self,
244 statement: Statement,
245 planner_context: &mut PlannerContext,
246 ) -> Result<LogicalPlan> {
247 let plan =
248 self.sql_statement_to_plan_with_context_impl(statement, planner_context)?;
249 check_plan(&plan)?;
250 Ok(plan)
251 }
252
253 fn sql_statement_to_plan_with_context_impl(
254 &self,
255 statement: Statement,
256 planner_context: &mut PlannerContext,
257 ) -> Result<LogicalPlan> {
258 match statement {
259 Statement::ExplainTable {
260 describe_alias: DescribeAlias::Describe | DescribeAlias::Desc, table_name,
262 ..
263 } => self.describe_table_to_plan(table_name),
264 Statement::Explain {
265 describe_alias: DescribeAlias::Describe | DescribeAlias::Desc, statement,
267 ..
268 } => match *statement {
269 Statement::Query(query) => self.describe_query_to_plan(*query),
270 _ => {
271 not_impl_err!("Describing statements other than SELECT not supported")
272 }
273 },
274 Statement::Explain {
275 verbose,
276 statement,
277 analyze,
278 format,
279 ..
280 } => {
281 let format = format
282 .map(|format| ExplainFormat::from_str(&format.to_string()))
283 .transpose()?;
284 let statement = DFStatement::Statement(statement);
285 let options = ExplainStatementOptions {
286 analyze,
287 verbose,
288 format,
289 analyze_level: None,
290 analyze_categories: None,
291 show_statistics: None,
292 };
293 self.explain_to_plan(options, statement)
294 }
295 Statement::Query(query) => self.query_to_plan(*query, planner_context),
296 Statement::ShowVariable { variable } => self.show_variable_to_plan(&variable),
297 Statement::Set(statement) => self.set_statement_to_plan(statement),
298 Statement::CreateTable(CreateTable {
299 temporary,
300 external,
301 global,
302 transient,
303 volatile,
304 hive_distribution,
305 hive_formats,
306 file_format,
307 location,
308 query,
309 name,
310 columns,
311 constraints,
312 if_not_exists,
313 or_replace,
314 without_rowid,
315 like,
316 clone,
317 comment,
318 on_commit,
319 on_cluster,
320 primary_key,
321 order_by,
322 partition_by,
323 cluster_by,
324 clustered_by,
325 strict,
326 copy_grants,
327 enable_schema_evolution,
328 change_tracking,
329 data_retention_time_in_days,
330 max_data_extension_time_in_days,
331 default_ddl_collation,
332 with_aggregation_policy,
333 with_row_access_policy,
334 with_tags,
335 iceberg,
336 external_volume,
337 base_location,
338 catalog,
339 catalog_sync,
340 storage_serialization_policy,
341 inherits,
342 table_options: CreateTableOptions::None,
343 dynamic,
344 version,
345 target_lag,
346 warehouse,
347 refresh_mode,
348 initialize,
349 require_user,
350 partition_of,
351 for_values,
352 snapshot,
353 with_storage_lifecycle_policy,
354 diststyle,
355 distkey,
356 sortkey,
357 backup,
358 unlogged,
359 with_connection,
360 multiset,
361 fallback,
362 with_data,
363 }) => {
364 if temporary {
365 return not_impl_err!("Temporary tables not supported");
366 }
367 if external {
368 return not_impl_err!("External tables not supported");
369 }
370 if global.is_some() {
371 return not_impl_err!("Global tables not supported");
372 }
373 if transient {
374 return not_impl_err!("Transient tables not supported");
375 }
376 if volatile {
377 return not_impl_err!("Volatile tables not supported");
378 }
379 if hive_distribution != ast::HiveDistributionStyle::NONE {
380 return not_impl_err!(
381 "Hive distribution not supported: {hive_distribution:?}"
382 );
383 }
384 if hive_formats.is_some()
385 && !matches!(
386 hive_formats,
387 Some(ast::HiveFormat {
388 row_format: None,
389 serde_properties: None,
390 storage: None,
391 location: None,
392 })
393 )
394 {
395 return not_impl_err!("Hive formats not supported: {hive_formats:?}");
396 }
397 if file_format.is_some() {
398 return not_impl_err!("File format not supported");
399 }
400 if location.is_some() {
401 return not_impl_err!("Location not supported");
402 }
403 if without_rowid {
404 return not_impl_err!("Without rowid not supported");
405 }
406 if like.is_some() {
407 return not_impl_err!("Like not supported");
408 }
409 if clone.is_some() {
410 return not_impl_err!("Clone not supported");
411 }
412 if comment.is_some() {
413 return not_impl_err!("Comment not supported");
414 }
415 if on_commit.is_some() {
416 return not_impl_err!("On commit not supported");
417 }
418 if on_cluster.is_some() {
419 return not_impl_err!("On cluster not supported");
420 }
421 if primary_key.is_some() {
422 return not_impl_err!("Primary key not supported");
423 }
424 if order_by.is_some() {
425 return not_impl_err!("Order by not supported");
426 }
427 if partition_by.is_some() {
428 return not_impl_err!("Partition by not supported");
429 }
430 if cluster_by.is_some() {
431 return not_impl_err!("Cluster by not supported");
432 }
433 if clustered_by.is_some() {
434 return not_impl_err!("Clustered by not supported");
435 }
436 if strict {
437 return not_impl_err!("Strict not supported");
438 }
439 if copy_grants {
440 return not_impl_err!("Copy grants not supported");
441 }
442 if enable_schema_evolution.is_some() {
443 return not_impl_err!("Enable schema evolution not supported");
444 }
445 if change_tracking.is_some() {
446 return not_impl_err!("Change tracking not supported");
447 }
448 if data_retention_time_in_days.is_some() {
449 return not_impl_err!("Data retention time in days not supported");
450 }
451 if max_data_extension_time_in_days.is_some() {
452 return not_impl_err!(
453 "Max data extension time in days not supported"
454 );
455 }
456 if default_ddl_collation.is_some() {
457 return not_impl_err!("Default DDL collation not supported");
458 }
459 if with_aggregation_policy.is_some() {
460 return not_impl_err!("With aggregation policy not supported");
461 }
462 if with_row_access_policy.is_some() {
463 return not_impl_err!("With row access policy not supported");
464 }
465 if with_tags.is_some() {
466 return not_impl_err!("With tags not supported");
467 }
468 if iceberg {
469 return not_impl_err!("Iceberg not supported");
470 }
471 if external_volume.is_some() {
472 return not_impl_err!("External volume not supported");
473 }
474 if base_location.is_some() {
475 return not_impl_err!("Base location not supported");
476 }
477 if catalog.is_some() {
478 return not_impl_err!("Catalog not supported");
479 }
480 if catalog_sync.is_some() {
481 return not_impl_err!("Catalog sync not supported");
482 }
483 if storage_serialization_policy.is_some() {
484 return not_impl_err!("Storage serialization policy not supported");
485 }
486 if inherits.is_some() {
487 return not_impl_err!("Table inheritance not supported");
488 }
489 if dynamic {
490 return not_impl_err!("Dynamic tables not supported");
491 }
492 if version.is_some() {
493 return not_impl_err!("Version not supported");
494 }
495 if target_lag.is_some() {
496 return not_impl_err!("Target lag not supported");
497 }
498 if warehouse.is_some() {
499 return not_impl_err!("Warehouse not supported");
500 }
501 if refresh_mode.is_some() {
502 return not_impl_err!("Refresh mode not supported");
503 }
504 if initialize.is_some() {
505 return not_impl_err!("Initialize not supported");
506 }
507 if require_user {
508 return not_impl_err!("Require user not supported");
509 }
510 if partition_of.is_some() {
511 return not_impl_err!("PARTITION OF not supported");
512 }
513 if for_values.is_some() {
514 return not_impl_err!("PARTITION OF .. FOR VALUES .. not supported");
515 }
516 if snapshot {
517 return not_impl_err!("Snapshot tables not supported");
518 }
519 if with_storage_lifecycle_policy.is_some() {
520 return not_impl_err!("WITH STORAGE LIFECYCLE POLICY not supported");
521 }
522 if diststyle.is_some() {
523 return not_impl_err!("DISTSTYLE not supported");
524 }
525 if distkey.is_some() {
526 return not_impl_err!("DISTKEY not supported");
527 }
528 if sortkey.is_some() {
529 return not_impl_err!("SORTKEY not supported");
530 }
531 if backup.is_some() {
532 return not_impl_err!("BACKUP not supported");
533 }
534 if unlogged {
535 return not_impl_err!("UNLOGGED tables not supported");
536 }
537 if with_connection.is_some() {
538 return not_impl_err!("WITH CONNECTION not supported");
539 }
540 if multiset.is_some() {
541 return not_impl_err!("MULTISET tables not supported");
542 }
543 if fallback.is_some() {
544 return not_impl_err!("FALLBACK not supported");
545 }
546 if with_data.is_some() {
547 return not_impl_err!("WITH [NO] DATA not supported");
548 }
549 let mut all_constraints = constraints;
551 let inline_constraints = calc_inline_constraints_from_columns(&columns);
552 all_constraints.extend(inline_constraints);
553 let column_defaults =
555 self.build_column_defaults(&columns, planner_context)?;
556
557 let has_columns = !columns.is_empty();
558 let schema = self.build_schema(columns)?.to_dfschema_ref()?;
559 if has_columns {
560 planner_context.set_table_schema(Some(Arc::clone(&schema)));
561 }
562
563 match query {
564 Some(query) => {
565 let plan = self.query_to_plan(*query, planner_context)?;
566 let input_schema = plan.schema();
567
568 let plan = if has_columns {
569 if schema.fields().len() != input_schema.fields().len() {
570 return plan_err!(
571 "Mismatch: {} columns specified, but result has {} columns",
572 schema.fields().len(),
573 input_schema.fields().len()
574 );
575 }
576 let input_columns = input_schema.columns();
577 let project_exprs = schema
578 .fields()
579 .iter()
580 .zip(input_columns)
581 .map(|(field, input_column)| {
582 cast(
583 Expr::Column(input_column),
584 field.data_type().clone(),
585 )
586 .alias(field.name())
587 })
588 .collect::<Vec<_>>();
589
590 LogicalPlanBuilder::from(plan.clone())
591 .project(project_exprs)?
592 .build()?
593 } else {
594 plan
595 };
596
597 let constraints = self.new_constraint_from_table_constraints(
598 &all_constraints,
599 plan.schema(),
600 )?;
601
602 Ok(LogicalPlan::Ddl(DdlStatement::CreateMemoryTable(
603 CreateMemoryTable {
604 name: self.object_name_to_table_reference(name)?,
605 constraints,
606 input: Arc::new(plan),
607 if_not_exists,
608 or_replace,
609 column_defaults,
610 temporary,
611 },
612 )))
613 }
614
615 None => {
616 let plan = EmptyRelation {
617 produce_one_row: false,
618 schema,
619 };
620 let plan = LogicalPlan::EmptyRelation(plan);
621 let constraints = self.new_constraint_from_table_constraints(
622 &all_constraints,
623 plan.schema(),
624 )?;
625 Ok(LogicalPlan::Ddl(DdlStatement::CreateMemoryTable(
626 CreateMemoryTable {
627 name: self.object_name_to_table_reference(name)?,
628 constraints,
629 input: Arc::new(plan),
630 if_not_exists,
631 or_replace,
632 column_defaults,
633 temporary,
634 },
635 )))
636 }
637 }
638 }
639 Statement::CreateView(ast::CreateView {
640 or_replace,
641 materialized,
642 name,
643 columns,
644 query,
645 options: CreateTableOptions::None,
646 cluster_by,
647 comment,
648 with_no_schema_binding,
649 if_not_exists,
650 temporary,
651 to,
652 params,
653 or_alter,
654 secure,
655 name_before_not_exists,
656 copy_grants,
657 }) => {
658 if materialized {
659 return not_impl_err!("Materialized views not supported")?;
660 }
661 if !cluster_by.is_empty() {
662 return not_impl_err!("Cluster by not supported")?;
663 }
664 if comment.is_some() {
665 return not_impl_err!("Comment not supported")?;
666 }
667 if with_no_schema_binding {
668 return not_impl_err!("With no schema binding not supported")?;
669 }
670 if if_not_exists {
671 return not_impl_err!("If not exists not supported")?;
672 }
673 if to.is_some() {
674 return not_impl_err!("To not supported")?;
675 }
676 if copy_grants {
677 return not_impl_err!("COPY GRANTS not supported")?;
678 }
679
680 let stmt = Statement::CreateView(ast::CreateView {
683 or_replace,
684 materialized,
685 name,
686 columns,
687 query,
688 options: CreateTableOptions::None,
689 cluster_by,
690 comment,
691 with_no_schema_binding,
692 if_not_exists,
693 temporary,
694 to,
695 params,
696 or_alter,
697 secure,
698 name_before_not_exists,
699 copy_grants,
700 });
701 let sql = stmt.to_string();
702 let Statement::CreateView(ast::CreateView {
703 name,
704 columns,
705 query,
706 or_replace,
707 temporary,
708 ..
709 }) = stmt
710 else {
711 return internal_err!("Unreachable code in create view");
712 };
713
714 let columns = columns
715 .into_iter()
716 .map(|view_column_def| {
717 if let Some(options) = view_column_def.options {
718 plan_err!(
719 "Options not supported for view columns: {options:?}"
720 )
721 } else {
722 Ok(view_column_def.name)
723 }
724 })
725 .collect::<Result<Vec<_>>>()?;
726
727 let mut plan = self.query_to_plan(*query, &mut PlannerContext::new())?;
728 plan = self.apply_expr_alias(plan, columns)?;
729
730 Ok(LogicalPlan::Ddl(DdlStatement::CreateView(CreateView {
731 name: self.object_name_to_table_reference(name)?,
732 input: Arc::new(plan),
733 or_replace,
734 definition: Some(sql),
735 temporary,
736 })))
737 }
738 Statement::ShowCreate { obj_type, obj_name } => match obj_type {
739 ShowCreateObject::Table => self.show_create_table_to_plan(obj_name),
740 _ => {
741 not_impl_err!("Only `SHOW CREATE TABLE ...` statement is supported")
742 }
743 },
744 Statement::CreateSchema {
745 schema_name,
746 if_not_exists,
747 ..
748 } => Ok(LogicalPlan::Ddl(DdlStatement::CreateCatalogSchema(
749 CreateCatalogSchema {
750 schema_name: get_schema_name(&schema_name),
751 if_not_exists,
752 schema: Arc::new(DFSchema::empty()),
753 },
754 ))),
755 Statement::CreateDatabase {
756 db_name,
757 if_not_exists,
758 ..
759 } => Ok(LogicalPlan::Ddl(DdlStatement::CreateCatalog(
760 CreateCatalog {
761 catalog_name: object_name_to_string(&db_name),
762 if_not_exists,
763 schema: Arc::new(DFSchema::empty()),
764 },
765 ))),
766 Statement::Drop {
767 object_type,
768 if_exists,
769 mut names,
770 cascade,
771 restrict: _,
772 purge: _,
773 temporary: _,
774 table: _,
775 } => {
776 let name = match names.len() {
779 0 => Err::<_, DataFusionError>(
780 ParserError("Missing table name.".to_string()).into(),
781 ),
782 1 => Ok(names.pop().unwrap()),
783 _ => Err::<_, DataFusionError>(
784 ParserError("Multiple objects not supported".to_string()).into(),
785 ),
786 }?;
787
788 match object_type {
789 ObjectType::Table => {
790 Ok(LogicalPlan::Ddl(DdlStatement::DropTable(DropTable {
791 name: self.object_name_to_table_reference(name)?,
792 if_exists,
793 schema: DFSchemaRef::new(DFSchema::empty()),
794 })))
795 }
796 ObjectType::View => {
797 Ok(LogicalPlan::Ddl(DdlStatement::DropView(DropView {
798 name: self.object_name_to_table_reference(name)?,
799 if_exists,
800 schema: DFSchemaRef::new(DFSchema::empty()),
801 })))
802 }
803 ObjectType::Schema => {
804 let name = match self.object_name_to_table_reference(name)? {
805 TableReference::Bare { table } => {
806 Ok(SchemaReference::Bare { schema: table })
807 }
808 TableReference::Partial { schema, table } => {
809 Ok(SchemaReference::Full {
810 schema: table,
811 catalog: schema,
812 })
813 }
814 TableReference::Full {
815 catalog: _,
816 schema: _,
817 table: _,
818 } => Err(ParserError(
819 "Invalid schema specifier (has 3 parts)".to_string(),
820 )),
821 }?;
822 Ok(LogicalPlan::Ddl(DdlStatement::DropCatalogSchema(
823 DropCatalogSchema {
824 name,
825 if_exists,
826 cascade,
827 schema: DFSchemaRef::new(DFSchema::empty()),
828 },
829 )))
830 }
831 ObjectType::Database => {
832 Ok(LogicalPlan::Ddl(DdlStatement::DropCatalog(
833 DropCatalog::builder(object_name_to_string(&name))
834 .with_if_exists(if_exists)
835 .with_cascade(cascade)
836 .build(),
837 )))
838 }
839 _ => not_impl_err!(
840 "Only `DROP TABLE/VIEW/SCHEMA/CATALOG/DATABASE ...` statement is supported currently"
841 ),
842 }
843 }
844 Statement::Prepare {
845 name,
846 data_types,
847 statement,
848 } => {
849 let mut fields: Vec<FieldRef> = data_types
851 .into_iter()
852 .map(|t| self.convert_data_type_to_field(&t))
853 .collect::<Result<_>>()?;
854
855 let mut planner_context = PlannerContext::new()
857 .with_prepare_param_data_types(
858 fields.iter().cloned().map(Some).collect(),
859 );
860
861 let plan = self.sql_statement_to_plan_with_context_impl(
863 *statement,
864 &mut planner_context,
865 )?;
866
867 if fields.is_empty() {
868 let map_types = plan.get_parameter_fields()?;
869 let param_types: Option<Vec<FieldRef>> = (1..=map_types.len())
870 .map(|i| {
871 let key = format!("${i}");
872 map_types.get(&key).and_then(|opt| opt.clone())
873 })
874 .collect();
875 if let Some(param_types) = param_types {
876 fields.extend(param_types.iter().cloned());
877 planner_context.with_prepare_param_data_types(
878 param_types.into_iter().map(Some).collect(),
879 );
880 }
881 }
882
883 Ok(LogicalPlan::Statement(PlanStatement::Prepare(Prepare {
884 name: ident_to_string(&name),
885 fields,
886 input: Arc::new(plan),
887 })))
888 }
889 Statement::Execute {
890 name,
891 parameters,
892 using,
893 has_parentheses: _,
896 immediate,
897 into,
898 output,
899 default,
900 } => {
901 if !using.is_empty() {
903 return not_impl_err!(
904 "Execute statement with USING is not supported"
905 );
906 }
907 if immediate {
908 return not_impl_err!(
909 "Execute statement with IMMEDIATE is not supported"
910 );
911 }
912 if !into.is_empty() {
913 return not_impl_err!("Execute statement with INTO is not supported");
914 }
915 if output {
916 return not_impl_err!(
917 "Execute statement with OUTPUT is not supported"
918 );
919 }
920 if default {
921 return not_impl_err!(
922 "Execute statement with DEFAULT is not supported"
923 );
924 }
925 let name = name.ok_or_else(|| {
926 plan_datafusion_err!("EXECUTE statement requires a name")
927 })?;
928
929 let empty_schema = DFSchema::empty();
930 let parameters = parameters
931 .into_iter()
932 .map(|expr| self.sql_to_expr(expr, &empty_schema, planner_context))
933 .collect::<Result<Vec<Expr>>>()?;
934
935 Ok(LogicalPlan::Statement(PlanStatement::Execute(Execute {
936 name: object_name_to_string(&name),
937 parameters,
938 })))
939 }
940 Statement::Deallocate {
941 name,
942 prepare: _,
944 } => Ok(LogicalPlan::Statement(PlanStatement::Deallocate(
945 Deallocate {
946 name: ident_to_string(&name),
947 },
948 ))),
949
950 Statement::ShowTables {
951 extended,
952 full,
953 terse,
954 history,
955 external,
956 show_options,
957 } => {
958 if extended {
961 return not_impl_err!("SHOW TABLES EXTENDED not supported")?;
962 }
963 if full {
964 return not_impl_err!("SHOW FULL TABLES not supported")?;
965 }
966 if terse {
967 return not_impl_err!("SHOW TERSE TABLES not supported")?;
968 }
969 if history {
970 return not_impl_err!("SHOW TABLES HISTORY not supported")?;
971 }
972 if external {
973 return not_impl_err!("SHOW EXTERNAL TABLES not supported")?;
974 }
975 let ShowStatementOptions {
976 show_in,
977 starts_with,
978 limit,
979 limit_from,
980 filter_position,
981 } = show_options;
982 if show_in.is_some() {
983 return not_impl_err!("SHOW TABLES IN not supported")?;
984 }
985 if starts_with.is_some() {
986 return not_impl_err!("SHOW TABLES LIKE not supported")?;
987 }
988 if limit.is_some() {
989 return not_impl_err!("SHOW TABLES LIMIT not supported")?;
990 }
991 if limit_from.is_some() {
992 return not_impl_err!("SHOW TABLES LIMIT FROM not supported")?;
993 }
994 if filter_position.is_some() {
995 return not_impl_err!("SHOW TABLES FILTER not supported")?;
996 }
997 self.show_tables_to_plan()
998 }
999
1000 Statement::ShowColumns {
1001 extended,
1002 full,
1003 show_options,
1004 } => {
1005 let ShowStatementOptions {
1006 show_in,
1007 starts_with,
1008 limit,
1009 limit_from,
1010 filter_position,
1011 } = show_options;
1012 if starts_with.is_some() {
1013 return not_impl_err!("SHOW COLUMNS LIKE not supported")?;
1014 }
1015 if limit.is_some() {
1016 return not_impl_err!("SHOW COLUMNS LIMIT not supported")?;
1017 }
1018 if limit_from.is_some() {
1019 return not_impl_err!("SHOW COLUMNS LIMIT FROM not supported")?;
1020 }
1021 if filter_position.is_some() {
1022 return not_impl_err!(
1023 "SHOW COLUMNS with WHERE or LIKE is not supported"
1024 )?;
1025 }
1026 let Some(ShowStatementIn {
1027 clause: _,
1030 parent_type,
1031 parent_name,
1032 }) = show_in
1033 else {
1034 return plan_err!("SHOW COLUMNS requires a table name");
1035 };
1036
1037 if let Some(parent_type) = parent_type {
1038 return not_impl_err!("SHOW COLUMNS IN {parent_type} not supported");
1039 }
1040 let Some(table_name) = parent_name else {
1041 return plan_err!("SHOW COLUMNS requires a table name");
1042 };
1043
1044 self.show_columns_to_plan(extended, full, table_name)
1045 }
1046
1047 Statement::ShowFunctions { filter, .. } => {
1048 self.show_functions_to_plan(filter)
1049 }
1050
1051 Statement::Insert(Insert {
1052 or,
1053 into,
1054 columns,
1055 overwrite,
1056 source,
1057 partitioned,
1058 after_columns,
1059 table,
1060 on,
1061 returning,
1062 ignore,
1063 table_alias,
1064 mut replace_into,
1065 priority,
1066 insert_alias,
1067 assignments,
1068 has_table_keyword,
1069 settings,
1070 format_clause,
1071 insert_token: _, optimizer_hints,
1073 output,
1074 multi_table_insert_type,
1075 multi_table_into_clauses,
1076 multi_table_when_clauses,
1077 multi_table_else_clause,
1078 }) => {
1079 let table_name = match table {
1080 TableObject::TableName(table_name) => table_name,
1081 TableObject::TableFunction(_) => {
1082 return not_impl_err!(
1083 "INSERT INTO Table functions not supported"
1084 );
1085 }
1086 TableObject::TableQuery(_) => {
1087 return not_impl_err!(
1088 "INSERT INTO subquery target not supported"
1089 );
1090 }
1091 };
1092 if let Some(or) = or {
1093 match or {
1094 SqliteOnConflict::Replace => replace_into = true,
1095 _ => plan_err!("Inserts with {or} clause is not supported")?,
1096 }
1097 }
1098 if partitioned.is_some() {
1099 plan_err!("Partitioned inserts not yet supported")?;
1100 }
1101 if !after_columns.is_empty() {
1102 plan_err!("After-columns clause not supported")?;
1103 }
1104 if on.is_some() {
1105 plan_err!("Insert-on clause not supported")?;
1106 }
1107 if returning.is_some() {
1108 plan_err!("Insert-returning clause not supported")?;
1109 }
1110 if ignore {
1111 plan_err!("Insert-ignore clause not supported")?;
1112 }
1113 let Some(source) = source else {
1114 plan_err!("Inserts without a source not supported")?
1115 };
1116 if let Some(table_alias) = table_alias {
1117 plan_err!(
1118 "Inserts with a table alias not supported: {table_alias:?}"
1119 )?
1120 }
1121 if let Some(priority) = priority {
1122 plan_err!(
1123 "Inserts with a `PRIORITY` clause not supported: {priority:?}"
1124 )?
1125 }
1126 if insert_alias.is_some() {
1127 plan_err!("Inserts with an alias not supported")?;
1128 }
1129 if !assignments.is_empty() {
1130 plan_err!("Inserts with assignments not supported")?;
1131 }
1132 if settings.is_some() {
1133 plan_err!("Inserts with settings not supported")?;
1134 }
1135 if format_clause.is_some() {
1136 plan_err!("Inserts with format clause not supported")?;
1137 }
1138 if !optimizer_hints.is_empty() {
1139 plan_err!("Optimizer hints not supported")?;
1140 }
1141 if output.is_some() {
1142 plan_err!("Insert OUTPUT clause not supported")?;
1143 }
1144 if multi_table_insert_type.is_some()
1145 || !multi_table_into_clauses.is_empty()
1146 || !multi_table_when_clauses.is_empty()
1147 || multi_table_else_clause.is_some()
1148 {
1149 plan_err!("Multi-table INSERT not supported")?;
1150 }
1151 let _ = into;
1153 let _ = has_table_keyword;
1154 self.insert_to_plan(table_name, columns, source, overwrite, replace_into)
1155 }
1156 Statement::Update(Update {
1157 table,
1158 assignments,
1159 from,
1160 selection,
1161 returning,
1162 or,
1163 limit,
1164 update_token: _,
1165 optimizer_hints,
1166 output,
1167 order_by,
1168 }) => {
1169 let from_clauses =
1170 from.map(|update_table_from_kind| match update_table_from_kind {
1171 UpdateTableFromKind::BeforeSet(from_clauses) => from_clauses,
1172 UpdateTableFromKind::AfterSet(from_clauses) => from_clauses,
1173 });
1174 if from_clauses.as_ref().is_some_and(|f| f.len() > 1) {
1176 not_impl_err!(
1177 "Multiple tables in UPDATE SET FROM not yet supported"
1178 )?;
1179 }
1180 let update_from = from_clauses.and_then(|mut f| f.pop());
1181
1182 if update_from.is_some() {
1185 return not_impl_err!("UPDATE ... FROM is not supported");
1186 }
1187
1188 if returning.is_some() {
1189 plan_err!("Update-returning clause not yet supported")?;
1190 }
1191 if or.is_some() {
1192 plan_err!("ON conflict not supported")?;
1193 }
1194 if limit.is_some() {
1195 return not_impl_err!("Update-limit clause not supported")?;
1196 }
1197 if !optimizer_hints.is_empty() {
1198 plan_err!("Optimizer hints not supported")?;
1199 }
1200 if output.is_some() {
1201 plan_err!("Update OUTPUT clause not supported")?;
1202 }
1203 if !order_by.is_empty() {
1204 plan_err!("Update ORDER BY not supported")?;
1205 }
1206 self.update_to_plan(table, &assignments, update_from, selection)
1207 }
1208
1209 Statement::Delete(Delete {
1210 tables,
1211 using,
1212 selection,
1213 returning,
1214 from,
1215 order_by,
1216 limit,
1217 delete_token: _,
1218 optimizer_hints,
1219 output,
1220 }) => {
1221 if !tables.is_empty() {
1222 plan_err!("DELETE <TABLE> not supported")?;
1223 }
1224
1225 if using.is_some() {
1226 plan_err!("Using clause not supported")?;
1227 }
1228
1229 if returning.is_some() {
1230 plan_err!("Delete-returning clause not yet supported")?;
1231 }
1232
1233 if !order_by.is_empty() {
1234 plan_err!("Delete-order-by clause not yet supported")?;
1235 }
1236
1237 if limit.is_some() {
1238 return plan_err!("Delete-limit clause is not supported");
1239 }
1240
1241 if !optimizer_hints.is_empty() {
1242 plan_err!("Optimizer hints not supported")?;
1243 }
1244 if output.is_some() {
1245 plan_err!("Delete OUTPUT clause not supported")?;
1246 }
1247
1248 let table_name = self.get_delete_target(from)?;
1249 self.delete_to_plan(&table_name, selection)
1250 }
1251
1252 Statement::Merge(merge) => self.merge_to_plan(merge),
1253
1254 Statement::StartTransaction {
1255 modes,
1256 begin: false,
1257 modifier,
1258 transaction,
1259 statements,
1260 has_end_keyword,
1261 exception,
1262 } => {
1263 if let Some(modifier) = modifier {
1264 return not_impl_err!(
1265 "Transaction modifier not supported: {modifier}"
1266 );
1267 }
1268 if !statements.is_empty() {
1269 return not_impl_err!(
1270 "Transaction with multiple statements not supported"
1271 );
1272 }
1273 if exception.is_some() {
1274 return not_impl_err!(
1275 "Transaction with exception statements not supported"
1276 );
1277 }
1278 if has_end_keyword {
1279 return not_impl_err!("Transaction with END keyword not supported");
1280 }
1281 self.validate_transaction_kind(transaction.as_ref())?;
1282 let isolation_level: ast::TransactionIsolationLevel = modes
1283 .iter()
1284 .filter_map(|m: &TransactionMode| match m {
1285 TransactionMode::AccessMode(_) => None,
1286 TransactionMode::IsolationLevel(level) => Some(level),
1287 })
1288 .next_back()
1289 .copied()
1290 .unwrap_or(ast::TransactionIsolationLevel::Serializable);
1291 let access_mode: ast::TransactionAccessMode = modes
1292 .iter()
1293 .filter_map(|m: &TransactionMode| match m {
1294 TransactionMode::AccessMode(mode) => Some(mode),
1295 TransactionMode::IsolationLevel(_) => None,
1296 })
1297 .next_back()
1298 .copied()
1299 .unwrap_or(ast::TransactionAccessMode::ReadWrite);
1300 let isolation_level = match isolation_level {
1301 ast::TransactionIsolationLevel::ReadUncommitted => {
1302 TransactionIsolationLevel::ReadUncommitted
1303 }
1304 ast::TransactionIsolationLevel::ReadCommitted => {
1305 TransactionIsolationLevel::ReadCommitted
1306 }
1307 ast::TransactionIsolationLevel::RepeatableRead => {
1308 TransactionIsolationLevel::RepeatableRead
1309 }
1310 ast::TransactionIsolationLevel::Serializable => {
1311 TransactionIsolationLevel::Serializable
1312 }
1313 ast::TransactionIsolationLevel::Snapshot => {
1314 TransactionIsolationLevel::Snapshot
1315 }
1316 };
1317 let access_mode = match access_mode {
1318 ast::TransactionAccessMode::ReadOnly => {
1319 TransactionAccessMode::ReadOnly
1320 }
1321 ast::TransactionAccessMode::ReadWrite => {
1322 TransactionAccessMode::ReadWrite
1323 }
1324 };
1325 let statement = PlanStatement::TransactionStart(TransactionStart {
1326 access_mode,
1327 isolation_level,
1328 });
1329 Ok(LogicalPlan::Statement(statement))
1330 }
1331 Statement::Commit {
1332 chain,
1333 end,
1334 modifier,
1335 } => {
1336 if end {
1337 return not_impl_err!("COMMIT AND END not supported");
1338 }
1339 if let Some(modifier) = modifier {
1340 return not_impl_err!("COMMIT {modifier} not supported");
1341 }
1342 let statement = PlanStatement::TransactionEnd(TransactionEnd {
1343 conclusion: TransactionConclusion::Commit,
1344 chain,
1345 });
1346 Ok(LogicalPlan::Statement(statement))
1347 }
1348 Statement::Rollback { chain, savepoint } => {
1349 if savepoint.is_some() {
1350 plan_err!("Savepoints not supported")?;
1351 }
1352 let statement = PlanStatement::TransactionEnd(TransactionEnd {
1353 conclusion: TransactionConclusion::Rollback,
1354 chain,
1355 });
1356 Ok(LogicalPlan::Statement(statement))
1357 }
1358 Statement::CreateFunction(ast::CreateFunction {
1359 or_replace,
1360 temporary,
1361 name,
1362 args,
1363 return_type,
1364 function_body,
1365 behavior,
1366 language,
1367 ..
1368 }) => {
1369 let return_type = match return_type {
1370 Some(ast::FunctionReturnType::DataType(t)) => {
1371 Some(self.convert_data_type_to_field(&t)?)
1372 }
1373 Some(ast::FunctionReturnType::SetOf(_)) => {
1374 return not_impl_err!(
1375 "RETURNS SETOF in CREATE FUNCTION is not supported"
1376 );
1377 }
1378 None => None,
1379 };
1380 let mut planner_context = PlannerContext::new();
1381 let empty_schema = &DFSchema::empty();
1382
1383 let args = match args {
1384 Some(function_args) => {
1385 let function_args = function_args
1386 .into_iter()
1387 .map(|arg| {
1388 let data_type =
1389 self.convert_data_type_to_field(&arg.data_type)?;
1390
1391 let default_expr = match arg.default_expr {
1392 Some(expr) => Some(self.sql_to_expr(
1393 expr,
1394 empty_schema,
1395 &mut planner_context,
1396 )?),
1397 None => None,
1398 };
1399 Ok(OperateFunctionArg {
1400 name: arg.name,
1401 default_expr,
1402 data_type: data_type.data_type().clone(),
1403 })
1404 })
1405 .collect::<Result<Vec<OperateFunctionArg>>>();
1406 Some(function_args?)
1407 }
1408 None => None,
1409 };
1410 let first_default = args
1412 .as_ref()
1413 .and_then(|arg| arg.iter().position(|t| t.default_expr.is_some()));
1414 let last_non_default = args
1415 .as_ref()
1416 .and_then(|arg| arg.iter().rposition(|t| t.default_expr.is_none()));
1417 if let (Some(pos_default), Some(pos_non_default)) =
1418 (first_default, last_non_default)
1419 && pos_non_default > pos_default
1420 {
1421 return plan_err!(
1422 "Non-default arguments cannot follow default arguments."
1423 );
1424 }
1425 let name = match &name.0[..] {
1427 [] => exec_err!("Function should have name")?,
1428 [n] => n.as_ident().unwrap().value.clone(),
1429 [..] => not_impl_err!("Qualified functions are not supported")?,
1430 };
1431 let arg_types = args.as_ref().map(|arg| {
1435 arg.iter()
1436 .map(|t| {
1437 let name = match t.name.clone() {
1438 Some(name) => name.value,
1439 None => "".to_string(),
1440 };
1441 Arc::new(Field::new(name, t.data_type.clone(), true))
1442 })
1443 .collect::<Vec<_>>()
1444 });
1445 if let Some(ref fields) = arg_types {
1447 let count_positional =
1448 fields.iter().filter(|f| f.name() == "").count();
1449 if !(count_positional == 0 || count_positional == fields.len()) {
1450 return plan_err!(
1451 "All function arguments must use either named or positional style."
1452 );
1453 }
1454 }
1455 let mut planner_context = PlannerContext::new()
1456 .with_prepare_param_data_types(
1457 arg_types
1458 .unwrap_or_default()
1459 .into_iter()
1460 .map(Some)
1461 .collect(),
1462 );
1463
1464 let function_body = match function_body {
1465 Some(r) => Some(self.sql_to_expr(
1466 match r {
1467 ast::CreateFunctionBody::AsBeforeOptions{body: expr, link_symbol: _link_symbol} => expr,
1469 ast::CreateFunctionBody::AsAfterOptions(expr) => expr,
1470 ast::CreateFunctionBody::Return(expr) => expr,
1471 ast::CreateFunctionBody::AsBeginEnd(_) => {
1472 return not_impl_err!(
1473 "BEGIN/END enclosed function body syntax is not supported"
1474 )?;
1475 }
1476 ast::CreateFunctionBody::AsReturnExpr(_)
1477 | ast::CreateFunctionBody::AsReturnSelect(_) => {
1478 return not_impl_err!(
1479 "AS RETURN function syntax is not supported"
1480 )?
1481 }
1482 },
1483 &DFSchema::empty(),
1484 &mut planner_context,
1485 )?),
1486 None => None,
1487 };
1488
1489 let params = CreateFunctionBody {
1490 language,
1491 behavior: behavior.map(|b| match b {
1492 ast::FunctionBehavior::Immutable => Volatility::Immutable,
1493 ast::FunctionBehavior::Stable => Volatility::Stable,
1494 ast::FunctionBehavior::Volatile => Volatility::Volatile,
1495 }),
1496 function_body,
1497 };
1498
1499 let statement =
1500 DdlStatement::CreateFunction(Box::new(CreateFunction::try_new(
1501 or_replace,
1502 temporary,
1503 name,
1504 args,
1505 return_type.map(|f| f.data_type().clone()),
1506 params,
1507 )?));
1508
1509 Ok(LogicalPlan::Ddl(statement))
1510 }
1511 Statement::DropFunction(ast::DropFunction {
1512 if_exists,
1513 func_desc,
1514 drop_behavior: _,
1515 }) => {
1516 if let Some(desc) = func_desc.first() {
1519 let name = match &desc.name.0[..] {
1521 [] => exec_err!("Function should have name")?,
1522 [n] => n.as_ident().unwrap().value.clone(),
1523 [..] => not_impl_err!("Qualified functions are not supported")?,
1524 };
1525 let statement = DdlStatement::DropFunction(DropFunction {
1526 if_exists,
1527 name,
1528 schema: DFSchemaRef::new(DFSchema::empty()),
1529 });
1530 Ok(LogicalPlan::Ddl(statement))
1531 } else {
1532 exec_err!("Function name not provided")
1533 }
1534 }
1535 Statement::Truncate(ast::Truncate {
1536 table_names,
1537 partitions,
1538 identity,
1539 cascade,
1540 on_cluster,
1541 table,
1542 if_exists,
1543 }) => {
1544 let _ = table; if table_names.len() != 1 {
1546 return not_impl_err!(
1547 "TRUNCATE with multiple tables is not supported"
1548 );
1549 }
1550
1551 let target = &table_names[0];
1552 if target.only {
1553 return not_impl_err!("TRUNCATE with ONLY is not supported");
1554 }
1555 if partitions.is_some() {
1556 return not_impl_err!("TRUNCATE with PARTITION is not supported");
1557 }
1558 if identity.is_some() {
1559 return not_impl_err!(
1560 "TRUNCATE with RESTART/CONTINUE IDENTITY is not supported"
1561 );
1562 }
1563 if cascade.is_some() {
1564 return not_impl_err!(
1565 "TRUNCATE with CASCADE/RESTRICT is not supported"
1566 );
1567 }
1568 if on_cluster.is_some() {
1569 return not_impl_err!("TRUNCATE with ON CLUSTER is not supported");
1570 }
1571 if if_exists {
1572 return not_impl_err!("TRUNCATE .. with IF EXISTS is not supported");
1573 }
1574 let table = self.object_name_to_table_reference(target.name.clone())?;
1575 let source = self.context_provider.get_table_source(table.clone())?;
1576
1577 Ok(LogicalPlan::Dml(DmlStatement::new(
1580 table.clone(),
1581 source,
1582 WriteOp::Truncate,
1583 Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
1584 produce_one_row: false,
1585 schema: DFSchemaRef::new(DFSchema::empty()),
1586 })),
1587 )))
1588 }
1589 Statement::CreateIndex(CreateIndex {
1590 name,
1591 table_name,
1592 using,
1593 columns,
1594 unique,
1595 if_not_exists,
1596 ..
1597 }) => {
1598 let name: Option<String> = name.as_ref().map(object_name_to_string);
1599 let table = self.object_name_to_table_reference(table_name)?;
1600 let table_schema = self
1601 .context_provider
1602 .get_table_source(table.clone())?
1603 .schema()
1604 .to_dfschema_ref()?;
1605 let using: Option<String> =
1606 using.as_ref().map(|index_type| match index_type {
1607 IndexType::Custom(ident) => ident_to_string(ident),
1608 _ => index_type.to_string().to_ascii_lowercase(),
1609 });
1610 let order_by_exprs: Vec<OrderByExpr> =
1611 columns.into_iter().map(|col| col.column).collect();
1612 let columns = self.order_by_to_sort_expr(
1613 order_by_exprs,
1614 &table_schema,
1615 planner_context,
1616 false,
1617 None,
1618 )?;
1619 Ok(LogicalPlan::Ddl(DdlStatement::CreateIndex(
1620 PlanCreateIndex {
1621 name,
1622 table,
1623 using,
1624 columns,
1625 unique,
1626 if_not_exists,
1627 schema: DFSchemaRef::new(DFSchema::empty()),
1628 },
1629 )))
1630 }
1631 stmt => {
1632 not_impl_err!("Unsupported SQL statement: {stmt}")
1633 }
1634 }
1635 }
1636
1637 fn get_delete_target(&self, from: FromTable) -> Result<ObjectName> {
1638 let mut from = match from {
1639 FromTable::WithFromKeyword(v) => v,
1640 FromTable::WithoutKeyword(v) => v,
1641 };
1642
1643 if from.len() != 1 {
1644 return not_impl_err!(
1645 "DELETE FROM only supports single table, got {}: {from:?}",
1646 from.len()
1647 );
1648 }
1649 let table_factor = from.pop().unwrap();
1650 if !table_factor.joins.is_empty() {
1651 return not_impl_err!("DELETE FROM only supports single table, got: joins");
1652 }
1653 let TableFactor::Table { name, .. } = table_factor.relation else {
1654 return not_impl_err!(
1655 "DELETE FROM only supports single table, got: {table_factor:?}"
1656 );
1657 };
1658
1659 Ok(name)
1660 }
1661
1662 fn show_tables_to_plan(&self) -> Result<LogicalPlan> {
1664 LogicalPlanBuilder::show_tables()?.build()
1665 }
1666
1667 fn describe_table_to_plan(&self, table_name: ObjectName) -> Result<LogicalPlan> {
1668 let table_ref = self.object_name_to_table_reference(table_name)?;
1669 let _ = self.context_provider.get_table_source(table_ref.clone())?;
1671
1672 LogicalPlanBuilder::show_columns(table_ref, ColumnsDetail::Describe)?.build()
1673 }
1674
1675 fn describe_query_to_plan(&self, query: Query) -> Result<LogicalPlan> {
1676 let plan = self.query_to_plan(query, &mut PlannerContext::new())?;
1677
1678 let schema = Arc::new(plan.schema().as_arrow().clone());
1679
1680 LogicalPlanBuilder::describe(schema)?.build()
1681 }
1682
1683 fn copy_to_plan(&self, statement: CopyToStatement) -> Result<LogicalPlan> {
1684 let copy_source = statement.source;
1686 let (input, input_schema, table_ref) = match copy_source {
1687 CopyToSource::Relation(object_name) => {
1688 let table_name = object_name_to_string(&object_name);
1689 let table_ref = self.object_name_to_table_reference(object_name)?;
1690 let table_source =
1691 self.context_provider.get_table_source(table_ref.clone())?;
1692 let plan =
1693 LogicalPlanBuilder::scan(table_name, table_source, None)?.build()?;
1694 let input_schema = Arc::clone(plan.schema());
1695 (plan, input_schema, Some(table_ref))
1696 }
1697 CopyToSource::Query(query) => {
1698 let plan = self.query_to_plan(*query, &mut PlannerContext::new())?;
1699 let input_schema = Arc::clone(plan.schema());
1700 (plan, input_schema, None)
1701 }
1702 };
1703
1704 let options_map = self.parse_options_map(statement.options, true)?;
1705
1706 let maybe_file_type = if let Some(stored_as) = &statement.stored_as {
1707 self.context_provider.get_file_type(stored_as).ok()
1708 } else {
1709 None
1710 };
1711
1712 let file_type = match maybe_file_type {
1713 Some(ft) => ft,
1714 None => {
1715 let e = || {
1716 DataFusionError::Configuration(
1717 "Format not explicitly set and unable to get file extension! Use STORED AS to define file format."
1718 .to_string(),
1719 )
1720 };
1721 let extension: &str = &Path::new(&statement.target)
1723 .extension()
1724 .ok_or_else(e)?
1725 .to_str()
1726 .ok_or_else(e)?
1727 .to_lowercase();
1728
1729 self.context_provider.get_file_type(extension)?
1730 }
1731 };
1732
1733 let partition_by = statement
1734 .partitioned_by
1735 .iter()
1736 .map(|col| input_schema.field_with_name(table_ref.as_ref(), col))
1737 .collect::<Result<Vec<_>>>()?
1738 .into_iter()
1739 .map(|f| f.name().to_owned())
1740 .collect();
1741
1742 Ok(LogicalPlan::Copy(CopyTo::new(
1743 Arc::new(input),
1744 statement.target,
1745 partition_by,
1746 file_type,
1747 options_map,
1748 )))
1749 }
1750
1751 fn build_order_by(
1752 &self,
1753 order_exprs: Vec<LexOrdering>,
1754 schema: &DFSchemaRef,
1755 planner_context: &mut PlannerContext,
1756 ) -> Result<Vec<Vec<SortExpr>>> {
1757 if !order_exprs.is_empty() && schema.fields().is_empty() {
1758 let results = order_exprs
1759 .iter()
1760 .map(|lex_order| {
1761 let result = lex_order
1762 .iter()
1763 .map(|order_by_expr| {
1764 let ordered_expr = &order_by_expr.expr;
1765 let ordered_expr = ordered_expr.to_owned();
1766 let ordered_expr = self.sql_expr_to_logical_expr(
1767 ordered_expr,
1768 schema,
1769 planner_context,
1770 )?;
1771 let asc = match &order_by_expr.options.sort {
1772 Some(ast::OrderBySort::Asc) | None => true,
1773 Some(ast::OrderBySort::Desc) => false,
1774 Some(ast::OrderBySort::Using(op)) => {
1775 return not_impl_err!(
1776 "ORDER BY USING is not supported: {op}"
1777 );
1778 }
1779 };
1780 let nulls_first =
1781 order_by_expr.options.nulls_first.unwrap_or_else(|| {
1782 self.options.default_null_ordering.nulls_first(asc)
1783 });
1784
1785 Ok(SortExpr::new(ordered_expr, asc, nulls_first))
1786 })
1787 .collect::<Result<Vec<SortExpr>>>()?;
1788 Ok(result)
1789 })
1790 .collect::<Result<Vec<Vec<SortExpr>>>>()?;
1791
1792 return Ok(results);
1793 }
1794
1795 let mut all_results = Vec::with_capacity(order_exprs.len());
1796 for expr in order_exprs {
1797 let expr_vec =
1799 self.order_by_to_sort_expr(expr, schema, planner_context, true, None)?;
1800 for sort in expr_vec.iter() {
1802 for column in sort.expr.column_refs().iter() {
1803 if !schema.has_column(column) {
1804 return plan_err!("Column {column} is not in schema");
1806 }
1807 }
1808 }
1809 all_results.push(expr_vec)
1811 }
1812 Ok(all_results)
1813 }
1814
1815 fn external_table_to_plan(
1817 &self,
1818 statement: CreateExternalTable,
1819 ) -> Result<LogicalPlan> {
1820 let definition = Some(statement.to_string());
1821 let CreateExternalTable {
1822 name,
1823 columns,
1824 file_type,
1825 locations,
1826 table_partition_cols,
1827 if_not_exists,
1828 temporary,
1829 order_exprs,
1830 unbounded,
1831 options,
1832 constraints,
1833 or_replace,
1834 } = statement;
1835
1836 let mut all_constraints = constraints;
1838 let inline_constraints = calc_inline_constraints_from_columns(&columns);
1839 all_constraints.extend(inline_constraints);
1840
1841 let options_map = self.parse_options_map(options, false)?;
1842
1843 let compression = options_map
1844 .get("format.compression")
1845 .map(|c| CompressionTypeVariant::from_str(c))
1846 .transpose()?;
1847 if (file_type == "PARQUET" || file_type == "AVRO" || file_type == "ARROW")
1848 && compression
1849 .map(|c| c != CompressionTypeVariant::UNCOMPRESSED)
1850 .unwrap_or(false)
1851 {
1852 plan_err!(
1853 "File compression type cannot be set for PARQUET, AVRO, or ARROW files."
1854 )?;
1855 }
1856
1857 let mut planner_context = PlannerContext::new();
1858
1859 let column_defaults = self
1860 .build_column_defaults(&columns, &mut planner_context)?
1861 .into_iter()
1862 .collect();
1863
1864 let schema = self.build_schema(columns)?;
1865 let df_schema = schema.to_dfschema_ref()?;
1866 df_schema.check_names()?;
1867
1868 let ordered_exprs =
1869 self.build_order_by(order_exprs, &df_schema, &mut planner_context)?;
1870
1871 let name = self.object_name_to_table_reference(name)?;
1872 let constraints =
1873 self.new_constraint_from_table_constraints(&all_constraints, &df_schema)?;
1874
1875 let Some(location) = locations.first().cloned() else {
1876 return plan_err!("CREATE EXTERNAL TABLE requires at least one location");
1877 };
1878
1879 Ok(LogicalPlan::Ddl(DdlStatement::CreateExternalTable(
1882 Box::new(
1883 PlanCreateExternalTable::builder(name, location, file_type, df_schema)
1884 .with_locations(locations)
1885 .with_partition_cols(table_partition_cols)
1886 .with_if_not_exists(if_not_exists)
1887 .with_or_replace(or_replace)
1888 .with_temporary(temporary)
1889 .with_definition(definition)
1890 .with_order_exprs(ordered_exprs)
1891 .with_unbounded(unbounded)
1892 .with_options(options_map)
1893 .with_constraints(constraints)
1894 .with_column_defaults(column_defaults)
1895 .build(),
1896 ),
1897 )))
1898 }
1899
1900 fn external_catalog_to_plan(
1901 &self,
1902 statement: CreateExternalCatalog,
1903 ) -> Result<LogicalPlan> {
1904 let CreateExternalCatalog {
1905 catalog_name,
1906 catalog_type,
1907 location,
1908 if_not_exists,
1909 or_replace,
1910 options,
1911 } = statement;
1912
1913 let mut options_map = HashMap::with_capacity(options.len());
1914 for (key, value) in options {
1915 if options_map.contains_key(&key) {
1916 return plan_err!("Option {key} is specified multiple times");
1917 }
1918 let Some(value_string) = crate::utils::value_to_string(&value) else {
1919 return plan_err!("Unsupported Value {}", value);
1920 };
1921 options_map.insert(key, value_string);
1922 }
1923
1924 Ok(LogicalPlan::Ddl(DdlStatement::CreateExternalCatalog(
1925 Box::new(
1926 PlanCreateExternalCatalog::builder(
1927 object_name_to_string(&catalog_name),
1928 catalog_type,
1929 )
1930 .with_location(location)
1931 .with_if_not_exists(if_not_exists)
1932 .with_or_replace(or_replace)
1933 .with_options(options_map)
1934 .build(),
1935 ),
1936 )))
1937 }
1938
1939 fn get_constraint_column_indices(
1942 &self,
1943 df_schema: &DFSchemaRef,
1944 columns: &[IndexColumn],
1945 constraint_name: &str,
1946 ) -> Result<Vec<usize>> {
1947 let field_names = df_schema.field_names();
1948 columns
1949 .iter()
1950 .map(|index_column| {
1951 let expr = &index_column.column.expr;
1952 let SQLExpr::Identifier(ident) = expr else {
1953 return Err(plan_datafusion_err!(
1954 "Column name for {constraint_name} must be an identifier: {expr}"
1955 ));
1956 };
1957 let column = self.ident_normalizer.normalize(ident.clone());
1958 field_names
1959 .iter()
1960 .position(|item| *item == column)
1961 .ok_or_else(|| {
1962 plan_datafusion_err!(
1963 "Column for {constraint_name} not found in schema: {column}"
1964 )
1965 })
1966 })
1967 .collect::<Result<Vec<_>>>()
1968 }
1969
1970 pub fn new_constraint_from_table_constraints(
1972 &self,
1973 constraints: &[TableConstraint],
1974 df_schema: &DFSchemaRef,
1975 ) -> Result<Constraints> {
1976 let constraints = constraints
1977 .iter()
1978 .map(|c: &TableConstraint| match c {
1979 TableConstraint::Unique(UniqueConstraint {
1980 name,
1981 index_name: _,
1982 index_type_display: _,
1983 index_type: _,
1984 columns,
1985 include: _,
1986 index_options: _,
1987 characteristics: _,
1988 nulls_distinct: _,
1989 }) => {
1990 let constraint_name = match &name {
1991 Some(name) => &format!("unique constraint with name '{name}'"),
1992 None => "unique constraint",
1993 };
1994 let indices = self.get_constraint_column_indices(
1996 df_schema,
1997 columns,
1998 constraint_name,
1999 )?;
2000 Ok(Constraint::Unique(indices))
2001 }
2002 TableConstraint::PrimaryKey(PrimaryKeyConstraint {
2003 name: _,
2004 index_name: _,
2005 index_type: _,
2006 columns,
2007 include: _,
2008 index_options: _,
2009 characteristics: _,
2010 }) => {
2011 let indices = self.get_constraint_column_indices(
2013 df_schema,
2014 columns,
2015 "primary key",
2016 )?;
2017 Ok(Constraint::PrimaryKey(indices))
2018 }
2019 TableConstraint::ForeignKey { .. } => {
2020 _plan_err!("Foreign key constraints are not currently supported")
2021 }
2022 TableConstraint::Exclude(_) => {
2023 _plan_err!("Exclude constraints are not currently supported")
2024 }
2025 TableConstraint::Check { .. } => {
2026 _plan_err!("Check constraints are not currently supported")
2027 }
2028 TableConstraint::Index { .. } => {
2029 _plan_err!("Indexes are not currently supported")
2030 }
2031 TableConstraint::FulltextOrSpatial { .. } => {
2032 _plan_err!("Indexes are not currently supported")
2033 }
2034 TableConstraint::PrimaryKeyUsingIndex(_) => {
2035 _plan_err!(
2036 "PRIMARY KEY USING INDEX constraints are not currently supported"
2037 )
2038 }
2039 TableConstraint::UniqueUsingIndex(_) => {
2040 _plan_err!(
2041 "UNIQUE USING INDEX constraints are not currently supported"
2042 )
2043 }
2044 })
2045 .collect::<Result<Vec<_>>>()?;
2046 Ok(Constraints::new_unverified(constraints))
2047 }
2048
2049 fn parse_options_map(
2050 &self,
2051 options: Vec<(String, Value)>,
2052 allow_duplicates: bool,
2053 ) -> Result<HashMap<String, String>> {
2054 let mut options_map = HashMap::with_capacity(options.len());
2055 for (key, value) in options {
2056 if !allow_duplicates && options_map.contains_key(&key) {
2057 return plan_err!("Option {key} is specified multiple times");
2058 }
2059
2060 let Some(value_string) = crate::utils::value_to_string(&value) else {
2061 return plan_err!("Unsupported Value {}", value);
2062 };
2063
2064 if !(&key.contains('.')) {
2065 let renamed_key = format!("format.{key}");
2069 options_map.insert(renamed_key.to_lowercase(), value_string);
2070 } else {
2071 options_map.insert(key.to_lowercase(), value_string);
2072 }
2073 }
2074
2075 Ok(options_map)
2076 }
2077
2078 fn explain_to_plan(
2083 &self,
2084 opts: ExplainStatementOptions,
2085 statement: DFStatement,
2086 ) -> Result<LogicalPlan> {
2087 let plan = self.statement_to_plan(statement)?;
2088 if matches!(plan, LogicalPlan::Explain(_)) {
2089 return plan_err!("Nested EXPLAINs are not supported");
2090 }
2091
2092 let plan = Arc::new(plan);
2093 let schema = LogicalPlan::explain_schema();
2094 let schema = schema.to_dfschema_ref()?;
2095
2096 let ExplainStatementOptions {
2097 analyze,
2098 verbose,
2099 format,
2100 analyze_level,
2101 analyze_categories,
2102 show_statistics,
2103 } = opts;
2104
2105 if verbose && format.is_some() {
2107 return plan_err!("EXPLAIN VERBOSE with FORMAT is not supported");
2108 }
2109 if !analyze {
2110 if analyze_level.is_some() {
2111 return plan_err!("EXPLAIN option LEVEL requires ANALYZE");
2112 }
2113 if analyze_categories.is_some() {
2114 return plan_err!("EXPLAIN option METRICS requires ANALYZE");
2115 }
2116 }
2117 if analyze && show_statistics.is_some() {
2118 return plan_err!("EXPLAIN option COSTS cannot be combined with ANALYZE");
2119 }
2120
2121 let options = self.context_provider.options();
2127 let format = if verbose {
2128 ExplainFormat::Indent
2129 } else if let Some(format) = format {
2130 format
2131 } else if analyze {
2132 ExplainFormat::Indent
2133 } else {
2134 options.explain.format.clone()
2135 };
2136
2137 if analyze {
2138 match &format {
2139 ExplainFormat::Indent => {}
2140 ExplainFormat::PostgresJSON => {
2141 if options.explain.show_statistics {
2144 return plan_err!(
2145 "EXPLAIN ANALYZE with FORMAT pgjson does not support show_statistics"
2146 );
2147 }
2148 }
2149 ExplainFormat::Tree | ExplainFormat::Graphviz => {
2150 return plan_err!(
2151 "EXPLAIN ANALYZE with FORMAT {format} is not supported"
2152 );
2153 }
2154 }
2155 Ok(LogicalPlan::Analyze(Analyze {
2156 verbose,
2157 format,
2158 input: plan,
2159 schema,
2160 analyze_level,
2161 analyze_categories,
2162 }))
2163 } else {
2164 let stringified_plans =
2165 vec![plan.to_stringified(PlanType::InitialLogicalPlan)];
2166
2167 Ok(LogicalPlan::Explain(Explain {
2168 verbose,
2169 explain_format: format,
2170 plan,
2171 stringified_plans,
2172 schema,
2173 logical_optimization_succeeded: false,
2174 show_statistics,
2175 }))
2176 }
2177 }
2178
2179 fn show_variable_to_plan(&self, variable: &[Ident]) -> Result<LogicalPlan> {
2180 let verbose = variable
2181 .last()
2182 .map(|s| ident_to_string(s) == "verbose")
2183 .unwrap_or(false);
2184 let mut variable_vec = variable.to_vec();
2185
2186 if verbose {
2187 variable_vec = variable_vec.split_at(variable_vec.len() - 1).0.to_vec();
2188 }
2189
2190 let variable = object_name_to_string(&ObjectName::from(variable_vec));
2191 let name = if variable == "all" {
2192 None
2193 } else {
2194 Some(variable)
2196 };
2197
2198 LogicalPlanBuilder::show_variables(name, verbose)?.build()
2199 }
2200
2201 fn set_statement_to_plan(&self, statement: Set) -> Result<LogicalPlan> {
2202 match statement {
2203 Set::SingleAssignment {
2204 scope,
2205 hivevar,
2206 variable,
2207 values,
2208 } => {
2209 if scope.is_some() {
2210 return not_impl_err!("SET with scope modifiers is not supported");
2211 }
2212
2213 if hivevar {
2214 return not_impl_err!("SET HIVEVAR is not supported");
2215 }
2216
2217 let variable = object_name_to_string(&variable);
2218 let mut variable_lower = variable.to_lowercase();
2219
2220 if variable_lower == "timezone" || variable_lower == "time.zone" {
2222 variable_lower = "datafusion.execution.time_zone".to_string();
2223 }
2224
2225 if values.len() != 1 {
2226 return plan_err!("SET only supports single value assignment");
2227 }
2228
2229 let value_string = match &values[0] {
2230 SQLExpr::Identifier(i) => ident_to_string(i),
2231 SQLExpr::Value(v) => match crate::utils::value_to_string(&v.value) {
2232 None => {
2233 return plan_err!("Unsupported value {:?}", v.value);
2234 }
2235 Some(s) => s,
2236 },
2237 SQLExpr::UnaryOp { op, expr } => match op {
2238 UnaryOperator::Plus => format!("+{expr}"),
2239 UnaryOperator::Minus => format!("-{expr}"),
2240 _ => return plan_err!("Unsupported unary op {:?}", op),
2241 },
2242 _ => return plan_err!("Unsupported expr {:?}", values[0]),
2243 };
2244
2245 Ok(LogicalPlan::Statement(PlanStatement::SetVariable(
2246 SetVariable {
2247 variable: variable_lower,
2248 value: value_string,
2249 },
2250 )))
2251 }
2252 other => not_impl_err!("SET variant not implemented yet: {other:?}"),
2253 }
2254 }
2255
2256 fn reset_statement_to_plan(&self, statement: ResetStatement) -> Result<LogicalPlan> {
2257 match statement {
2258 ResetStatement::Variable(variable) => {
2259 let variable = object_name_to_string(&variable);
2260 let mut variable_lower = variable.to_lowercase();
2261
2262 if variable_lower == "timezone" || variable_lower == "time.zone" {
2264 variable_lower = "datafusion.execution.time_zone".to_string();
2265 }
2266
2267 Ok(LogicalPlan::Statement(PlanStatement::ResetVariable(
2268 ResetVariable {
2269 variable: variable_lower,
2270 },
2271 )))
2272 }
2273 }
2274 }
2275
2276 fn delete_to_plan(
2277 &self,
2278 table_name: &ObjectName,
2279 predicate_expr: Option<SQLExpr>,
2280 ) -> Result<LogicalPlan> {
2281 let table_ref = self.object_name_to_table_reference(table_name.clone())?;
2283 let table_source = self.context_provider.get_table_source(table_ref.clone())?;
2284 let schema = DFSchema::try_from_qualified_schema(
2285 table_ref.clone(),
2286 &table_source.schema(),
2287 )?;
2288 let scan =
2289 LogicalPlanBuilder::scan(table_ref.clone(), Arc::clone(&table_source), None)?
2290 .build()?;
2291 let mut planner_context = PlannerContext::new();
2292
2293 let source = match predicate_expr {
2294 None => scan,
2295 Some(predicate_expr) => {
2296 let filter_expr =
2297 self.sql_to_expr(predicate_expr, &schema, &mut planner_context)?;
2298 let schema = Arc::new(schema);
2299 let mut using_columns = HashSet::new();
2300 expr_to_columns(&filter_expr, &mut using_columns)?;
2301 let filter_expr = normalize_col_with_schemas_and_ambiguity_check(
2302 filter_expr,
2303 &[&[&schema]],
2304 &[using_columns],
2305 )?;
2306 LogicalPlan::Filter(Filter::try_new(filter_expr, Arc::new(scan))?)
2307 }
2308 };
2309
2310 let plan = LogicalPlan::Dml(DmlStatement::new(
2311 table_ref,
2312 table_source,
2313 WriteOp::Delete,
2314 Arc::new(source),
2315 ));
2316 Ok(plan)
2317 }
2318
2319 fn update_to_plan(
2320 &self,
2321 table: TableWithJoins,
2322 assignments: &[Assignment],
2323 from: Option<TableWithJoins>,
2324 predicate_expr: Option<SQLExpr>,
2325 ) -> Result<LogicalPlan> {
2326 let (table_name, table_alias) = match &table.relation {
2327 TableFactor::Table { name, alias, .. } => (name.clone(), alias.clone()),
2328 _ => plan_err!("Cannot update non-table relation!")?,
2329 };
2330
2331 let table_name = self.object_name_to_table_reference(table_name)?;
2333 let table_source = self.context_provider.get_table_source(table_name.clone())?;
2334 let table_schema = Arc::new(DFSchema::try_from_qualified_schema(
2335 table_name.clone(),
2336 &table_source.schema(),
2337 )?);
2338
2339 let mut planner_context = PlannerContext::new();
2341 let mut assign_map = assignments
2342 .iter()
2343 .map(|assign| {
2344 let cols = match &assign.target {
2345 AssignmentTarget::ColumnName(cols) => cols,
2346 _ => plan_err!("Tuples are not supported")?,
2347 };
2348 let col_name: &Ident = cols
2349 .0
2350 .last()
2351 .ok_or_else(|| plan_datafusion_err!("Empty column id"))?
2352 .as_ident()
2353 .unwrap();
2354 table_schema.field_with_unqualified_name(&col_name.value)?;
2356 Ok((col_name.value.clone(), assign.value.clone()))
2357 })
2358 .collect::<Result<HashMap<String, SQLExpr>>>()?;
2359
2360 let mut input_tables = vec![table];
2362 input_tables.extend(from);
2363 let scan = self.plan_from_tables(input_tables, &mut planner_context)?;
2364
2365 let source = match predicate_expr {
2367 None => scan,
2368 Some(predicate_expr) => {
2369 let filter_expr = self.sql_to_expr(
2370 predicate_expr,
2371 scan.schema(),
2372 &mut planner_context,
2373 )?;
2374 let mut using_columns = HashSet::new();
2375 expr_to_columns(&filter_expr, &mut using_columns)?;
2376 let filter_expr = normalize_col_with_schemas_and_ambiguity_check(
2377 filter_expr,
2378 &[&[scan.schema()]],
2379 &[using_columns],
2380 )?;
2381 LogicalPlan::Filter(Filter::try_new(filter_expr, Arc::new(scan))?)
2382 }
2383 };
2384
2385 let exprs = table_schema
2387 .iter()
2388 .map(|(qualifier, field)| {
2389 let expr = match assign_map.remove(field.name()) {
2390 Some(new_value) => {
2391 let mut expr = self.sql_to_expr(
2392 new_value,
2393 source.schema(),
2394 &mut planner_context,
2395 )?;
2396 if let Expr::Placeholder(placeholder) = &mut expr {
2398 placeholder.field = placeholder
2399 .field
2400 .take()
2401 .or_else(|| Some(Arc::clone(field)));
2402 }
2403 expr.cast_to(field.data_type(), source.schema())?
2405 }
2406 None => {
2407 if let Some(alias) = &table_alias {
2409 Expr::Column(Column::new(
2410 Some(self.ident_normalizer.normalize(alias.name.clone())),
2411 field.name(),
2412 ))
2413 } else {
2414 Expr::Column(Column::from((qualifier, field)))
2415 }
2416 }
2417 };
2418 Ok(expr.alias(field.name()))
2419 })
2420 .collect::<Result<Vec<_>>>()?;
2421
2422 let source = project(source, exprs)?;
2423
2424 let plan = LogicalPlan::Dml(DmlStatement::new(
2425 table_name,
2426 table_source,
2427 WriteOp::Update,
2428 Arc::new(source),
2429 ));
2430 Ok(plan)
2431 }
2432
2433 fn merge_to_plan(&self, merge: ast::Merge) -> Result<LogicalPlan> {
2434 let ast::Merge {
2435 table,
2436 source,
2437 on,
2438 clauses,
2439 into: _,
2440 merge_token: _,
2441 optimizer_hints,
2442 output,
2443 } = merge;
2444
2445 if !optimizer_hints.is_empty() {
2446 plan_err!("Optimizer hints not supported")?;
2447 }
2448
2449 if output.is_some() {
2450 return not_impl_err!("MERGE OUTPUT clause is not supported");
2451 }
2452
2453 if clauses.is_empty() {
2454 return plan_err!("MERGE INTO requires at least one WHEN clause");
2455 }
2456
2457 let (target_table_name, target_alias) = match table {
2459 TableFactor::Table {
2460 name,
2461 alias,
2462 args,
2463 with_hints,
2464 version,
2465 with_ordinality,
2466 partitions,
2467 json_path,
2468 sample,
2469 index_hints,
2470 } => {
2471 if alias
2472 .as_ref()
2473 .is_some_and(|alias| !alias.columns.is_empty())
2474 {
2475 return not_impl_err!(
2476 "MERGE target alias column lists are not supported"
2477 );
2478 }
2479 if args.is_some()
2480 || !with_hints.is_empty()
2481 || version.is_some()
2482 || with_ordinality
2483 || !partitions.is_empty()
2484 || json_path.is_some()
2485 || sample.is_some()
2486 || !index_hints.is_empty()
2487 {
2488 return not_impl_err!(
2489 "MERGE target table modifiers are not supported"
2490 );
2491 }
2492 (name, alias)
2493 }
2494 _ => plan_err!("Cannot MERGE INTO non-table relation!")?,
2495 };
2496 let target_table_ref = self.object_name_to_table_reference(target_table_name)?;
2497 let target_table_source = self
2498 .context_provider
2499 .get_table_source(target_table_ref.clone())?;
2500 let target_qualifier = target_alias
2503 .as_ref()
2504 .map(|a| {
2505 TableReference::bare(self.ident_normalizer.normalize(a.name.clone()))
2506 })
2507 .unwrap_or_else(|| target_table_ref.clone());
2508 let target_schema = Arc::new(DFSchema::try_from_qualified_schema(
2509 target_qualifier.clone(),
2510 &target_table_source.schema(),
2511 )?);
2512
2513 let mut planner_context = PlannerContext::new();
2515 let source_table_with_joins = TableWithJoins {
2516 relation: source,
2517 joins: vec![],
2518 };
2519 let source_plan =
2520 self.plan_from_tables(vec![source_table_with_joins], &mut planner_context)?;
2521
2522 let combined_schema = Arc::new(MergeIntoOp::expression_schema_for(
2524 &target_qualifier,
2525 &target_table_source.schema(),
2526 source_plan.schema(),
2527 )?);
2528
2529 let on_expr = self.sql_to_expr(*on, &combined_schema, &mut planner_context)?;
2531
2532 let df_clauses = clauses
2534 .into_iter()
2535 .map(|clause| {
2536 self.merge_clause_to_plan(
2537 clause,
2538 &combined_schema,
2539 &target_schema,
2540 &target_qualifier,
2541 &mut planner_context,
2542 )
2543 })
2544 .collect::<Result<Vec<_>>>()?;
2545
2546 let merge_op = MergeIntoOp::new(target_qualifier, on_expr, df_clauses);
2550
2551 Ok(LogicalPlan::Dml(DmlStatement::new(
2552 target_table_ref,
2553 target_table_source,
2554 WriteOp::MergeInto(Box::new(merge_op)),
2555 Arc::new(source_plan),
2556 )))
2557 }
2558
2559 fn merge_target_column_name(
2560 &self,
2561 name: &ObjectName,
2562 target_qualifier: &TableReference,
2563 ) -> Result<String> {
2564 let part = name
2565 .0
2566 .last()
2567 .ok_or_else(|| plan_datafusion_err!("Empty column name"))?;
2568 let ident = part
2569 .as_ident()
2570 .cloned()
2571 .ok_or_else(|| plan_datafusion_err!("Expected simple identifier"))?;
2572
2573 if name.0.len() > 1 {
2574 let qualifier = self.object_name_to_table_reference(ObjectName(
2575 name.0[..name.0.len() - 1].to_vec(),
2576 ))?;
2577 if !qualifier.resolved_eq(target_qualifier) {
2578 return plan_err!(
2579 "MERGE assignment target '{name}' must reference target table \
2580 '{target_qualifier}'"
2581 );
2582 }
2583 }
2584
2585 Ok(self.ident_normalizer.normalize(ident))
2586 }
2587
2588 fn merge_clause_to_plan(
2589 &self,
2590 clause: ast::MergeClause,
2591 combined_schema: &DFSchema,
2592 target_schema: &DFSchema,
2593 target_qualifier: &TableReference,
2594 planner_context: &mut PlannerContext,
2595 ) -> Result<MergeIntoClause> {
2596 let kind = match clause.clause_kind {
2597 ast::MergeClauseKind::Matched => MergeIntoClauseKind::Matched,
2598 ast::MergeClauseKind::NotMatched => MergeIntoClauseKind::NotMatched,
2599 ast::MergeClauseKind::NotMatchedByTarget => {
2600 MergeIntoClauseKind::NotMatchedByTarget
2601 }
2602 ast::MergeClauseKind::NotMatchedBySource => {
2603 MergeIntoClauseKind::NotMatchedBySource
2604 }
2605 };
2606
2607 let predicate = clause
2608 .predicate
2609 .map(|p| self.sql_to_expr(p, combined_schema, planner_context))
2610 .transpose()?;
2611
2612 let action = match clause.action {
2613 ast::MergeAction::Update(update_expr) => {
2614 if update_expr.update_predicate.is_some() {
2615 return not_impl_err!(
2616 "MERGE UPDATE WHERE predicates are not supported"
2617 );
2618 }
2619 if update_expr.delete_predicate.is_some() {
2620 return not_impl_err!(
2621 "MERGE UPDATE DELETE WHERE predicates are not supported"
2622 );
2623 }
2624 let sql_assignments = match update_expr.kind {
2625 ast::MergeUpdateKind::Set(assignments) => assignments,
2626 ast::MergeUpdateKind::Wildcard => {
2627 return not_impl_err!("MERGE UPDATE SET * is not supported");
2628 }
2629 };
2630 let assignments = sql_assignments
2631 .into_iter()
2632 .map(|assign| {
2633 let col_name = match &assign.target {
2634 AssignmentTarget::ColumnName(cols) => {
2635 self.merge_target_column_name(cols, target_qualifier)?
2636 }
2637 _ => plan_err!("Tuples are not supported")?,
2638 };
2639 target_schema.field_with_unqualified_name(&col_name)?;
2641 let value = self.sql_to_expr(
2642 assign.value,
2643 combined_schema,
2644 planner_context,
2645 )?;
2646 Ok((col_name, value))
2647 })
2648 .collect::<Result<Vec<_>>>()?;
2649 let mut seen = HashSet::with_capacity(assignments.len());
2650 for (column, _) in &assignments {
2651 if !seen.insert(column.as_str()) {
2652 return plan_err!("Duplicate column '{column}' in MERGE UPDATE");
2653 }
2654 }
2655 MergeIntoAction::Update(assignments)
2656 }
2657 ast::MergeAction::Insert(insert_expr) => {
2658 if insert_expr.insert_predicate.is_some() {
2659 return not_impl_err!(
2660 "MERGE INSERT WHERE predicates are not supported"
2661 );
2662 }
2663 let columns: Vec<String> = insert_expr
2664 .columns
2665 .iter()
2666 .map(|c| self.merge_target_column_name(c, target_qualifier))
2667 .collect::<Result<Vec<_>>>()?;
2668
2669 let mut seen = HashSet::with_capacity(columns.len());
2671 for col in &columns {
2672 if !seen.insert(col.as_str()) {
2673 return plan_err!("Duplicate column '{col}' in MERGE INSERT");
2674 }
2675 target_schema.field_with_unqualified_name(col)?;
2676 }
2677
2678 let num_target_cols = target_schema.fields().len();
2679
2680 let values = match insert_expr.kind {
2681 ast::MergeInsertKind::Values(values) => {
2682 if values.rows.len() != 1 {
2683 return plan_err!(
2684 "MERGE INSERT must have exactly one row of values"
2685 );
2686 }
2687 let row = values.rows.into_iter().next().unwrap().content;
2688 let expected = if columns.is_empty() {
2689 num_target_cols
2690 } else {
2691 columns.len()
2692 };
2693 if row.len() != expected {
2694 return plan_err!(
2695 "MERGE INSERT has {expected} column(s) but {} value(s)",
2696 row.len()
2697 );
2698 }
2699 row.into_iter()
2700 .map(|v| {
2701 self.sql_to_expr(v, combined_schema, planner_context)
2702 })
2703 .collect::<Result<Vec<_>>>()?
2704 }
2705 ast::MergeInsertKind::Row => {
2706 return not_impl_err!("MERGE INSERT ROW is not supported");
2707 }
2708 ast::MergeInsertKind::Wildcard => {
2709 return not_impl_err!("MERGE INSERT * is not supported");
2710 }
2711 };
2712
2713 MergeIntoAction::Insert { columns, values }
2714 }
2715 ast::MergeAction::Delete { .. } => MergeIntoAction::Delete,
2716 ast::MergeAction::DoNothing { .. } => {
2717 return not_impl_err!(
2718 "MERGE WHEN ... THEN DO NOTHING action is not supported"
2719 );
2720 }
2721 };
2722
2723 Ok(MergeIntoClause {
2724 kind,
2725 predicate,
2726 action,
2727 })
2728 }
2729
2730 fn insert_to_plan(
2731 &self,
2732 table_name: ObjectName,
2733 columns: Vec<ObjectName>,
2734 source: Box<Query>,
2735 overwrite: bool,
2736 replace_into: bool,
2737 ) -> Result<LogicalPlan> {
2738 let table_name = self.object_name_to_table_reference(table_name)?;
2740 let table_source = self.context_provider.get_table_source(table_name.clone())?;
2741 let table_schema = DFSchema::try_from(table_source.schema())?;
2742
2743 let columns: Vec<Ident> = columns
2744 .into_iter()
2745 .map(|name| {
2746 if name.0.len() != 1 {
2747 return not_impl_err!(
2748 "Multi-part column names in INSERT not supported: {name}"
2749 );
2750 }
2751 let part = &name.0[0];
2752 let Some(ident) = part.as_ident() else {
2753 return not_impl_err!(
2754 "Non-identifier column name part in INSERT not supported: {part}"
2755 );
2756 };
2757 Ok(ident.clone())
2758 })
2759 .collect::<Result<Vec<_>>>()?;
2760
2761 let (fields, value_indices) = if columns.is_empty() {
2769 (
2771 table_schema.fields().clone(),
2772 (0..table_schema.fields().len())
2773 .map(Some)
2774 .collect::<Vec<_>>(),
2775 )
2776 } else {
2777 let mut value_indices = vec![None; table_schema.fields().len()];
2778 let fields = columns
2779 .into_iter()
2780 .enumerate()
2781 .map(|(i, c)| {
2782 let c = self.ident_normalizer.normalize(c);
2783 let column_index = table_schema
2784 .index_of_column_by_name(None, &c)
2785 .ok_or_else(|| unqualified_field_not_found(&c, &table_schema))?;
2786
2787 if value_indices[column_index].is_some() {
2788 return schema_err!(SchemaError::DuplicateUnqualifiedField {
2789 name: c,
2790 });
2791 } else {
2792 value_indices[column_index] = Some(i);
2793 }
2794 Ok(Arc::clone(table_schema.field(column_index)))
2795 })
2796 .collect::<Result<Vec<_>>>()?;
2797 (Fields::from(fields), value_indices)
2798 };
2799
2800 let mut prepare_param_data_types = BTreeMap::new();
2802 if let SetExpr::Values(ast::Values { rows, .. }) = (*source.body).clone() {
2803 for row in rows.iter() {
2804 for (idx, val) in row.content.iter().enumerate() {
2805 if let SQLExpr::Value(ValueWithSpan {
2806 value: Value::Placeholder(name),
2807 span: _,
2808 }) = val
2809 {
2810 let index = match name[1..].parse::<usize>().map_err(|_| {
2811 plan_datafusion_err!("Can't parse placeholder: {name}")
2812 })? {
2813 0 => {
2814 return plan_err!(
2815 "Invalid placeholder, zero is not a valid index: {name}"
2816 );
2817 }
2818 index => index - 1,
2819 };
2820 let field = fields.get(idx).ok_or_else(|| {
2821 plan_datafusion_err!(
2822 "Placeholder ${} refers to a non existent column",
2823 idx + 1
2824 )
2825 })?;
2826 let _ = prepare_param_data_types.insert(index, Arc::clone(field));
2827 }
2828 }
2829 }
2830 }
2831 let prepare_param_data_types = {
2832 let len = prepare_param_data_types.keys().last().map_or(0, |&k| k + 1);
2833 (0..len)
2834 .map(|i| prepare_param_data_types.remove(&i))
2835 .collect()
2836 };
2837
2838 let mut planner_context =
2840 PlannerContext::new().with_prepare_param_data_types(prepare_param_data_types);
2841 planner_context.set_table_schema(Some(DFSchemaRef::new(
2842 DFSchema::from_unqualified_fields(fields.clone(), Metadata::new())?,
2843 )));
2844 let source = self.query_to_plan(*source, &mut planner_context)?;
2845 if fields.len() != source.schema().fields().len() {
2846 plan_err!("Column count doesn't match insert query!")?;
2847 }
2848
2849 let exprs = value_indices
2850 .into_iter()
2851 .enumerate()
2852 .map(|(i, value_index)| {
2853 let target_field = table_schema.field(i);
2854 let expr = match value_index {
2855 Some(v) => {
2856 Expr::Column(Column::from(source.schema().qualified_field(v)))
2857 .cast_to(target_field.data_type(), source.schema())?
2858 }
2859 None => table_source
2861 .get_column_default(target_field.name())
2862 .cloned()
2863 .unwrap_or_else(|| {
2864 Expr::Literal(ScalarValue::Null, None)
2866 })
2867 .cast_to(target_field.data_type(), &DFSchema::empty())?,
2868 };
2869 let (_, expr_field) = expr.to_field(source.schema())?;
2870 let expr = if target_field.extension_type_name().is_none()
2873 || expr_field.metadata() == target_field.metadata()
2874 {
2875 expr
2876 } else {
2877 match expr {
2878 Expr::Cast(cast) => Expr::Cast(Cast::new_from_field(
2879 cast.expr,
2880 Arc::clone(target_field),
2881 )),
2882 expr => Expr::Cast(Cast::new_from_field(
2883 Box::new(expr),
2884 Arc::clone(target_field),
2885 )),
2886 }
2887 };
2888 Ok(expr.alias(target_field.name()))
2889 })
2890 .collect::<Result<Vec<Expr>>>()?;
2891 let source = project(source, exprs)?;
2892
2893 let insert_op = match (overwrite, replace_into) {
2894 (false, false) => InsertOp::Append,
2895 (true, false) => InsertOp::Overwrite,
2896 (false, true) => InsertOp::Replace,
2897 (true, true) => plan_err!(
2898 "Conflicting insert operations: `overwrite` and `replace_into` cannot both be true"
2899 )?,
2900 };
2901
2902 let plan = LogicalPlan::Dml(DmlStatement::new(
2903 table_name,
2904 Arc::clone(&table_source),
2905 WriteOp::Insert(insert_op),
2906 Arc::new(source),
2907 ));
2908 Ok(plan)
2909 }
2910
2911 fn show_columns_to_plan(
2912 &self,
2913 extended: bool,
2914 full: bool,
2915 sql_table_name: ObjectName,
2916 ) -> Result<LogicalPlan> {
2917 let table_ref = self.object_name_to_table_reference(sql_table_name)?;
2918 let _ = self.context_provider.get_table_source(table_ref.clone())?;
2920
2921 let detail = if full || extended {
2923 ColumnsDetail::Full
2924 } else {
2925 ColumnsDetail::Basic
2926 };
2927
2928 LogicalPlanBuilder::show_columns(table_ref, detail)?.build()
2929 }
2930
2931 fn show_functions_to_plan(
2933 &self,
2934 filter: Option<ShowStatementFilter>,
2935 ) -> Result<LogicalPlan> {
2936 let filter = match filter {
2937 Some(ShowStatementFilter::Like(like)) => Some(like),
2938 Some(_) => return plan_err!("Unsupported SHOW FUNCTIONS filter"),
2939 None => None,
2940 };
2941
2942 LogicalPlanBuilder::show_functions(filter)?.build()
2943 }
2944
2945 fn show_create_table_to_plan(
2946 &self,
2947 sql_table_name: ObjectName,
2948 ) -> Result<LogicalPlan> {
2949 let table_ref = self.object_name_to_table_reference(sql_table_name)?;
2950 let _ = self.context_provider.get_table_source(table_ref.clone())?;
2952
2953 LogicalPlanBuilder::show_create_table(table_ref)?.build()
2954 }
2955
2956 fn validate_transaction_kind(
2957 &self,
2958 kind: Option<&BeginTransactionKind>,
2959 ) -> Result<()> {
2960 match kind {
2961 None => Ok(()),
2963 Some(BeginTransactionKind::Transaction) => Ok(()),
2965 Some(BeginTransactionKind::Work) | Some(BeginTransactionKind::Tran) => {
2966 not_impl_err!("Transaction kind not supported: {kind:?}")
2967 }
2968 }
2969 }
2970}
2971
2972fn check_plan(plan: &LogicalPlan) -> Result<()> {
2973 use datafusion_common::plan_err;
2974 use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};
2975 plan.apply(|node| {
2976 for field in node.schema().fields() {
2977 if field.name().starts_with("__common_expr") {
2978 return plan_err!(
2979 "{} is a reserved DataFusion column name, please use another name",
2980 field.name()
2981 );
2982 }
2983 }
2984 Ok(TreeNodeRecursion::Continue)
2985 })
2986 .map(|_| ())
2987}