use crate::{Expr, LogicalPlan, SortExpr, Volatility};
use std::cmp::Ordering;
use std::collections::HashMap;
use std::sync::Arc;
use std::{
fmt::{self, Display},
hash::{Hash, Hasher},
};
use crate::expr::{Exists, InSubquery, SetComparison, Sort};
#[cfg(not(feature = "sql"))]
use crate::sql::Ident;
use arrow::datatypes::DataType;
use datafusion_common::tree_node::{
Transformed, TreeNode, TreeNodeContainer, TreeNodeRecursion,
};
use datafusion_common::{
Constraints, DFSchema, DFSchemaRef, Result, SchemaReference, TableReference, plan_err,
};
#[cfg(feature = "sql")]
use sqlparser::ast::Ident;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
pub enum DdlStatement {
CreateExternalTable(Box<CreateExternalTable>),
CreateMemoryTable(CreateMemoryTable),
CreateView(CreateView),
CreateCatalogSchema(CreateCatalogSchema),
CreateCatalog(CreateCatalog),
CreateExternalCatalog(Box<CreateExternalCatalog>),
CreateIndex(CreateIndex),
DropTable(DropTable),
DropView(DropView),
DropCatalogSchema(DropCatalogSchema),
DropCatalog(DropCatalog),
CreateFunction(Box<CreateFunction>),
DropFunction(DropFunction),
}
impl DdlStatement {
pub fn schema(&self) -> &DFSchemaRef {
match self {
DdlStatement::CreateExternalTable(ce) => &ce.schema,
DdlStatement::CreateMemoryTable(CreateMemoryTable { input, .. })
| DdlStatement::CreateView(CreateView { input, .. }) => input.schema(),
DdlStatement::CreateCatalogSchema(CreateCatalogSchema { schema, .. }) => {
schema
}
DdlStatement::CreateCatalog(CreateCatalog { schema, .. }) => schema,
DdlStatement::CreateExternalCatalog(ce) => &ce.schema,
DdlStatement::CreateIndex(CreateIndex { schema, .. }) => schema,
DdlStatement::DropTable(DropTable { schema, .. }) => schema,
DdlStatement::DropView(DropView { schema, .. }) => schema,
DdlStatement::DropCatalogSchema(DropCatalogSchema { schema, .. }) => schema,
DdlStatement::DropCatalog(DropCatalog { schema, .. }) => schema,
DdlStatement::CreateFunction(cf) => &cf.schema,
DdlStatement::DropFunction(DropFunction { schema, .. }) => schema,
}
}
pub fn name(&self) -> &str {
match self {
DdlStatement::CreateExternalTable(_) => "CreateExternalTable",
DdlStatement::CreateMemoryTable(_) => "CreateMemoryTable",
DdlStatement::CreateView(_) => "CreateView",
DdlStatement::CreateCatalogSchema(_) => "CreateCatalogSchema",
DdlStatement::CreateCatalog(_) => "CreateCatalog",
DdlStatement::CreateExternalCatalog(_) => "CreateExternalCatalog",
DdlStatement::CreateIndex(_) => "CreateIndex",
DdlStatement::DropTable(_) => "DropTable",
DdlStatement::DropView(_) => "DropView",
DdlStatement::DropCatalogSchema(_) => "DropCatalogSchema",
DdlStatement::DropCatalog(_) => "DropCatalog",
DdlStatement::CreateFunction(_) => "CreateFunction",
DdlStatement::DropFunction(_) => "DropFunction",
}
}
pub fn inputs(&self) -> Vec<&LogicalPlan> {
match self {
DdlStatement::CreateExternalTable(_) => vec![],
DdlStatement::CreateCatalogSchema(_) => vec![],
DdlStatement::CreateCatalog(_) => vec![],
DdlStatement::CreateExternalCatalog(_) => vec![],
DdlStatement::CreateMemoryTable(CreateMemoryTable { input, .. }) => {
vec![input]
}
DdlStatement::CreateView(CreateView { input, .. }) => vec![input],
DdlStatement::CreateIndex(_) => vec![],
DdlStatement::DropTable(_) => vec![],
DdlStatement::DropView(_) => vec![],
DdlStatement::DropCatalogSchema(_) => vec![],
DdlStatement::DropCatalog(_) => vec![],
DdlStatement::CreateFunction(_) => vec![],
DdlStatement::DropFunction(_) => vec![],
}
}
pub fn display(&self) -> impl Display + '_ {
struct Wrapper<'a>(&'a DdlStatement);
impl Display for Wrapper<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.0 {
DdlStatement::CreateExternalTable(ce) => {
let name = &ce.name;
let constraints = &ce.constraints;
if constraints.is_empty() {
write!(f, "CreateExternalTable: {name:?}")
} else {
write!(f, "CreateExternalTable: {name:?} {constraints}")
}
}
DdlStatement::CreateMemoryTable(CreateMemoryTable {
name,
constraints,
..
}) => {
if constraints.is_empty() {
write!(f, "CreateMemoryTable: {name:?}")
} else {
write!(f, "CreateMemoryTable: {name:?} {constraints}")
}
}
DdlStatement::CreateView(CreateView { name, .. }) => {
write!(f, "CreateView: {name:?}")
}
DdlStatement::CreateCatalogSchema(CreateCatalogSchema {
schema_name,
..
}) => {
write!(f, "CreateCatalogSchema: {schema_name:?}")
}
DdlStatement::CreateCatalog(CreateCatalog {
catalog_name, ..
}) => {
write!(f, "CreateCatalog: {catalog_name:?}")
}
DdlStatement::CreateExternalCatalog(ce) => {
write!(f, "CreateExternalCatalog: {:?}", ce.catalog_name)
}
DdlStatement::CreateIndex(CreateIndex { name, .. }) => {
write!(f, "CreateIndex: {name:?}")
}
DdlStatement::DropTable(DropTable {
name, if_exists, ..
}) => {
write!(f, "DropTable: {name:?} if not exist:={if_exists}")
}
DdlStatement::DropView(DropView {
name, if_exists, ..
}) => {
write!(f, "DropView: {name:?} if not exist:={if_exists}")
}
DdlStatement::DropCatalogSchema(DropCatalogSchema {
name,
if_exists,
cascade,
..
}) => {
write!(
f,
"DropCatalogSchema: {name:?} if not exist:={if_exists} cascade:={cascade}"
)
}
DdlStatement::DropCatalog(DropCatalog {
name, if_exists, ..
}) => {
write!(f, "DropCatalog: {name:?} if not exist:={if_exists}")
}
DdlStatement::CreateFunction(cf) => {
let name = &cf.name;
write!(f, "CreateFunction: name {name:?}")
}
DdlStatement::DropFunction(DropFunction { name, .. }) => {
write!(f, "DropFunction: name {name:?}")
}
}
}
}
Wrapper(self)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreateExternalTable {
pub schema: DFSchemaRef,
pub name: TableReference,
pub locations: Vec<String>,
pub file_type: String,
pub table_partition_cols: Vec<String>,
pub if_not_exists: bool,
pub or_replace: bool,
pub temporary: bool,
pub definition: Option<String>,
pub order_exprs: Vec<Vec<Sort>>,
pub unbounded: bool,
pub options: HashMap<String, String>,
pub constraints: Constraints,
pub column_defaults: HashMap<String, Expr>,
}
impl CreateExternalTable {
pub fn builder(
name: impl Into<TableReference>,
location: impl Into<String>,
file_type: impl Into<String>,
schema: DFSchemaRef,
) -> CreateExternalTableBuilder {
CreateExternalTableBuilder {
name: name.into(),
locations: vec![location.into()],
file_type: file_type.into(),
schema,
table_partition_cols: vec![],
if_not_exists: false,
or_replace: false,
temporary: false,
definition: None,
order_exprs: vec![],
unbounded: false,
options: HashMap::new(),
constraints: Default::default(),
column_defaults: HashMap::new(),
}
}
}
#[derive(Debug, Clone)]
pub struct CreateExternalTableBuilder {
name: TableReference,
locations: Vec<String>,
file_type: String,
schema: DFSchemaRef,
table_partition_cols: Vec<String>,
if_not_exists: bool,
or_replace: bool,
temporary: bool,
definition: Option<String>,
order_exprs: Vec<Vec<Sort>>,
unbounded: bool,
options: HashMap<String, String>,
constraints: Constraints,
column_defaults: HashMap<String, Expr>,
}
impl CreateExternalTableBuilder {
pub fn with_partition_cols(mut self, cols: Vec<String>) -> Self {
self.table_partition_cols = cols;
self
}
pub fn with_locations(mut self, locations: Vec<String>) -> Self {
self.locations = locations;
self
}
pub fn with_if_not_exists(mut self, if_not_exists: bool) -> Self {
self.if_not_exists = if_not_exists;
self
}
pub fn with_or_replace(mut self, or_replace: bool) -> Self {
self.or_replace = or_replace;
self
}
pub fn with_temporary(mut self, temporary: bool) -> Self {
self.temporary = temporary;
self
}
pub fn with_definition(mut self, definition: Option<String>) -> Self {
self.definition = definition;
self
}
pub fn with_order_exprs(mut self, order_exprs: Vec<Vec<Sort>>) -> Self {
self.order_exprs = order_exprs;
self
}
pub fn with_unbounded(mut self, unbounded: bool) -> Self {
self.unbounded = unbounded;
self
}
pub fn with_options(mut self, options: HashMap<String, String>) -> Self {
self.options = options;
self
}
pub fn with_constraints(mut self, constraints: Constraints) -> Self {
self.constraints = constraints;
self
}
pub fn with_column_defaults(
mut self,
column_defaults: HashMap<String, Expr>,
) -> Self {
self.column_defaults = column_defaults;
self
}
pub fn build(self) -> CreateExternalTable {
CreateExternalTable {
schema: self.schema,
name: self.name,
locations: self.locations,
file_type: self.file_type,
table_partition_cols: self.table_partition_cols,
if_not_exists: self.if_not_exists,
or_replace: self.or_replace,
temporary: self.temporary,
definition: self.definition,
order_exprs: self.order_exprs,
unbounded: self.unbounded,
options: self.options,
constraints: self.constraints,
column_defaults: self.column_defaults,
}
}
}
impl Hash for CreateExternalTable {
fn hash<H: Hasher>(&self, state: &mut H) {
self.schema.hash(state);
self.name.hash(state);
self.locations.hash(state);
self.file_type.hash(state);
self.table_partition_cols.hash(state);
self.if_not_exists.hash(state);
self.definition.hash(state);
self.order_exprs.hash(state);
self.unbounded.hash(state);
self.options.len().hash(state); }
}
impl PartialOrd for CreateExternalTable {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
#[derive(PartialEq, PartialOrd)]
struct ComparableCreateExternalTable<'a> {
pub name: &'a TableReference,
pub locations: &'a Vec<String>,
pub file_type: &'a String,
pub table_partition_cols: &'a Vec<String>,
pub if_not_exists: &'a bool,
pub definition: &'a Option<String>,
pub order_exprs: &'a Vec<Vec<Sort>>,
pub unbounded: &'a bool,
pub constraints: &'a Constraints,
}
let comparable_self = ComparableCreateExternalTable {
name: &self.name,
locations: &self.locations,
file_type: &self.file_type,
table_partition_cols: &self.table_partition_cols,
if_not_exists: &self.if_not_exists,
definition: &self.definition,
order_exprs: &self.order_exprs,
unbounded: &self.unbounded,
constraints: &self.constraints,
};
let comparable_other = ComparableCreateExternalTable {
name: &other.name,
locations: &other.locations,
file_type: &other.file_type,
table_partition_cols: &other.table_partition_cols,
if_not_exists: &other.if_not_exists,
definition: &other.definition,
order_exprs: &other.order_exprs,
unbounded: &other.unbounded,
constraints: &other.constraints,
};
comparable_self
.partial_cmp(&comparable_other)
.filter(|cmp| *cmp != Ordering::Equal || self == other)
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
pub struct CreateMemoryTable {
pub name: TableReference,
pub constraints: Constraints,
pub input: Arc<LogicalPlan>,
pub if_not_exists: bool,
pub or_replace: bool,
pub column_defaults: Vec<(String, Expr)>,
pub temporary: bool,
}
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Hash)]
pub struct CreateView {
pub name: TableReference,
pub input: Arc<LogicalPlan>,
pub or_replace: bool,
pub definition: Option<String>,
pub temporary: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CreateCatalog {
pub catalog_name: String,
pub if_not_exists: bool,
pub schema: DFSchemaRef,
}
impl PartialOrd for CreateCatalog {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
match self.catalog_name.partial_cmp(&other.catalog_name) {
Some(Ordering::Equal) => self.if_not_exists.partial_cmp(&other.if_not_exists),
cmp => cmp,
}
.filter(|cmp| *cmp != Ordering::Equal || self == other)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreateExternalCatalog {
pub catalog_name: String,
pub catalog_type: String,
pub location: Option<String>,
pub if_not_exists: bool,
pub or_replace: bool,
pub options: HashMap<String, String>,
pub schema: DFSchemaRef,
}
impl Hash for CreateExternalCatalog {
fn hash<H: Hasher>(&self, state: &mut H) {
self.catalog_name.hash(state);
self.catalog_type.hash(state);
self.location.hash(state);
self.if_not_exists.hash(state);
self.or_replace.hash(state);
self.options.len().hash(state); }
}
impl PartialOrd for CreateExternalCatalog {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
#[derive(PartialEq, PartialOrd)]
struct ComparableCreateExternalCatalog<'a> {
pub catalog_name: &'a String,
pub catalog_type: &'a String,
pub location: &'a Option<String>,
pub if_not_exists: &'a bool,
pub or_replace: &'a bool,
}
let comparable_self = ComparableCreateExternalCatalog {
catalog_name: &self.catalog_name,
catalog_type: &self.catalog_type,
location: &self.location,
if_not_exists: &self.if_not_exists,
or_replace: &self.or_replace,
};
let comparable_other = ComparableCreateExternalCatalog {
catalog_name: &other.catalog_name,
catalog_type: &other.catalog_type,
location: &other.location,
if_not_exists: &other.if_not_exists,
or_replace: &other.or_replace,
};
comparable_self
.partial_cmp(&comparable_other)
.filter(|cmp| *cmp != Ordering::Equal || self == other)
}
}
impl CreateExternalCatalog {
#[must_use]
pub fn builder(
catalog_name: impl Into<String>,
catalog_type: impl Into<String>,
) -> CreateExternalCatalogBuilder {
CreateExternalCatalogBuilder {
catalog_name: catalog_name.into(),
catalog_type: catalog_type.into(),
location: None,
if_not_exists: false,
or_replace: false,
options: HashMap::new(),
schema: Arc::new(DFSchema::empty()),
}
}
}
#[derive(Debug, Clone)]
pub struct CreateExternalCatalogBuilder {
catalog_name: String,
catalog_type: String,
location: Option<String>,
if_not_exists: bool,
or_replace: bool,
options: HashMap<String, String>,
schema: DFSchemaRef,
}
impl CreateExternalCatalogBuilder {
#[must_use]
pub fn with_location(mut self, location: Option<String>) -> Self {
self.location = location;
self
}
#[must_use]
pub fn with_if_not_exists(mut self, if_not_exists: bool) -> Self {
self.if_not_exists = if_not_exists;
self
}
#[must_use]
pub fn with_or_replace(mut self, or_replace: bool) -> Self {
self.or_replace = or_replace;
self
}
#[must_use]
pub fn with_options(mut self, options: HashMap<String, String>) -> Self {
self.options = options;
self
}
#[must_use]
pub fn with_schema(mut self, schema: DFSchemaRef) -> Self {
self.schema = schema;
self
}
#[must_use]
pub fn build(self) -> CreateExternalCatalog {
CreateExternalCatalog {
catalog_name: self.catalog_name,
catalog_type: self.catalog_type,
location: self.location,
if_not_exists: self.if_not_exists,
or_replace: self.or_replace,
options: self.options,
schema: self.schema,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CreateCatalogSchema {
pub schema_name: String,
pub if_not_exists: bool,
pub schema: DFSchemaRef,
}
impl PartialOrd for CreateCatalogSchema {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
match self.schema_name.partial_cmp(&other.schema_name) {
Some(Ordering::Equal) => self.if_not_exists.partial_cmp(&other.if_not_exists),
cmp => cmp,
}
.filter(|cmp| *cmp != Ordering::Equal || self == other)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DropTable {
pub name: TableReference,
pub if_exists: bool,
pub schema: DFSchemaRef,
}
impl PartialOrd for DropTable {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
match self.name.partial_cmp(&other.name) {
Some(Ordering::Equal) => self.if_exists.partial_cmp(&other.if_exists),
cmp => cmp,
}
.filter(|cmp| *cmp != Ordering::Equal || self == other)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DropView {
pub name: TableReference,
pub if_exists: bool,
pub schema: DFSchemaRef,
}
impl PartialOrd for DropView {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
match self.name.partial_cmp(&other.name) {
Some(Ordering::Equal) => self.if_exists.partial_cmp(&other.if_exists),
cmp => cmp,
}
.filter(|cmp| *cmp != Ordering::Equal || self == other)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DropCatalogSchema {
pub name: SchemaReference,
pub if_exists: bool,
pub cascade: bool,
pub schema: DFSchemaRef,
}
impl PartialOrd for DropCatalogSchema {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
match self.name.partial_cmp(&other.name) {
Some(Ordering::Equal) => match self.if_exists.partial_cmp(&other.if_exists) {
Some(Ordering::Equal) => self.cascade.partial_cmp(&other.cascade),
cmp => cmp,
},
cmp => cmp,
}
.filter(|cmp| *cmp != Ordering::Equal || self == other)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DropCatalog {
pub name: String,
pub if_exists: bool,
pub cascade: bool,
pub schema: DFSchemaRef,
}
impl PartialOrd for DropCatalog {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
match self.name.partial_cmp(&other.name) {
Some(Ordering::Equal) => self.if_exists.partial_cmp(&other.if_exists),
cmp => cmp,
}
.filter(|cmp| *cmp != Ordering::Equal || self == other)
}
}
impl DropCatalog {
#[must_use]
pub fn builder(name: impl Into<String>) -> DropCatalogBuilder {
DropCatalogBuilder {
name: name.into(),
if_exists: false,
cascade: false,
schema: Arc::new(DFSchema::empty()),
}
}
}
#[derive(Debug, Clone)]
pub struct DropCatalogBuilder {
name: String,
if_exists: bool,
cascade: bool,
schema: DFSchemaRef,
}
impl DropCatalogBuilder {
#[must_use]
pub fn with_if_exists(mut self, if_exists: bool) -> Self {
self.if_exists = if_exists;
self
}
#[must_use]
pub fn with_cascade(mut self, cascade: bool) -> Self {
self.cascade = cascade;
self
}
#[must_use]
pub fn with_schema(mut self, schema: DFSchemaRef) -> Self {
self.schema = schema;
self
}
#[must_use]
pub fn build(self) -> DropCatalog {
DropCatalog {
name: self.name,
if_exists: self.if_exists,
cascade: self.cascade,
schema: self.schema,
}
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct CreateFunction {
pub or_replace: bool,
pub temporary: bool,
pub name: String,
pub args: Option<Vec<OperateFunctionArg>>,
pub return_type: Option<DataType>,
pub params: CreateFunctionBody,
pub schema: DFSchemaRef,
}
impl CreateFunction {
pub fn try_new(
or_replace: bool,
temporary: bool,
name: String,
args: Option<Vec<OperateFunctionArg>>,
return_type: Option<DataType>,
params: CreateFunctionBody,
) -> Result<Self> {
let arg_count = args.as_ref().map_or(0, |declared| declared.len());
for default_expr in args
.iter()
.flatten()
.filter_map(|arg| arg.default_expr.as_ref())
{
validate_function_body_placeholders(default_expr, arg_count)?;
}
if let Some(body) = ¶ms.function_body {
validate_function_body_placeholders(body, arg_count)?;
}
Ok(Self {
or_replace,
temporary,
name,
args,
return_type,
params,
schema: DFSchemaRef::new(DFSchema::empty()),
})
}
}
fn validate_function_body_placeholders(expr: &Expr, arg_count: usize) -> Result<()> {
expr.apply(|expr| {
if let Expr::Placeholder(placeholder) = expr {
match placeholder
.id
.strip_prefix('$')
.and_then(|id| id.parse::<usize>().ok())
{
Some(idx) if (1..=arg_count).contains(&idx) => {}
Some(_) => {
return plan_err!(
"Invalid placeholder, out of range: {}",
placeholder.id
);
}
None => {
return plan_err!("Unknown placeholder: {}", placeholder.id);
}
}
}
if let Some(subquery) = match expr {
Expr::ScalarSubquery(subquery) => Some(&subquery.subquery),
Expr::Exists(Exists { subquery, .. }) => Some(&subquery.subquery),
Expr::InSubquery(InSubquery { subquery, .. }) => Some(&subquery.subquery),
Expr::SetComparison(SetComparison { subquery, .. }) => {
Some(&subquery.subquery)
}
_ => None,
} {
subquery.apply(|plan| {
plan.apply_expressions(|e| {
validate_function_body_placeholders(e, arg_count)?;
Ok(TreeNodeRecursion::Continue)
})
})?;
}
Ok(TreeNodeRecursion::Continue)
})?;
Ok(())
}
impl PartialOrd for CreateFunction {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
#[derive(PartialEq, PartialOrd)]
struct ComparableCreateFunction<'a> {
pub or_replace: &'a bool,
pub temporary: &'a bool,
pub name: &'a String,
pub args: &'a Option<Vec<OperateFunctionArg>>,
pub return_type: &'a Option<DataType>,
pub params: &'a CreateFunctionBody,
}
let comparable_self = ComparableCreateFunction {
or_replace: &self.or_replace,
temporary: &self.temporary,
name: &self.name,
args: &self.args,
return_type: &self.return_type,
params: &self.params,
};
let comparable_other = ComparableCreateFunction {
or_replace: &other.or_replace,
temporary: &other.temporary,
name: &other.name,
args: &other.args,
return_type: &other.return_type,
params: &other.params,
};
comparable_self
.partial_cmp(&comparable_other)
.filter(|cmp| *cmp != Ordering::Equal || self == other)
}
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
pub struct OperateFunctionArg {
pub name: Option<Ident>,
pub data_type: DataType,
pub default_expr: Option<Expr>,
}
impl<'a> TreeNodeContainer<'a, Expr> for OperateFunctionArg {
fn apply_elements<F: FnMut(&'a Expr) -> Result<TreeNodeRecursion>>(
&'a self,
f: F,
) -> Result<TreeNodeRecursion> {
self.default_expr.apply_elements(f)
}
fn map_elements<F: FnMut(Expr) -> Result<Transformed<Expr>>>(
self,
f: F,
) -> Result<Transformed<Self>> {
self.default_expr.map_elements(f)?.map_data(|default_expr| {
Ok(Self {
default_expr,
..self
})
})
}
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
pub struct CreateFunctionBody {
pub language: Option<Ident>,
pub behavior: Option<Volatility>,
pub function_body: Option<Expr>,
}
impl<'a> TreeNodeContainer<'a, Expr> for CreateFunctionBody {
fn apply_elements<F: FnMut(&'a Expr) -> Result<TreeNodeRecursion>>(
&'a self,
f: F,
) -> Result<TreeNodeRecursion> {
self.function_body.apply_elements(f)
}
fn map_elements<F: FnMut(Expr) -> Result<Transformed<Expr>>>(
self,
f: F,
) -> Result<Transformed<Self>> {
self.function_body
.map_elements(f)?
.map_data(|function_body| {
Ok(Self {
function_body,
..self
})
})
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct DropFunction {
pub name: String,
pub if_exists: bool,
pub schema: DFSchemaRef,
}
impl PartialOrd for DropFunction {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
match self.name.partial_cmp(&other.name) {
Some(Ordering::Equal) => self.if_exists.partial_cmp(&other.if_exists),
cmp => cmp,
}
.filter(|cmp| *cmp != Ordering::Equal || self == other)
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct CreateIndex {
pub name: Option<String>,
pub table: TableReference,
pub using: Option<String>,
pub columns: Vec<SortExpr>,
pub unique: bool,
pub if_not_exists: bool,
pub schema: DFSchemaRef,
}
impl PartialOrd for CreateIndex {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
#[derive(PartialEq, PartialOrd)]
struct ComparableCreateIndex<'a> {
pub name: &'a Option<String>,
pub table: &'a TableReference,
pub using: &'a Option<String>,
pub columns: &'a Vec<SortExpr>,
pub unique: &'a bool,
pub if_not_exists: &'a bool,
}
let comparable_self = ComparableCreateIndex {
name: &self.name,
table: &self.table,
using: &self.using,
columns: &self.columns,
unique: &self.unique,
if_not_exists: &self.if_not_exists,
};
let comparable_other = ComparableCreateIndex {
name: &other.name,
table: &other.table,
using: &other.using,
columns: &other.columns,
unique: &other.unique,
if_not_exists: &other.if_not_exists,
};
comparable_self
.partial_cmp(&comparable_other)
.filter(|cmp| *cmp != Ordering::Equal || self == other)
}
}
#[cfg(test)]
mod test {
use super::{CreateFunction, CreateFunctionBody, OperateFunctionArg};
use crate::expr_fn::placeholder;
use crate::{
CreateCatalog, CreateExternalCatalog, DdlStatement, DropCatalog, DropView, Expr,
LogicalPlanBuilder, Subquery,
};
use arrow::datatypes::DataType;
use datafusion_common::{DFSchema, DFSchemaRef, TableReference};
use std::{cmp::Ordering, collections::HashMap, sync::Arc};
#[test]
fn create_function_try_new_validates_placeholders() {
let create = |body, default_expr| {
CreateFunction::try_new(
false,
false,
"f".to_string(),
Some(vec![OperateFunctionArg {
name: None,
data_type: DataType::Int64,
default_expr,
}]),
Some(DataType::Int64),
CreateFunctionBody {
language: None,
behavior: None,
function_body: body,
},
)
};
assert!(create(Some(placeholder("$1")), Some(placeholder("$1"))).is_ok());
assert!(create(None, None).is_ok());
for (body, default_expr) in [
(Some(placeholder("$2")), None),
(None, Some(placeholder("$2"))),
] {
let err = create(body, default_expr).unwrap_err();
assert_eq!(
err.strip_backtrace(),
"Error during planning: Invalid placeholder, out of range: $2"
);
}
let mut nested_body = placeholder("$2");
for _ in 0..16 {
let plan = LogicalPlanBuilder::empty(true)
.project(vec![nested_body.alias("v")])
.unwrap()
.build()
.unwrap();
nested_body = Expr::ScalarSubquery(Subquery {
subquery: Arc::new(plan),
outer_ref_columns: vec![],
spans: Default::default(),
});
}
let err = create(Some(nested_body), None).unwrap_err();
assert_eq!(
err.strip_backtrace(),
"Error during planning: Invalid placeholder, out of range: $2"
);
}
#[test]
fn test_partial_ord() {
let catalog = DdlStatement::CreateCatalog(CreateCatalog {
catalog_name: "name".to_string(),
if_not_exists: false,
schema: DFSchemaRef::new(DFSchema::empty()),
});
let catalog_2 = DdlStatement::CreateCatalog(CreateCatalog {
catalog_name: "name".to_string(),
if_not_exists: true,
schema: DFSchemaRef::new(DFSchema::empty()),
});
assert_eq!(catalog.partial_cmp(&catalog_2), Some(Ordering::Less));
let drop_view = DdlStatement::DropView(DropView {
name: TableReference::from("table"),
if_exists: false,
schema: DFSchemaRef::new(DFSchema::empty()),
});
assert_eq!(drop_view.partial_cmp(&catalog), Some(Ordering::Greater));
}
#[test]
fn test_create_external_catalog_builder_defaults() {
let expected = CreateExternalCatalog {
catalog_name: "my_catalog".to_string(),
catalog_type: "memory".to_string(),
location: None,
if_not_exists: false,
or_replace: false,
options: HashMap::new(),
schema: Arc::new(DFSchema::empty()),
};
let cmd = CreateExternalCatalog::builder("my_catalog", "memory").build();
assert_eq!(cmd, expected);
}
#[test]
fn test_create_external_catalog_builder_setters() {
let cmd = CreateExternalCatalog::builder("my_catalog", "memory")
.with_location(Some("/tmp/catalog".to_string()))
.with_if_not_exists(true)
.with_or_replace(true)
.with_options(HashMap::from([("key".to_string(), "value".to_string())]))
.with_schema(Arc::new(DFSchema::empty()))
.build();
assert_eq!(cmd.location, Some("/tmp/catalog".to_string()));
assert!(cmd.if_not_exists);
assert!(cmd.or_replace);
assert_eq!(cmd.options.get("key").map(String::as_str), Some("value"));
assert_eq!(cmd.schema, Arc::new(DFSchema::empty()));
}
#[test]
fn test_create_external_catalog_builder_unsets_location() {
let cmd = CreateExternalCatalog::builder("my_catalog", "memory")
.with_location(Some("/tmp/catalog".to_string()))
.with_location(None)
.build();
assert_eq!(cmd.location, None);
}
#[test]
fn test_drop_catalog_builder_defaults() {
let expected = DropCatalog {
name: "my_catalog".to_string(),
if_exists: false,
cascade: false,
schema: Arc::new(DFSchema::empty()),
};
let cmd = DropCatalog::builder("my_catalog").build();
assert_eq!(cmd, expected);
}
#[test]
fn test_drop_catalog_builder_setters() {
let cmd = DropCatalog::builder("my_catalog")
.with_if_exists(true)
.with_cascade(true)
.with_schema(Arc::new(DFSchema::empty()))
.build();
assert_eq!(cmd.name, "my_catalog");
assert!(cmd.if_exists);
assert!(cmd.cascade);
assert_eq!(cmd.schema, Arc::new(DFSchema::empty()));
}
}