Skip to main content

datafusion_expr/logical_plan/
ddl.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use crate::{Expr, LogicalPlan, SortExpr, Volatility};
6use std::cmp::Ordering;
7use std::collections::HashMap;
8use std::sync::Arc;
9use std::{
10    fmt::{self, Display},
11    hash::{Hash, Hasher},
12};
13
14use crate::expr::{Exists, InSubquery, SetComparison, Sort};
15#[cfg(not(feature = "sql"))]
16use crate::sql::Ident;
17use arrow::datatypes::DataType;
18use datafusion_common::tree_node::{
19    Transformed, TreeNode, TreeNodeContainer, TreeNodeRecursion,
20};
21use datafusion_common::{
22    Constraints, DFSchema, DFSchemaRef, Result, SchemaReference, TableReference, plan_err,
23};
24#[cfg(feature = "sql")]
25use sqlparser::ast::Ident;
26
27/// Various types of DDL  (CREATE / DROP) catalog manipulation
28#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
29pub enum DdlStatement {
30    /// Creates an external table. Boxed to keep `LogicalPlan` enum size down
31    /// — `CreateExternalTable` is ~312 bytes, dwarfing every other variant
32    /// in the plan tree and forcing the whole enum to that width.
33    CreateExternalTable(Box<CreateExternalTable>),
34    /// Creates an in memory table.
35    CreateMemoryTable(CreateMemoryTable),
36    /// Creates a new view.
37    CreateView(CreateView),
38    /// Creates a new catalog schema.
39    CreateCatalogSchema(CreateCatalogSchema),
40    /// Creates a new catalog (aka "Database").
41    CreateCatalog(CreateCatalog),
42    /// Creates a new catalog by invoking a registered `CatalogProviderFactory`.
43    CreateExternalCatalog(Box<CreateExternalCatalog>),
44    /// Creates a new index.
45    CreateIndex(CreateIndex),
46    /// Drops a table.
47    DropTable(DropTable),
48    /// Drops a view.
49    DropView(DropView),
50    /// Drops a catalog schema
51    DropCatalogSchema(DropCatalogSchema),
52    /// Drops a catalog (aka "Database").
53    DropCatalog(DropCatalog),
54    /// Create function statement. Boxed for the same reason as
55    /// [`Self::CreateExternalTable`] (~288 bytes).
56    CreateFunction(Box<CreateFunction>),
57    /// Drop function statement
58    DropFunction(DropFunction),
59}
60
61impl DdlStatement {
62    /// Get a reference to the logical plan's schema
63    pub fn schema(&self) -> &DFSchemaRef {
64        match self {
65            DdlStatement::CreateExternalTable(ce) => &ce.schema,
66            DdlStatement::CreateMemoryTable(CreateMemoryTable { input, .. })
67            | DdlStatement::CreateView(CreateView { input, .. }) => input.schema(),
68            DdlStatement::CreateCatalogSchema(CreateCatalogSchema { schema, .. }) => {
69                schema
70            }
71            DdlStatement::CreateCatalog(CreateCatalog { schema, .. }) => schema,
72            DdlStatement::CreateExternalCatalog(ce) => &ce.schema,
73            DdlStatement::CreateIndex(CreateIndex { schema, .. }) => schema,
74            DdlStatement::DropTable(DropTable { schema, .. }) => schema,
75            DdlStatement::DropView(DropView { schema, .. }) => schema,
76            DdlStatement::DropCatalogSchema(DropCatalogSchema { schema, .. }) => schema,
77            DdlStatement::DropCatalog(DropCatalog { schema, .. }) => schema,
78            DdlStatement::CreateFunction(cf) => &cf.schema,
79            DdlStatement::DropFunction(DropFunction { schema, .. }) => schema,
80        }
81    }
82
83    /// Return a descriptive string describing the type of this
84    /// [`DdlStatement`]
85    pub fn name(&self) -> &str {
86        match self {
87            DdlStatement::CreateExternalTable(_) => "CreateExternalTable",
88            DdlStatement::CreateMemoryTable(_) => "CreateMemoryTable",
89            DdlStatement::CreateView(_) => "CreateView",
90            DdlStatement::CreateCatalogSchema(_) => "CreateCatalogSchema",
91            DdlStatement::CreateCatalog(_) => "CreateCatalog",
92            DdlStatement::CreateExternalCatalog(_) => "CreateExternalCatalog",
93            DdlStatement::CreateIndex(_) => "CreateIndex",
94            DdlStatement::DropTable(_) => "DropTable",
95            DdlStatement::DropView(_) => "DropView",
96            DdlStatement::DropCatalogSchema(_) => "DropCatalogSchema",
97            DdlStatement::DropCatalog(_) => "DropCatalog",
98            DdlStatement::CreateFunction(_) => "CreateFunction",
99            DdlStatement::DropFunction(_) => "DropFunction",
100        }
101    }
102
103    /// Return all inputs for this plan
104    pub fn inputs(&self) -> Vec<&LogicalPlan> {
105        match self {
106            DdlStatement::CreateExternalTable(_) => vec![],
107            DdlStatement::CreateCatalogSchema(_) => vec![],
108            DdlStatement::CreateCatalog(_) => vec![],
109            DdlStatement::CreateExternalCatalog(_) => vec![],
110            DdlStatement::CreateMemoryTable(CreateMemoryTable { input, .. }) => {
111                vec![input]
112            }
113            DdlStatement::CreateView(CreateView { input, .. }) => vec![input],
114            DdlStatement::CreateIndex(_) => vec![],
115            DdlStatement::DropTable(_) => vec![],
116            DdlStatement::DropView(_) => vec![],
117            DdlStatement::DropCatalogSchema(_) => vec![],
118            DdlStatement::DropCatalog(_) => vec![],
119            DdlStatement::CreateFunction(_) => vec![],
120            DdlStatement::DropFunction(_) => vec![],
121        }
122    }
123
124    /// Return a `format`able structure with the a human readable
125    /// description of this LogicalPlan node per node, not including
126    /// children.
127    ///
128    /// See [crate::LogicalPlan::display] for an example
129    pub fn display(&self) -> impl Display + '_ {
130        struct Wrapper<'a>(&'a DdlStatement);
131        impl Display for Wrapper<'_> {
132            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
133                match self.0 {
134                    DdlStatement::CreateExternalTable(ce) => {
135                        let name = &ce.name;
136                        let constraints = &ce.constraints;
137                        if constraints.is_empty() {
138                            write!(f, "CreateExternalTable: {name:?}")
139                        } else {
140                            write!(f, "CreateExternalTable: {name:?} {constraints}")
141                        }
142                    }
143                    DdlStatement::CreateMemoryTable(CreateMemoryTable {
144                        name,
145                        constraints,
146                        ..
147                    }) => {
148                        if constraints.is_empty() {
149                            write!(f, "CreateMemoryTable: {name:?}")
150                        } else {
151                            write!(f, "CreateMemoryTable: {name:?} {constraints}")
152                        }
153                    }
154                    DdlStatement::CreateView(CreateView { name, .. }) => {
155                        write!(f, "CreateView: {name:?}")
156                    }
157                    DdlStatement::CreateCatalogSchema(CreateCatalogSchema {
158                        schema_name,
159                        ..
160                    }) => {
161                        write!(f, "CreateCatalogSchema: {schema_name:?}")
162                    }
163                    DdlStatement::CreateCatalog(CreateCatalog {
164                        catalog_name, ..
165                    }) => {
166                        write!(f, "CreateCatalog: {catalog_name:?}")
167                    }
168                    DdlStatement::CreateExternalCatalog(ce) => {
169                        write!(f, "CreateExternalCatalog: {:?}", ce.catalog_name)
170                    }
171                    DdlStatement::CreateIndex(CreateIndex { name, .. }) => {
172                        write!(f, "CreateIndex: {name:?}")
173                    }
174                    DdlStatement::DropTable(DropTable {
175                        name, if_exists, ..
176                    }) => {
177                        write!(f, "DropTable: {name:?} if not exist:={if_exists}")
178                    }
179                    DdlStatement::DropView(DropView {
180                        name, if_exists, ..
181                    }) => {
182                        write!(f, "DropView: {name:?} if not exist:={if_exists}")
183                    }
184                    DdlStatement::DropCatalogSchema(DropCatalogSchema {
185                        name,
186                        if_exists,
187                        cascade,
188                        ..
189                    }) => {
190                        write!(
191                            f,
192                            "DropCatalogSchema: {name:?} if not exist:={if_exists} cascade:={cascade}"
193                        )
194                    }
195                    DdlStatement::DropCatalog(DropCatalog {
196                        name, if_exists, ..
197                    }) => {
198                        write!(f, "DropCatalog: {name:?} if not exist:={if_exists}")
199                    }
200                    DdlStatement::CreateFunction(cf) => {
201                        let name = &cf.name;
202                        write!(f, "CreateFunction: name {name:?}")
203                    }
204                    DdlStatement::DropFunction(DropFunction { name, .. }) => {
205                        write!(f, "DropFunction: name {name:?}")
206                    }
207                }
208            }
209        }
210        Wrapper(self)
211    }
212}
213
214/// Creates an external table.
215#[derive(Debug, Clone, PartialEq, Eq)]
216pub struct CreateExternalTable {
217    /// The table schema
218    pub schema: DFSchemaRef,
219    /// The table name
220    pub name: TableReference,
221    /// The physical locations of the table files.
222    ///
223    /// More than one location may be supplied (for example
224    /// `CREATE EXTERNAL TABLE ... LOCATION ('a.parquet', 'b.parquet')`), in which
225    /// case the files are read together as a single table.
226    pub locations: Vec<String>,
227    /// The file type of physical file
228    pub file_type: String,
229    /// Partition Columns
230    pub table_partition_cols: Vec<String>,
231    /// Option to not error if table already exists
232    pub if_not_exists: bool,
233    /// Option to replace table content if table already exists
234    pub or_replace: bool,
235    /// Whether the table is a temporary table
236    pub temporary: bool,
237    /// SQL used to create the table, if available
238    pub definition: Option<String>,
239    /// Order expressions supplied by user
240    pub order_exprs: Vec<Vec<Sort>>,
241    /// Whether the table is an infinite streams
242    pub unbounded: bool,
243    /// Table(provider) specific options
244    pub options: HashMap<String, String>,
245    /// The list of constraints in the schema, such as primary key, unique, etc.
246    pub constraints: Constraints,
247    /// Default values for columns
248    pub column_defaults: HashMap<String, Expr>,
249}
250
251impl CreateExternalTable {
252    /// Creates a builder for [`CreateExternalTable`] with required fields.
253    ///
254    /// # Arguments
255    /// * `name` - The table name
256    /// * `location` - The physical location of the table files
257    /// * `file_type` - The file type (e.g., "parquet", "csv", "json")
258    /// * `schema` - The table schema
259    ///
260    /// # Example
261    /// ```
262    /// # use datafusion_expr::CreateExternalTable;
263    /// # use datafusion_common::{DFSchema, TableReference};
264    /// # use std::sync::Arc;
265    /// let table = CreateExternalTable::builder(
266    ///     TableReference::bare("my_table"),
267    ///     "/path/to/data",
268    ///     "parquet",
269    ///     Arc::new(DFSchema::empty())
270    /// ).build();
271    /// ```
272    pub fn builder(
273        name: impl Into<TableReference>,
274        location: impl Into<String>,
275        file_type: impl Into<String>,
276        schema: DFSchemaRef,
277    ) -> CreateExternalTableBuilder {
278        CreateExternalTableBuilder {
279            name: name.into(),
280            locations: vec![location.into()],
281            file_type: file_type.into(),
282            schema,
283            table_partition_cols: vec![],
284            if_not_exists: false,
285            or_replace: false,
286            temporary: false,
287            definition: None,
288            order_exprs: vec![],
289            unbounded: false,
290            options: HashMap::new(),
291            constraints: Default::default(),
292            column_defaults: HashMap::new(),
293        }
294    }
295}
296
297/// Builder for [`CreateExternalTable`] that provides a fluent API for construction.
298///
299/// Created via [`CreateExternalTable::builder`].
300#[derive(Debug, Clone)]
301pub struct CreateExternalTableBuilder {
302    name: TableReference,
303    locations: Vec<String>,
304    file_type: String,
305    schema: DFSchemaRef,
306    table_partition_cols: Vec<String>,
307    if_not_exists: bool,
308    or_replace: bool,
309    temporary: bool,
310    definition: Option<String>,
311    order_exprs: Vec<Vec<Sort>>,
312    unbounded: bool,
313    options: HashMap<String, String>,
314    constraints: Constraints,
315    column_defaults: HashMap<String, Expr>,
316}
317
318impl CreateExternalTableBuilder {
319    /// Set the partition columns
320    pub fn with_partition_cols(mut self, cols: Vec<String>) -> Self {
321        self.table_partition_cols = cols;
322        self
323    }
324
325    /// Set the physical locations of the table files, replacing the single
326    /// location supplied to [`CreateExternalTable::builder`].
327    ///
328    /// When more than one location is provided the files are read together as
329    /// a single table.
330    pub fn with_locations(mut self, locations: Vec<String>) -> Self {
331        self.locations = locations;
332        self
333    }
334
335    /// Set the if_not_exists flag
336    pub fn with_if_not_exists(mut self, if_not_exists: bool) -> Self {
337        self.if_not_exists = if_not_exists;
338        self
339    }
340
341    /// Set the or_replace flag
342    pub fn with_or_replace(mut self, or_replace: bool) -> Self {
343        self.or_replace = or_replace;
344        self
345    }
346
347    /// Set the temporary flag
348    pub fn with_temporary(mut self, temporary: bool) -> Self {
349        self.temporary = temporary;
350        self
351    }
352
353    /// Set the SQL definition
354    pub fn with_definition(mut self, definition: Option<String>) -> Self {
355        self.definition = definition;
356        self
357    }
358
359    /// Set the order expressions
360    pub fn with_order_exprs(mut self, order_exprs: Vec<Vec<Sort>>) -> Self {
361        self.order_exprs = order_exprs;
362        self
363    }
364
365    /// Set the unbounded flag
366    pub fn with_unbounded(mut self, unbounded: bool) -> Self {
367        self.unbounded = unbounded;
368        self
369    }
370
371    /// Set the table options
372    pub fn with_options(mut self, options: HashMap<String, String>) -> Self {
373        self.options = options;
374        self
375    }
376
377    /// Set the table constraints
378    pub fn with_constraints(mut self, constraints: Constraints) -> Self {
379        self.constraints = constraints;
380        self
381    }
382
383    /// Set the column defaults
384    pub fn with_column_defaults(
385        mut self,
386        column_defaults: HashMap<String, Expr>,
387    ) -> Self {
388        self.column_defaults = column_defaults;
389        self
390    }
391
392    /// Build the [`CreateExternalTable`]
393    pub fn build(self) -> CreateExternalTable {
394        CreateExternalTable {
395            schema: self.schema,
396            name: self.name,
397            locations: self.locations,
398            file_type: self.file_type,
399            table_partition_cols: self.table_partition_cols,
400            if_not_exists: self.if_not_exists,
401            or_replace: self.or_replace,
402            temporary: self.temporary,
403            definition: self.definition,
404            order_exprs: self.order_exprs,
405            unbounded: self.unbounded,
406            options: self.options,
407            constraints: self.constraints,
408            column_defaults: self.column_defaults,
409        }
410    }
411}
412
413// Hashing refers to a subset of fields considered in PartialEq.
414impl Hash for CreateExternalTable {
415    fn hash<H: Hasher>(&self, state: &mut H) {
416        self.schema.hash(state);
417        self.name.hash(state);
418        self.locations.hash(state);
419        self.file_type.hash(state);
420        self.table_partition_cols.hash(state);
421        self.if_not_exists.hash(state);
422        self.definition.hash(state);
423        self.order_exprs.hash(state);
424        self.unbounded.hash(state);
425        self.options.len().hash(state); // HashMap is not hashable
426    }
427}
428
429// Manual implementation needed because of `schema`, `options`, and `column_defaults` fields.
430// Comparison excludes these fields.
431impl PartialOrd for CreateExternalTable {
432    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
433        #[derive(PartialEq, PartialOrd)]
434        struct ComparableCreateExternalTable<'a> {
435            /// The table name
436            pub name: &'a TableReference,
437            /// The physical locations
438            pub locations: &'a Vec<String>,
439            /// The file type of physical file
440            pub file_type: &'a String,
441            /// Partition Columns
442            pub table_partition_cols: &'a Vec<String>,
443            /// Option to not error if table already exists
444            pub if_not_exists: &'a bool,
445            /// SQL used to create the table, if available
446            pub definition: &'a Option<String>,
447            /// Order expressions supplied by user
448            pub order_exprs: &'a Vec<Vec<Sort>>,
449            /// Whether the table is an infinite streams
450            pub unbounded: &'a bool,
451            /// The list of constraints in the schema, such as primary key, unique, etc.
452            pub constraints: &'a Constraints,
453        }
454        let comparable_self = ComparableCreateExternalTable {
455            name: &self.name,
456            locations: &self.locations,
457            file_type: &self.file_type,
458            table_partition_cols: &self.table_partition_cols,
459            if_not_exists: &self.if_not_exists,
460            definition: &self.definition,
461            order_exprs: &self.order_exprs,
462            unbounded: &self.unbounded,
463            constraints: &self.constraints,
464        };
465        let comparable_other = ComparableCreateExternalTable {
466            name: &other.name,
467            locations: &other.locations,
468            file_type: &other.file_type,
469            table_partition_cols: &other.table_partition_cols,
470            if_not_exists: &other.if_not_exists,
471            definition: &other.definition,
472            order_exprs: &other.order_exprs,
473            unbounded: &other.unbounded,
474            constraints: &other.constraints,
475        };
476        comparable_self
477            .partial_cmp(&comparable_other)
478            // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
479            .filter(|cmp| *cmp != Ordering::Equal || self == other)
480    }
481}
482
483/// Creates an in memory table.
484#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
485pub struct CreateMemoryTable {
486    /// The table name
487    pub name: TableReference,
488    /// The list of constraints in the schema, such as primary key, unique, etc.
489    pub constraints: Constraints,
490    /// The logical plan
491    pub input: Arc<LogicalPlan>,
492    /// Option to not error if table already exists
493    pub if_not_exists: bool,
494    /// Option to replace table content if table already exists
495    pub or_replace: bool,
496    /// Default values for columns
497    pub column_defaults: Vec<(String, Expr)>,
498    /// Whether the table is `TableType::Temporary`
499    pub temporary: bool,
500}
501
502/// Creates a view.
503#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Hash)]
504pub struct CreateView {
505    /// The table name
506    pub name: TableReference,
507    /// The logical plan
508    pub input: Arc<LogicalPlan>,
509    /// Option to not error if table already exists
510    pub or_replace: bool,
511    /// SQL used to create the view, if available
512    pub definition: Option<String>,
513    /// Whether the view is ephemeral
514    pub temporary: bool,
515}
516
517/// Creates a catalog (aka "Database").
518#[derive(Debug, Clone, PartialEq, Eq, Hash)]
519pub struct CreateCatalog {
520    /// The catalog name
521    pub catalog_name: String,
522    /// Do nothing (except issuing a notice) if a schema with the same name already exists
523    pub if_not_exists: bool,
524    /// Empty schema
525    pub schema: DFSchemaRef,
526}
527
528// Manual implementation needed because of `schema` field. Comparison excludes this field.
529impl PartialOrd for CreateCatalog {
530    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
531        match self.catalog_name.partial_cmp(&other.catalog_name) {
532            Some(Ordering::Equal) => self.if_not_exists.partial_cmp(&other.if_not_exists),
533            cmp => cmp,
534        }
535        // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
536        .filter(|cmp| *cmp != Ordering::Equal || self == other)
537    }
538}
539
540/// Creates a catalog by invoking a registered `CatalogProviderFactory`.
541///
542/// This mirrors [`CreateExternalTable`], which creates a table by invoking a
543/// registered `TableProviderFactory`.
544#[derive(Debug, Clone, PartialEq, Eq)]
545pub struct CreateExternalCatalog {
546    /// The catalog name
547    pub catalog_name: String,
548    /// The key used to look up the `CatalogProviderFactory` (the `STORED AS` clause)
549    pub catalog_type: String,
550    /// The physical location of the catalog, if applicable
551    pub location: Option<String>,
552    /// Do nothing (except issuing a notice) if a catalog with the same name already exists
553    pub if_not_exists: bool,
554    /// Option to replace the catalog if it already exists
555    pub or_replace: bool,
556    /// Catalog(provider) specific options
557    pub options: HashMap<String, String>,
558    /// Dummy schema
559    pub schema: DFSchemaRef,
560}
561
562// Hashing refers to a subset of fields considered in PartialEq.
563impl Hash for CreateExternalCatalog {
564    fn hash<H: Hasher>(&self, state: &mut H) {
565        self.catalog_name.hash(state);
566        self.catalog_type.hash(state);
567        self.location.hash(state);
568        self.if_not_exists.hash(state);
569        self.or_replace.hash(state);
570        self.options.len().hash(state); // HashMap is not hashable
571    }
572}
573
574// Manual implementation needed because of `schema` and `options` fields.
575// Comparison excludes these fields.
576impl PartialOrd for CreateExternalCatalog {
577    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
578        #[derive(PartialEq, PartialOrd)]
579        struct ComparableCreateExternalCatalog<'a> {
580            pub catalog_name: &'a String,
581            pub catalog_type: &'a String,
582            pub location: &'a Option<String>,
583            pub if_not_exists: &'a bool,
584            pub or_replace: &'a bool,
585        }
586        let comparable_self = ComparableCreateExternalCatalog {
587            catalog_name: &self.catalog_name,
588            catalog_type: &self.catalog_type,
589            location: &self.location,
590            if_not_exists: &self.if_not_exists,
591            or_replace: &self.or_replace,
592        };
593        let comparable_other = ComparableCreateExternalCatalog {
594            catalog_name: &other.catalog_name,
595            catalog_type: &other.catalog_type,
596            location: &other.location,
597            if_not_exists: &other.if_not_exists,
598            or_replace: &other.or_replace,
599        };
600        comparable_self
601            .partial_cmp(&comparable_other)
602            // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
603            .filter(|cmp| *cmp != Ordering::Equal || self == other)
604    }
605}
606
607impl CreateExternalCatalog {
608    /// Creates a builder for [`CreateExternalCatalog`].
609    ///
610    /// # Example
611    /// ```
612    /// # use datafusion_expr::CreateExternalCatalog;
613    /// let cmd = CreateExternalCatalog::builder("my_catalog", "memory")
614    ///     .with_if_not_exists(true)
615    ///     .build();
616    /// assert_eq!(cmd.catalog_name, "my_catalog");
617    /// ```
618    #[must_use]
619    pub fn builder(
620        catalog_name: impl Into<String>,
621        catalog_type: impl Into<String>,
622    ) -> CreateExternalCatalogBuilder {
623        CreateExternalCatalogBuilder {
624            catalog_name: catalog_name.into(),
625            catalog_type: catalog_type.into(),
626            location: None,
627            if_not_exists: false,
628            or_replace: false,
629            options: HashMap::new(),
630            schema: Arc::new(DFSchema::empty()),
631        }
632    }
633}
634
635/// Builder for [`CreateExternalCatalog`].
636#[derive(Debug, Clone)]
637pub struct CreateExternalCatalogBuilder {
638    catalog_name: String,
639    catalog_type: String,
640    location: Option<String>,
641    if_not_exists: bool,
642    or_replace: bool,
643    options: HashMap<String, String>,
644    schema: DFSchemaRef,
645}
646
647impl CreateExternalCatalogBuilder {
648    /// Set the physical location of the catalog
649    ///
650    /// Passing `None` will **un**set the location.
651    #[must_use]
652    pub fn with_location(mut self, location: Option<String>) -> Self {
653        self.location = location;
654        self
655    }
656
657    /// Set the if_not_exists flag
658    #[must_use]
659    pub fn with_if_not_exists(mut self, if_not_exists: bool) -> Self {
660        self.if_not_exists = if_not_exists;
661        self
662    }
663
664    /// Set the or_replace flag
665    #[must_use]
666    pub fn with_or_replace(mut self, or_replace: bool) -> Self {
667        self.or_replace = or_replace;
668        self
669    }
670
671    /// Set the catalog options
672    #[must_use]
673    pub fn with_options(mut self, options: HashMap<String, String>) -> Self {
674        self.options = options;
675        self
676    }
677
678    /// Set the schema
679    #[must_use]
680    pub fn with_schema(mut self, schema: DFSchemaRef) -> Self {
681        self.schema = schema;
682        self
683    }
684
685    /// Build the [`CreateExternalCatalog`]
686    #[must_use]
687    pub fn build(self) -> CreateExternalCatalog {
688        CreateExternalCatalog {
689            catalog_name: self.catalog_name,
690            catalog_type: self.catalog_type,
691            location: self.location,
692            if_not_exists: self.if_not_exists,
693            or_replace: self.or_replace,
694            options: self.options,
695            schema: self.schema,
696        }
697    }
698}
699
700/// Creates a schema.
701#[derive(Debug, Clone, PartialEq, Eq, Hash)]
702pub struct CreateCatalogSchema {
703    /// The table schema
704    pub schema_name: String,
705    /// Do nothing (except issuing a notice) if a schema with the same name already exists
706    pub if_not_exists: bool,
707    /// Empty schema
708    pub schema: DFSchemaRef,
709}
710
711// Manual implementation needed because of `schema` field. Comparison excludes this field.
712impl PartialOrd for CreateCatalogSchema {
713    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
714        match self.schema_name.partial_cmp(&other.schema_name) {
715            Some(Ordering::Equal) => self.if_not_exists.partial_cmp(&other.if_not_exists),
716            cmp => cmp,
717        }
718        // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
719        .filter(|cmp| *cmp != Ordering::Equal || self == other)
720    }
721}
722
723/// Drops a table.
724#[derive(Debug, Clone, PartialEq, Eq, Hash)]
725pub struct DropTable {
726    /// The table name
727    pub name: TableReference,
728    /// If the table exists
729    pub if_exists: bool,
730    /// Dummy schema
731    pub schema: DFSchemaRef,
732}
733
734// Manual implementation needed because of `schema` field. Comparison excludes this field.
735impl PartialOrd for DropTable {
736    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
737        match self.name.partial_cmp(&other.name) {
738            Some(Ordering::Equal) => self.if_exists.partial_cmp(&other.if_exists),
739            cmp => cmp,
740        }
741        // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
742        .filter(|cmp| *cmp != Ordering::Equal || self == other)
743    }
744}
745
746/// Drops a view.
747#[derive(Debug, Clone, PartialEq, Eq, Hash)]
748pub struct DropView {
749    /// The view name
750    pub name: TableReference,
751    /// If the view exists
752    pub if_exists: bool,
753    /// Dummy schema
754    pub schema: DFSchemaRef,
755}
756
757// Manual implementation needed because of `schema` field. Comparison excludes this field.
758impl PartialOrd for DropView {
759    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
760        match self.name.partial_cmp(&other.name) {
761            Some(Ordering::Equal) => self.if_exists.partial_cmp(&other.if_exists),
762            cmp => cmp,
763        }
764        // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
765        .filter(|cmp| *cmp != Ordering::Equal || self == other)
766    }
767}
768
769/// Drops a schema
770#[derive(Debug, Clone, PartialEq, Eq, Hash)]
771pub struct DropCatalogSchema {
772    /// The schema name
773    pub name: SchemaReference,
774    /// If the schema exists
775    pub if_exists: bool,
776    /// Whether drop should cascade
777    pub cascade: bool,
778    /// Dummy schema
779    pub schema: DFSchemaRef,
780}
781
782// Manual implementation needed because of `schema` field. Comparison excludes this field.
783impl PartialOrd for DropCatalogSchema {
784    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
785        match self.name.partial_cmp(&other.name) {
786            Some(Ordering::Equal) => match self.if_exists.partial_cmp(&other.if_exists) {
787                Some(Ordering::Equal) => self.cascade.partial_cmp(&other.cascade),
788                cmp => cmp,
789            },
790            cmp => cmp,
791        }
792        // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
793        .filter(|cmp| *cmp != Ordering::Equal || self == other)
794    }
795}
796
797/// Drops a catalog previously created with `CREATE EXTERNAL CATALOG`.
798#[derive(Debug, Clone, PartialEq, Eq, Hash)]
799pub struct DropCatalog {
800    /// The catalog name
801    pub name: String,
802    /// If the catalog exists
803    pub if_exists: bool,
804    /// Whether drop should cascade
805    pub cascade: bool,
806    /// Dummy schema
807    pub schema: DFSchemaRef,
808}
809
810// Manual implementation needed because of `schema` field. Comparison excludes this field.
811impl PartialOrd for DropCatalog {
812    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
813        match self.name.partial_cmp(&other.name) {
814            Some(Ordering::Equal) => self.if_exists.partial_cmp(&other.if_exists),
815            cmp => cmp,
816        }
817        // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
818        .filter(|cmp| *cmp != Ordering::Equal || self == other)
819    }
820}
821
822impl DropCatalog {
823    /// Creates a builder for [`DropCatalog`].
824    ///
825    /// # Example
826    /// ```
827    /// # use datafusion_expr::DropCatalog;
828    /// let cmd = DropCatalog::builder("my_catalog").with_if_exists(true).build();
829    /// assert_eq!(cmd.name, "my_catalog");
830    /// ```
831    #[must_use]
832    pub fn builder(name: impl Into<String>) -> DropCatalogBuilder {
833        DropCatalogBuilder {
834            name: name.into(),
835            if_exists: false,
836            cascade: false,
837            schema: Arc::new(DFSchema::empty()),
838        }
839    }
840}
841
842/// Builder for [`DropCatalog`].
843#[derive(Debug, Clone)]
844pub struct DropCatalogBuilder {
845    name: String,
846    if_exists: bool,
847    cascade: bool,
848    schema: DFSchemaRef,
849}
850
851impl DropCatalogBuilder {
852    /// Set the if_exists flag
853    #[must_use]
854    pub fn with_if_exists(mut self, if_exists: bool) -> Self {
855        self.if_exists = if_exists;
856        self
857    }
858
859    /// Set whether the drop should cascade
860    #[must_use]
861    pub fn with_cascade(mut self, cascade: bool) -> Self {
862        self.cascade = cascade;
863        self
864    }
865
866    /// Set the schema
867    #[must_use]
868    pub fn with_schema(mut self, schema: DFSchemaRef) -> Self {
869        self.schema = schema;
870        self
871    }
872
873    /// Build the [`DropCatalog`]
874    #[must_use]
875    pub fn build(self) -> DropCatalog {
876        DropCatalog {
877            name: self.name,
878            if_exists: self.if_exists,
879            cascade: self.cascade,
880            schema: self.schema,
881        }
882    }
883}
884
885/// Arguments passed to the `CREATE FUNCTION` statement
886///
887/// These statements are turned into executable functions using [`FunctionFactory`]
888///
889/// # Notes
890///
891/// This structure purposely mirrors the structure in sqlparser's
892/// [`sqlparser::ast::Statement::CreateFunction`], but does not use it directly
893/// to avoid a dependency on sqlparser in the core crate.
894///
895///
896/// [`FunctionFactory`]: https://docs.rs/datafusion/latest/datafusion/execution/context/trait.FunctionFactory.html
897#[derive(Clone, PartialEq, Eq, Hash, Debug)]
898pub struct CreateFunction {
899    pub or_replace: bool,
900    pub temporary: bool,
901    pub name: String,
902    pub args: Option<Vec<OperateFunctionArg>>,
903    pub return_type: Option<DataType>,
904    pub params: CreateFunctionBody,
905    /// Dummy schema
906    pub schema: DFSchemaRef,
907}
908
909impl CreateFunction {
910    /// Creates a function definition, validating placeholders in its body and
911    /// argument defaults, including expressions inside subqueries.
912    ///
913    /// Placeholders must be positional (`$1`, `$2`, ...) and reference a
914    /// declared argument. SQL argument names must be resolved before calling
915    /// this constructor.
916    pub fn try_new(
917        or_replace: bool,
918        temporary: bool,
919        name: String,
920        args: Option<Vec<OperateFunctionArg>>,
921        return_type: Option<DataType>,
922        params: CreateFunctionBody,
923    ) -> Result<Self> {
924        let arg_count = args.as_ref().map_or(0, |declared| declared.len());
925        for default_expr in args
926            .iter()
927            .flatten()
928            .filter_map(|arg| arg.default_expr.as_ref())
929        {
930            validate_function_body_placeholders(default_expr, arg_count)?;
931        }
932        if let Some(body) = &params.function_body {
933            validate_function_body_placeholders(body, arg_count)?;
934        }
935        Ok(Self {
936            or_replace,
937            temporary,
938            name,
939            args,
940            return_type,
941            params,
942            schema: DFSchemaRef::new(DFSchema::empty()),
943        })
944    }
945}
946
947/// Rejects placeholders in a `CREATE FUNCTION` body or argument default
948/// expression that do not reference a declared argument (e.g. `$3` for a
949/// two-argument function) at definition time, instead of deferring the error
950/// to function invocation.
951fn validate_function_body_placeholders(expr: &Expr, arg_count: usize) -> Result<()> {
952    expr.apply(|expr| {
953        if let Expr::Placeholder(placeholder) = expr {
954            match placeholder
955                .id
956                .strip_prefix('$')
957                .and_then(|id| id.parse::<usize>().ok())
958            {
959                // In range, e.g. `$2` with two declared arguments
960                Some(idx) if (1..=arg_count).contains(&idx) => {}
961                // Out of range, e.g. `$3` with two declared arguments
962                Some(_) => {
963                    return plan_err!(
964                        "Invalid placeholder, out of range: {}",
965                        placeholder.id
966                    );
967                }
968                // Named or malformed placeholder
969                None => {
970                    return plan_err!("Unknown placeholder: {}", placeholder.id);
971                }
972            }
973        }
974        // `Expr::apply` does not descend into subqueries, so walk their
975        // plans explicitly to validate placeholders inside them
976        if let Some(subquery) = match expr {
977            Expr::ScalarSubquery(subquery) => Some(&subquery.subquery),
978            Expr::Exists(Exists { subquery, .. }) => Some(&subquery.subquery),
979            Expr::InSubquery(InSubquery { subquery, .. }) => Some(&subquery.subquery),
980            Expr::SetComparison(SetComparison { subquery, .. }) => {
981                Some(&subquery.subquery)
982            }
983            _ => None,
984        } {
985            // Nested subqueries are handled by this expression visitor
986            subquery.apply(|plan| {
987                plan.apply_expressions(|e| {
988                    validate_function_body_placeholders(e, arg_count)?;
989                    Ok(TreeNodeRecursion::Continue)
990                })
991            })?;
992        }
993        Ok(TreeNodeRecursion::Continue)
994    })?;
995    Ok(())
996}
997
998// Manual implementation needed because of `schema` field. Comparison excludes this field.
999impl PartialOrd for CreateFunction {
1000    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1001        #[derive(PartialEq, PartialOrd)]
1002        struct ComparableCreateFunction<'a> {
1003            pub or_replace: &'a bool,
1004            pub temporary: &'a bool,
1005            pub name: &'a String,
1006            pub args: &'a Option<Vec<OperateFunctionArg>>,
1007            pub return_type: &'a Option<DataType>,
1008            pub params: &'a CreateFunctionBody,
1009        }
1010        let comparable_self = ComparableCreateFunction {
1011            or_replace: &self.or_replace,
1012            temporary: &self.temporary,
1013            name: &self.name,
1014            args: &self.args,
1015            return_type: &self.return_type,
1016            params: &self.params,
1017        };
1018        let comparable_other = ComparableCreateFunction {
1019            or_replace: &other.or_replace,
1020            temporary: &other.temporary,
1021            name: &other.name,
1022            args: &other.args,
1023            return_type: &other.return_type,
1024            params: &other.params,
1025        };
1026        comparable_self
1027            .partial_cmp(&comparable_other)
1028            // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
1029            .filter(|cmp| *cmp != Ordering::Equal || self == other)
1030    }
1031}
1032
1033/// Part of the `CREATE FUNCTION` statement
1034///
1035/// See [`CreateFunction`] for details
1036#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1037pub struct OperateFunctionArg {
1038    // TODO: figure out how to support mode
1039    // pub mode: Option<ArgMode>,
1040    pub name: Option<Ident>,
1041    pub data_type: DataType,
1042    pub default_expr: Option<Expr>,
1043}
1044
1045impl<'a> TreeNodeContainer<'a, Expr> for OperateFunctionArg {
1046    fn apply_elements<F: FnMut(&'a Expr) -> Result<TreeNodeRecursion>>(
1047        &'a self,
1048        f: F,
1049    ) -> Result<TreeNodeRecursion> {
1050        self.default_expr.apply_elements(f)
1051    }
1052
1053    fn map_elements<F: FnMut(Expr) -> Result<Transformed<Expr>>>(
1054        self,
1055        f: F,
1056    ) -> Result<Transformed<Self>> {
1057        self.default_expr.map_elements(f)?.map_data(|default_expr| {
1058            Ok(Self {
1059                default_expr,
1060                ..self
1061            })
1062        })
1063    }
1064}
1065
1066/// Part of the `CREATE FUNCTION` statement
1067///
1068/// See [`CreateFunction`] for details
1069#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1070pub struct CreateFunctionBody {
1071    /// LANGUAGE lang_name
1072    pub language: Option<Ident>,
1073    /// IMMUTABLE | STABLE | VOLATILE
1074    pub behavior: Option<Volatility>,
1075    /// RETURN or AS function body
1076    pub function_body: Option<Expr>,
1077}
1078
1079impl<'a> TreeNodeContainer<'a, Expr> for CreateFunctionBody {
1080    fn apply_elements<F: FnMut(&'a Expr) -> Result<TreeNodeRecursion>>(
1081        &'a self,
1082        f: F,
1083    ) -> Result<TreeNodeRecursion> {
1084        self.function_body.apply_elements(f)
1085    }
1086
1087    fn map_elements<F: FnMut(Expr) -> Result<Transformed<Expr>>>(
1088        self,
1089        f: F,
1090    ) -> Result<Transformed<Self>> {
1091        self.function_body
1092            .map_elements(f)?
1093            .map_data(|function_body| {
1094                Ok(Self {
1095                    function_body,
1096                    ..self
1097                })
1098            })
1099    }
1100}
1101
1102#[derive(Clone, PartialEq, Eq, Hash, Debug)]
1103pub struct DropFunction {
1104    pub name: String,
1105    pub if_exists: bool,
1106    pub schema: DFSchemaRef,
1107}
1108
1109impl PartialOrd for DropFunction {
1110    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1111        match self.name.partial_cmp(&other.name) {
1112            Some(Ordering::Equal) => self.if_exists.partial_cmp(&other.if_exists),
1113            cmp => cmp,
1114        }
1115        // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
1116        .filter(|cmp| *cmp != Ordering::Equal || self == other)
1117    }
1118}
1119
1120#[derive(Clone, PartialEq, Eq, Hash, Debug)]
1121pub struct CreateIndex {
1122    pub name: Option<String>,
1123    pub table: TableReference,
1124    pub using: Option<String>,
1125    pub columns: Vec<SortExpr>,
1126    pub unique: bool,
1127    pub if_not_exists: bool,
1128    pub schema: DFSchemaRef,
1129}
1130
1131// Manual implementation needed because of `schema` field. Comparison excludes this field.
1132impl PartialOrd for CreateIndex {
1133    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1134        #[derive(PartialEq, PartialOrd)]
1135        struct ComparableCreateIndex<'a> {
1136            pub name: &'a Option<String>,
1137            pub table: &'a TableReference,
1138            pub using: &'a Option<String>,
1139            pub columns: &'a Vec<SortExpr>,
1140            pub unique: &'a bool,
1141            pub if_not_exists: &'a bool,
1142        }
1143        let comparable_self = ComparableCreateIndex {
1144            name: &self.name,
1145            table: &self.table,
1146            using: &self.using,
1147            columns: &self.columns,
1148            unique: &self.unique,
1149            if_not_exists: &self.if_not_exists,
1150        };
1151        let comparable_other = ComparableCreateIndex {
1152            name: &other.name,
1153            table: &other.table,
1154            using: &other.using,
1155            columns: &other.columns,
1156            unique: &other.unique,
1157            if_not_exists: &other.if_not_exists,
1158        };
1159        comparable_self
1160            .partial_cmp(&comparable_other)
1161            // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
1162            .filter(|cmp| *cmp != Ordering::Equal || self == other)
1163    }
1164}
1165
1166#[cfg(test)]
1167mod test {
1168    use super::{CreateFunction, CreateFunctionBody, OperateFunctionArg};
1169    use crate::expr_fn::placeholder;
1170    use crate::{
1171        CreateCatalog, CreateExternalCatalog, DdlStatement, DropCatalog, DropView, Expr,
1172        LogicalPlanBuilder, Subquery,
1173    };
1174    use arrow::datatypes::DataType;
1175    use datafusion_common::{DFSchema, DFSchemaRef, TableReference};
1176    use std::{cmp::Ordering, collections::HashMap, sync::Arc};
1177
1178    #[test]
1179    fn create_function_try_new_validates_placeholders() {
1180        let create = |body, default_expr| {
1181            CreateFunction::try_new(
1182                false,
1183                false,
1184                "f".to_string(),
1185                Some(vec![OperateFunctionArg {
1186                    name: None,
1187                    data_type: DataType::Int64,
1188                    default_expr,
1189                }]),
1190                Some(DataType::Int64),
1191                CreateFunctionBody {
1192                    language: None,
1193                    behavior: None,
1194                    function_body: body,
1195                },
1196            )
1197        };
1198
1199        assert!(create(Some(placeholder("$1")), Some(placeholder("$1"))).is_ok());
1200        assert!(create(None, None).is_ok());
1201        for (body, default_expr) in [
1202            (Some(placeholder("$2")), None),
1203            (None, Some(placeholder("$2"))),
1204        ] {
1205            let err = create(body, default_expr).unwrap_err();
1206            assert_eq!(
1207                err.strip_backtrace(),
1208                "Error during planning: Invalid placeholder, out of range: $2"
1209            );
1210        }
1211
1212        let mut nested_body = placeholder("$2");
1213        for _ in 0..16 {
1214            let plan = LogicalPlanBuilder::empty(true)
1215                .project(vec![nested_body.alias("v")])
1216                .unwrap()
1217                .build()
1218                .unwrap();
1219            nested_body = Expr::ScalarSubquery(Subquery {
1220                subquery: Arc::new(plan),
1221                outer_ref_columns: vec![],
1222                spans: Default::default(),
1223            });
1224        }
1225        let err = create(Some(nested_body), None).unwrap_err();
1226        assert_eq!(
1227            err.strip_backtrace(),
1228            "Error during planning: Invalid placeholder, out of range: $2"
1229        );
1230    }
1231
1232    #[test]
1233    fn test_partial_ord() {
1234        let catalog = DdlStatement::CreateCatalog(CreateCatalog {
1235            catalog_name: "name".to_string(),
1236            if_not_exists: false,
1237            schema: DFSchemaRef::new(DFSchema::empty()),
1238        });
1239        let catalog_2 = DdlStatement::CreateCatalog(CreateCatalog {
1240            catalog_name: "name".to_string(),
1241            if_not_exists: true,
1242            schema: DFSchemaRef::new(DFSchema::empty()),
1243        });
1244
1245        assert_eq!(catalog.partial_cmp(&catalog_2), Some(Ordering::Less));
1246
1247        let drop_view = DdlStatement::DropView(DropView {
1248            name: TableReference::from("table"),
1249            if_exists: false,
1250            schema: DFSchemaRef::new(DFSchema::empty()),
1251        });
1252
1253        assert_eq!(drop_view.partial_cmp(&catalog), Some(Ordering::Greater));
1254    }
1255
1256    #[test]
1257    fn test_create_external_catalog_builder_defaults() {
1258        let expected = CreateExternalCatalog {
1259            catalog_name: "my_catalog".to_string(),
1260            catalog_type: "memory".to_string(),
1261            location: None,
1262            if_not_exists: false,
1263            or_replace: false,
1264            options: HashMap::new(),
1265            schema: Arc::new(DFSchema::empty()),
1266        };
1267        let cmd = CreateExternalCatalog::builder("my_catalog", "memory").build();
1268        assert_eq!(cmd, expected);
1269    }
1270
1271    #[test]
1272    fn test_create_external_catalog_builder_setters() {
1273        let cmd = CreateExternalCatalog::builder("my_catalog", "memory")
1274            .with_location(Some("/tmp/catalog".to_string()))
1275            .with_if_not_exists(true)
1276            .with_or_replace(true)
1277            .with_options(HashMap::from([("key".to_string(), "value".to_string())]))
1278            .with_schema(Arc::new(DFSchema::empty()))
1279            .build();
1280        assert_eq!(cmd.location, Some("/tmp/catalog".to_string()));
1281        assert!(cmd.if_not_exists);
1282        assert!(cmd.or_replace);
1283        assert_eq!(cmd.options.get("key").map(String::as_str), Some("value"));
1284        assert_eq!(cmd.schema, Arc::new(DFSchema::empty()));
1285    }
1286
1287    #[test]
1288    fn test_create_external_catalog_builder_unsets_location() {
1289        let cmd = CreateExternalCatalog::builder("my_catalog", "memory")
1290            .with_location(Some("/tmp/catalog".to_string()))
1291            .with_location(None)
1292            .build();
1293        assert_eq!(cmd.location, None);
1294    }
1295
1296    #[test]
1297    fn test_drop_catalog_builder_defaults() {
1298        let expected = DropCatalog {
1299            name: "my_catalog".to_string(),
1300            if_exists: false,
1301            cascade: false,
1302            schema: Arc::new(DFSchema::empty()),
1303        };
1304        let cmd = DropCatalog::builder("my_catalog").build();
1305        assert_eq!(cmd, expected);
1306    }
1307
1308    #[test]
1309    fn test_drop_catalog_builder_setters() {
1310        let cmd = DropCatalog::builder("my_catalog")
1311            .with_if_exists(true)
1312            .with_cascade(true)
1313            .with_schema(Arc::new(DFSchema::empty()))
1314            .build();
1315        assert_eq!(cmd.name, "my_catalog");
1316        assert!(cmd.if_exists);
1317        assert!(cmd.cascade);
1318        assert_eq!(cmd.schema, Arc::new(DFSchema::empty()));
1319    }
1320}