Skip to content
Open
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
4 changes: 3 additions & 1 deletion src/binder/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -728,7 +728,9 @@ impl<'a, T: StorageTransaction, A: AsRef<[(usize, LogicalType)]>> Binder<'a, '_,
.resolve(&function_name, &arg_types)?
{
let function = function.clone();
Self::cast_function_args(&mut args, &resolved.arg_types, arena)?;
if !function.accepts_any_args() {
Self::cast_function_args(&mut args, &resolved.arg_types, arena)?;
}
return Ok(ScalarExpression::ScalaFunction(ScalarFunction {
args,
inner: ArcScalarFunctionImpl(function),
Expand Down
5 changes: 3 additions & 2 deletions src/expression/evaluator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,12 +281,13 @@ impl ScalarExpression {
}
Ok(Cow::Owned(DataValue::Tuple(values)))
}
ScalarExpression::ScalaFunction(ScalarFunction { inner, args, .. }) => {
ScalarExpression::ScalaFunction(function) => {
let ScalarFunction { inner, args } = function;
let value = match tuple {
Some(tuple) => inner.eval(args, arena, Some(&InputRef(tuple)))?,
None => inner.eval(args, arena, None)?,
};
value.cast(inner.return_type()).map(Cow::Owned)
value.cast(&function.return_type(arena)).map(Cow::Owned)
}
ScalarExpression::Empty => unreachable!(),
ScalarExpression::If {
Expand Down
110 changes: 108 additions & 2 deletions src/expression/function/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,21 @@ fn cmp_summary(a: &FunctionSummary, b: &FunctionSummary) -> Ordering {
.then_with(|| a.arg_types.cmp(&b.arg_types))
}

/// How a registered function takes its arguments, as far as resolution is concerned.
pub(crate) trait FunctionArgs {
/// Whether the function takes its arguments as they are, of any type, instead of by its
/// declared parameter types. The default implementation returns `false`.
fn accepts_any_args(&self) -> bool {
false
}

/// Whether a function that [`accepts_any_args`](Self::accepts_any_args) takes `n`
/// arguments. The default implementation returns `false`.
fn accepts_arity(&self, _n: usize) -> bool {
false
}
}

#[derive(Debug)]
pub struct FunctionRegistry<V>(Vec<(FunctionSummary, V)>);

Expand Down Expand Up @@ -109,6 +124,12 @@ impl<V> FunctionRegistry<V> {
self.0.iter().map(|(_, v)| v)
}

/// Finds the function `name` that takes arguments of `arg_types`.
///
/// Overloads resolved by their declared parameter types are tried first. When none of them
/// accepts the arguments, a function of that name that
/// [`accepts_any_args`](FunctionArgs::accepts_any_args) with this many arguments is used;
/// its arguments are not cast.
pub(crate) fn resolve<T, I>(
&self,
name: &str,
Expand All @@ -117,14 +138,16 @@ impl<V> FunctionRegistry<V> {
where
T: Borrow<LogicalType>,
I: ExactSizeIterator<Item = T> + Clone,
V: FunctionArgs,
{
let start = self.0.partition_point(|(s, _)| s.name.as_ref() < name);
let end = start + self.0[start..].partition_point(|(s, _)| s.name.as_ref() == name);
let mut best = None;
let mut ambiguous = false;
let candidates = || {
self.0[start..end].iter().filter(|(s, _)| {
s.arg_types.len() == arg_types.len()
self.0[start..end].iter().filter(|(s, v)| {
!v.accepts_any_args()
&& s.arg_types.len() == arg_types.len()
&& arg_types
.clone()
.zip(&s.arg_types)
Expand Down Expand Up @@ -159,6 +182,15 @@ impl<V> FunctionRegistry<V> {
if ambiguous {
return Err(DatabaseError::AmbiguousFunction(name.to_string()));
}
if best.is_none() {
let mut any_args = self.0[start..end]
.iter()
.filter(|(_, v)| v.accepts_any_args() && v.accepts_arity(arg_types.len()));
best = any_args.next();
if best.is_some() && any_args.next().is_some() {
return Err(DatabaseError::AmbiguousFunction(name.to_string()));
}
}
Ok(best.map(|(s, v)| (s, v)))
}

Expand Down Expand Up @@ -189,6 +221,22 @@ mod tests {
use super::*;
use crate::types::CharLengthUnits;

impl FunctionArgs for &'static str {}

/// A function that takes any arguments, between `min` and `max` of them.
#[derive(Debug, PartialEq)]
struct AnyArgs(&'static str, usize, usize);

impl FunctionArgs for AnyArgs {
fn accepts_any_args(&self) -> bool {
self.1 <= self.2
}

fn accepts_arity(&self, n: usize) -> bool {
(self.1..=self.2).contains(&n)
}
}

fn summary(name: &str, arg_types: Vec<LogicalType>) -> FunctionSummary {
FunctionSummary {
name: name.into(),
Expand Down Expand Up @@ -432,6 +480,64 @@ mod tests {
assert_eq!(found(&registry, "p", &args), Some("p_bigint"));
}

#[test]
fn test_resolve_any_args_after_declared_overloads() {
let varchar = LogicalType::Varchar(None, CharLengthUnits::Characters);
let found = |registry: &FunctionRegistry<AnyArgs>, name: &str, args: &[LogicalType]| {
registry
.resolve(name, &args.iter())
.unwrap()
.map(|(_, v)| v.0)
};
let mut registry = FunctionRegistry::default();
// A declared overload: `AnyArgs(_, 1, 0)` does not accept any args.
registry.insert(
summary("m", vec![LogicalType::Bigint, LogicalType::Bigint]),
AnyArgs("m_bigint", 1, 0),
);
// Variadic: its declared parameter types are never used for resolution.
registry.insert(
summary("m", vec![varchar.clone()]),
AnyArgs("m_any", 1, usize::MAX),
);
registry.insert(summary("z", vec![]), AnyArgs("z_two", 2, 2));

// The declared overload wins whenever it accepts the arguments.
let ints = [LogicalType::Integer, LogicalType::Bigint];
assert_eq!(found(&registry, "m", &ints), Some("m_bigint"));
// Otherwise the any-args function takes them, whatever their types and count.
let mixed = [LogicalType::Integer, varchar.clone()];
assert_eq!(found(&registry, "m", &mixed), Some("m_any"));
let dates = [
LogicalType::Date,
LogicalType::DateTime,
LogicalType::SqlNull,
];
assert_eq!(found(&registry, "m", &dates), Some("m_any"));
assert_eq!(
found(&registry, "m", &[LogicalType::Boolean]),
Some("m_any")
);
// A one-argument call no longer matches the summary's single VARCHAR exactly.
assert_eq!(
found(&registry, "m", std::slice::from_ref(&varchar)),
Some("m_any")
);
assert_eq!(found(&registry, "m", &[]), None);
// The arity is checked by the function, not by its summary.
assert_eq!(found(&registry, "z", &[]), None);
assert_eq!(found(&registry, "z", &ints), Some("z_two"));
assert_eq!(found(&registry, "z", &dates), None);

// Two any-args functions of one name that take the arguments are ambiguous.
registry.insert(summary("z", vec![varchar]), AnyArgs("z_more", 2, 3));
assert!(matches!(
registry.resolve("z", &ints.iter()),
Err(DatabaseError::AmbiguousFunction(_))
));
assert_eq!(found(&registry, "z", &dates), Some("z_more"));
}

#[test]
fn test_check_arg_types_rejects_length_and_precision() {
let check = |ty: LogicalType| summary("f", vec![ty]).check_arg_types().is_ok();
Expand Down
55 changes: 54 additions & 1 deletion src/expression/function/scala.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,15 @@
// limitations under the License.

use crate::errors::DatabaseError;
use crate::expression::function::FunctionSummary;
use crate::expression::function::{FunctionArgs, FunctionSummary};
use crate::expression::TypeCast;
use crate::planner::ExprRef;
use crate::planner::MetaArena;
use crate::types::tuple::Input;
use crate::types::value::DataValue;
use crate::types::LogicalType;
use kite_sql_serde_macros::ReferenceSerialization;
use std::borrow::Cow;
use std::fmt::Debug;
use std::hash::{Hash, Hasher};
use std::ops::Deref;
Expand Down Expand Up @@ -75,10 +77,61 @@ pub trait ScalarFunctionImpl: Debug + Send + Sync {
fn return_type(&self) -> &LogicalType;

fn summary(&self) -> &FunctionSummary;

/// Whether the function takes its arguments as they are, of any type, instead of by the
/// parameter types in its [`summary`](Self::summary).
///
/// Such a function is resolved only when no overload of the same name accepts the
/// arguments by their declared types. Its arguments are not cast, so
/// [`eval`](Self::eval) handles every argument type, and its summary only identifies it
/// (for example when a plan is decoded). The default implementation returns `false`.
fn accepts_any_args(&self) -> bool {
false
}

/// Whether a function that [`accepts_any_args`](Self::accepts_any_args) takes `n`
/// arguments, for example `n >= 1` for a variadic function.
///
/// The default implementation accepts the number of parameters in its summary.
fn accepts_arity(&self, n: usize) -> bool {
self.summary().arg_types.len() == n
}

/// Returns the result type of a call with arguments of `arg_types`.
///
/// Only called for a function that [`accepts_any_args`](Self::accepts_any_args), whose
/// result type may depend on its arguments. The default implementation returns
/// [`return_type`](Self::return_type).
fn return_type_for(&self, _arg_types: &[LogicalType]) -> LogicalType {
self.return_type().clone()
}
}

impl FunctionArgs for Arc<dyn ScalarFunctionImpl> {
fn accepts_any_args(&self) -> bool {
ScalarFunctionImpl::accepts_any_args(self.as_ref())
}

fn accepts_arity(&self, n: usize) -> bool {
ScalarFunctionImpl::accepts_arity(self.as_ref(), n)
}
}

impl ScalarFunction {
pub fn summary(&self) -> &FunctionSummary {
self.inner.summary()
}

/// Returns the result type of this call.
pub(crate) fn return_type<A: MetaArena + ?Sized>(&self, arena: &A) -> Cow<'_, LogicalType> {
if !self.inner.accepts_any_args() {
return Cow::Borrowed(self.inner.return_type());
}
let arg_types = self
.args
.iter()
.map(|arg| arg.return_type(arena).into_owned())
.collect::<Vec<_>>();
Cow::Owned(self.inner.return_type_for(&arg_types))
}
}
4 changes: 3 additions & 1 deletion src/expression/function/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
// limitations under the License.

use crate::errors::DatabaseError;
use crate::expression::function::FunctionSummary;
use crate::expression::function::{FunctionArgs, FunctionSummary};
use crate::planner::MetaArena;
use crate::planner::{ExprRef, TableArena};
use crate::types::tuple::{Schema, Tuple};
Expand Down Expand Up @@ -46,6 +46,8 @@ pub struct TableFunctionCatalog {
pub(crate) inner: ArcTableFunctionImpl,
}

impl FunctionArgs for TableFunctionCatalog {}

impl PartialEq for TableFunction {
fn eq(&self, other: &Self) -> bool {
self.summary() == other.summary()
Expand Down
4 changes: 1 addition & 3 deletions src/expression/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -504,9 +504,7 @@ impl TypeCast for ScalarExpression {
.map(|expr| expr.return_type(arena).into_owned())
.collect(),
)),
ScalarExpression::ScalaFunction(ScalarFunction { inner, .. }) => {
Cow::Borrowed(inner.return_type())
}
ScalarExpression::ScalaFunction(function) => function.return_type(arena),
}
}

Expand Down
Loading
Loading