Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 30 additions & 20 deletions src/binder/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,10 @@
use crate::errors::DatabaseError;
use crate::expression;
use crate::expression::agg::AggKind;
use crate::iter_ext::Itertools;

use super::{Binder, BinderContext, BoundScalarQuery, QueryBindStep, SubQueryType};
use crate::expression::function::scala::{ArcScalarFunctionImpl, ScalarFunction};
use crate::expression::function::table::TableFunction;
use crate::expression::function::FunctionSummary;
use crate::expression::{AliasType, ScalarExpression, TypeCast};
use crate::planner::operator::mark_apply::MarkApplyQuantifier;
use crate::planner::operator::scalar_subquery::ScalarSubqueryOperator;
Expand Down Expand Up @@ -723,37 +721,49 @@ impl<'a, T: StorageTransaction, A: AsRef<[(usize, LogicalType)]>> Binder<'a, '_,
}
_ => (),
}
let arg_types = args
.iter()
.map(|arg| arg.return_type(arena).into_owned())
.collect_vec();
let summary = FunctionSummary {
name: function_name.into(),
arg_types,
};
// TODO: a NULL literal argument has type `SqlNull`, so the exact lookup
// misses e.g. `upper(null)` (FunctionNotFound). PostgreSQL treats it as
// an unknown type that matches any parameter and returns NULL.
if let Some(function) = self.context.scala_functions.get(&summary) {
let arg_types = args.iter().map(|arg| arg.return_type(arena));
if let Some((resolved, function)) = self
.context
.scala_functions
.resolve(&function_name, &arg_types)?
{
let function = function.clone();
Self::cast_function_args(&mut args, &resolved.arg_types, arena)?;
return Ok(ScalarExpression::ScalaFunction(ScalarFunction {
args,
inner: ArcScalarFunctionImpl(function.clone()),
inner: ArcScalarFunctionImpl(function),
}));
}
if let Some(function) = self.context.table_functions.get(&summary) {
if let Some((resolved, function)) = self
.context
.table_functions
.resolve(&function_name, &arg_types)?
{
if !table_function_source || !matches!(self.context.step_now(), QueryBindStep::From) {
return Err(DatabaseError::UnsupportedStmt(format!(
"table function `{}` can only be used as a FROM source",
summary.name
"table function `{function_name}` can only be used as a FROM source",
)));
}
let catalog = function.clone();
Self::cast_function_args(&mut args, &resolved.arg_types, arena)?;
return Ok(ScalarExpression::TableFunction(TableFunction {
args,
catalog: function.clone(),
catalog,
}));
}

Err(DatabaseError::function_not_found(summary.name.to_string()))
Err(DatabaseError::function_not_found(function_name))
}

fn cast_function_args(
args: &mut [ExprRef],
param_types: &[LogicalType],
arena: &mut PlanArena,
) -> Result<(), DatabaseError> {
for (arg, param) in args.iter_mut().zip(param_types) {
*arg = arg.type_cast(Cow::Borrowed(param), arena)?;
}
Ok(())
}

pub(crate) fn return_type(
Expand Down
37 changes: 20 additions & 17 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use crate::expression::function::scala::ScalarFunctionImpl;
use crate::expression::function::table::{
ArcTableFunctionImpl, TableFunctionCatalog, TableFunctionImpl,
};
use crate::expression::function::FunctionSummary;
use crate::expression::function::FunctionRegistry;
use crate::function::abs::Abs;
use crate::function::char_length::CharLength;
#[cfg(feature = "time")]
Expand Down Expand Up @@ -65,7 +65,7 @@ use ordered_float::OrderedFloat;
pub use program::{Param, Program, ProgramIter};
pub use session::{Session, SessionIter};
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::collections::HashSet;
use std::marker::PhantomData;
use std::mem;
use std::ops::Deref;
Expand Down Expand Up @@ -107,8 +107,8 @@ impl<T> Drop for OwnedPtr<T> {

pub(crate) type Execution<'a, 'p, A, T> = (ExecMetaArena<A>, (Executor<'p>, ExecArena<'p, 'a, T>));

pub(crate) type ScalaFunctions = HashMap<FunctionSummary, Arc<dyn ScalarFunctionImpl>>;
pub(crate) type TableFunctions = HashMap<FunctionSummary, TableFunctionCatalog>;
pub(crate) type ScalaFunctions = FunctionRegistry<Arc<dyn ScalarFunctionImpl>>;
pub(crate) type TableFunctions = FunctionRegistry<TableFunctionCatalog>;
pub(crate) type FunctionRegistries<'a> = (&'a ScalaFunctions, &'a TableFunctions);

pub enum CatalogKind {
Expand Down Expand Up @@ -482,17 +482,17 @@ impl<D: SqlDialect> DataBaseBuilder<D> {
};

for ty in Abs::types() {
state.load_scalar_function(Abs::new(ty));
state.load_scalar_function(Abs::new(ty))?;
}
state.load_scalar_function(CharLength::new("char_length".to_lowercase()));
state.load_scalar_function(CharLength::new("character_length".to_lowercase()));
state.load_scalar_function(CharLength::new("char_length".to_lowercase()))?;
state.load_scalar_function(CharLength::new("character_length".to_lowercase()))?;
#[cfg(feature = "time")]
state.load_scalar_function(CurrentDate::new());
state.load_scalar_function(CurrentDate::new())?;
#[cfg(feature = "time")]
state.load_scalar_function(CurrentTimeStamp::new());
state.load_scalar_function(Lower::new());
state.load_scalar_function(OctetLength::new());
state.load_scalar_function(Upper::new());
state.load_scalar_function(CurrentTimeStamp::new())?;
state.load_scalar_function(Lower::new())?;
state.load_scalar_function(OctetLength::new())?;
state.load_scalar_function(Upper::new())?;
state.load_table_function(Numbers::new())?;

Ok(Database {
Expand Down Expand Up @@ -765,15 +765,21 @@ impl<S: Storage, D: SqlDialect> State<S, D> {
&self.table_arena
}

fn load_scalar_function(&mut self, function: Arc<dyn ScalarFunctionImpl>) {
fn load_scalar_function(
&mut self,
function: Arc<dyn ScalarFunctionImpl>,
) -> Result<(), DatabaseError> {
function.summary().check_arg_types()?;
self.scala_functions
.insert(function.summary().clone(), function);
Ok(())
}

fn load_table_function(
&mut self,
function: Arc<dyn TableFunctionImpl>,
) -> Result<(), DatabaseError> {
function.summary().check_arg_types()?;
let summary = function.summary().clone();
let mut schema = Schema::new();
function.output_schema_into(self.table_arena.borrow_mut(), &mut schema);
Expand Down Expand Up @@ -1122,10 +1128,7 @@ impl<S: Storage, D: SqlDialect> Database<S, D> {

pub async fn load(&mut self, kind: CatalogKind) -> Result<(), DatabaseError> {
match kind {
CatalogKind::ScalarFunction(function) => {
self.state.load_scalar_function(function);
Ok(())
}
CatalogKind::ScalarFunction(function) => self.state.load_scalar_function(function),
CatalogKind::TableFunction(function) => {
self.state.load_table_function(function)?;
self.state.recycle_table_arena()?;
Expand Down
5 changes: 5 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ fn format_not_null_message(column: &Option<String>, span: &Option<SqlErrorSpan>)
pub enum DatabaseError {
AggMiss(String),
AmbiguousColumn(String),
AmbiguousFunction(String),
CacheSizeOverFlow,
CastFail {
from: LogicalType,
Expand Down Expand Up @@ -157,6 +158,10 @@ impl fmt::Display for DatabaseError {
match self {
Self::AggMiss(value) => write!(f, "agg miss: {value}"),
Self::AmbiguousColumn(value) => write!(f, "column: `{value}` is ambiguous"),
Self::AmbiguousFunction(value) => write!(
f,
"function: `{value}` is ambiguous for the given argument types, add explicit casts"
),
Self::CacheSizeOverFlow => f.write_str("cache size overflow"),
Self::CastFail { from, to, span } => {
write!(f, "cast fail: {from} -> {to}{}", format_sql_error_loc(span))
Expand Down
Loading
Loading