1use 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#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
29pub enum DdlStatement {
30 CreateExternalTable(Box<CreateExternalTable>),
34 CreateMemoryTable(CreateMemoryTable),
36 CreateView(CreateView),
38 CreateCatalogSchema(CreateCatalogSchema),
40 CreateCatalog(CreateCatalog),
42 CreateExternalCatalog(Box<CreateExternalCatalog>),
44 CreateIndex(CreateIndex),
46 DropTable(DropTable),
48 DropView(DropView),
50 DropCatalogSchema(DropCatalogSchema),
52 DropCatalog(DropCatalog),
54 CreateFunction(Box<CreateFunction>),
57 DropFunction(DropFunction),
59}
60
61impl DdlStatement {
62 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 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 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 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#[derive(Debug, Clone, PartialEq, Eq)]
216pub struct CreateExternalTable {
217 pub schema: DFSchemaRef,
219 pub name: TableReference,
221 pub locations: Vec<String>,
227 pub file_type: String,
229 pub table_partition_cols: Vec<String>,
231 pub if_not_exists: bool,
233 pub or_replace: bool,
235 pub temporary: bool,
237 pub definition: Option<String>,
239 pub order_exprs: Vec<Vec<Sort>>,
241 pub unbounded: bool,
243 pub options: HashMap<String, String>,
245 pub constraints: Constraints,
247 pub column_defaults: HashMap<String, Expr>,
249}
250
251impl CreateExternalTable {
252 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#[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 pub fn with_partition_cols(mut self, cols: Vec<String>) -> Self {
321 self.table_partition_cols = cols;
322 self
323 }
324
325 pub fn with_locations(mut self, locations: Vec<String>) -> Self {
331 self.locations = locations;
332 self
333 }
334
335 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 pub fn with_or_replace(mut self, or_replace: bool) -> Self {
343 self.or_replace = or_replace;
344 self
345 }
346
347 pub fn with_temporary(mut self, temporary: bool) -> Self {
349 self.temporary = temporary;
350 self
351 }
352
353 pub fn with_definition(mut self, definition: Option<String>) -> Self {
355 self.definition = definition;
356 self
357 }
358
359 pub fn with_order_exprs(mut self, order_exprs: Vec<Vec<Sort>>) -> Self {
361 self.order_exprs = order_exprs;
362 self
363 }
364
365 pub fn with_unbounded(mut self, unbounded: bool) -> Self {
367 self.unbounded = unbounded;
368 self
369 }
370
371 pub fn with_options(mut self, options: HashMap<String, String>) -> Self {
373 self.options = options;
374 self
375 }
376
377 pub fn with_constraints(mut self, constraints: Constraints) -> Self {
379 self.constraints = constraints;
380 self
381 }
382
383 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 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
413impl 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); }
427}
428
429impl PartialOrd for CreateExternalTable {
432 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
433 #[derive(PartialEq, PartialOrd)]
434 struct ComparableCreateExternalTable<'a> {
435 pub name: &'a TableReference,
437 pub locations: &'a Vec<String>,
439 pub file_type: &'a String,
441 pub table_partition_cols: &'a Vec<String>,
443 pub if_not_exists: &'a bool,
445 pub definition: &'a Option<String>,
447 pub order_exprs: &'a Vec<Vec<Sort>>,
449 pub unbounded: &'a bool,
451 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 .filter(|cmp| *cmp != Ordering::Equal || self == other)
480 }
481}
482
483#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
485pub struct CreateMemoryTable {
486 pub name: TableReference,
488 pub constraints: Constraints,
490 pub input: Arc<LogicalPlan>,
492 pub if_not_exists: bool,
494 pub or_replace: bool,
496 pub column_defaults: Vec<(String, Expr)>,
498 pub temporary: bool,
500}
501
502#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Hash)]
504pub struct CreateView {
505 pub name: TableReference,
507 pub input: Arc<LogicalPlan>,
509 pub or_replace: bool,
511 pub definition: Option<String>,
513 pub temporary: bool,
515}
516
517#[derive(Debug, Clone, PartialEq, Eq, Hash)]
519pub struct CreateCatalog {
520 pub catalog_name: String,
522 pub if_not_exists: bool,
524 pub schema: DFSchemaRef,
526}
527
528impl 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 .filter(|cmp| *cmp != Ordering::Equal || self == other)
537 }
538}
539
540#[derive(Debug, Clone, PartialEq, Eq)]
545pub struct CreateExternalCatalog {
546 pub catalog_name: String,
548 pub catalog_type: String,
550 pub location: Option<String>,
552 pub if_not_exists: bool,
554 pub or_replace: bool,
556 pub options: HashMap<String, String>,
558 pub schema: DFSchemaRef,
560}
561
562impl 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); }
572}
573
574impl 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 .filter(|cmp| *cmp != Ordering::Equal || self == other)
604 }
605}
606
607impl CreateExternalCatalog {
608 #[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#[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 #[must_use]
652 pub fn with_location(mut self, location: Option<String>) -> Self {
653 self.location = location;
654 self
655 }
656
657 #[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 #[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 #[must_use]
673 pub fn with_options(mut self, options: HashMap<String, String>) -> Self {
674 self.options = options;
675 self
676 }
677
678 #[must_use]
680 pub fn with_schema(mut self, schema: DFSchemaRef) -> Self {
681 self.schema = schema;
682 self
683 }
684
685 #[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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
702pub struct CreateCatalogSchema {
703 pub schema_name: String,
705 pub if_not_exists: bool,
707 pub schema: DFSchemaRef,
709}
710
711impl 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 .filter(|cmp| *cmp != Ordering::Equal || self == other)
720 }
721}
722
723#[derive(Debug, Clone, PartialEq, Eq, Hash)]
725pub struct DropTable {
726 pub name: TableReference,
728 pub if_exists: bool,
730 pub schema: DFSchemaRef,
732}
733
734impl 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 .filter(|cmp| *cmp != Ordering::Equal || self == other)
743 }
744}
745
746#[derive(Debug, Clone, PartialEq, Eq, Hash)]
748pub struct DropView {
749 pub name: TableReference,
751 pub if_exists: bool,
753 pub schema: DFSchemaRef,
755}
756
757impl 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 .filter(|cmp| *cmp != Ordering::Equal || self == other)
766 }
767}
768
769#[derive(Debug, Clone, PartialEq, Eq, Hash)]
771pub struct DropCatalogSchema {
772 pub name: SchemaReference,
774 pub if_exists: bool,
776 pub cascade: bool,
778 pub schema: DFSchemaRef,
780}
781
782impl 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 .filter(|cmp| *cmp != Ordering::Equal || self == other)
794 }
795}
796
797#[derive(Debug, Clone, PartialEq, Eq, Hash)]
799pub struct DropCatalog {
800 pub name: String,
802 pub if_exists: bool,
804 pub cascade: bool,
806 pub schema: DFSchemaRef,
808}
809
810impl 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 .filter(|cmp| *cmp != Ordering::Equal || self == other)
819 }
820}
821
822impl DropCatalog {
823 #[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#[derive(Debug, Clone)]
844pub struct DropCatalogBuilder {
845 name: String,
846 if_exists: bool,
847 cascade: bool,
848 schema: DFSchemaRef,
849}
850
851impl DropCatalogBuilder {
852 #[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 #[must_use]
861 pub fn with_cascade(mut self, cascade: bool) -> Self {
862 self.cascade = cascade;
863 self
864 }
865
866 #[must_use]
868 pub fn with_schema(mut self, schema: DFSchemaRef) -> Self {
869 self.schema = schema;
870 self
871 }
872
873 #[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#[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 pub schema: DFSchemaRef,
907}
908
909impl CreateFunction {
910 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) = ¶ms.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
947fn 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 Some(idx) if (1..=arg_count).contains(&idx) => {}
961 Some(_) => {
963 return plan_err!(
964 "Invalid placeholder, out of range: {}",
965 placeholder.id
966 );
967 }
968 None => {
970 return plan_err!("Unknown placeholder: {}", placeholder.id);
971 }
972 }
973 }
974 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 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
998impl 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 .filter(|cmp| *cmp != Ordering::Equal || self == other)
1030 }
1031}
1032
1033#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1037pub struct OperateFunctionArg {
1038 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#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1070pub struct CreateFunctionBody {
1071 pub language: Option<Ident>,
1073 pub behavior: Option<Volatility>,
1075 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 .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
1131impl 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 .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}