From 61821bfdcd3845a21f451892c310ae23074ed49b Mon Sep 17 00:00:00 2001 From: Alex Skinner Date: Sun, 6 Dec 2026 02:36:59 +0000 Subject: [PATCH] feat(function): let scalar functions accept any arguments Function lookup (#418) resolves a call by the parameter types a function declares, so a function such as GREATEST(a, b, ...) or CONCAT_WS(sep, ...) that takes any number of arguments of mixed types cannot be registered, and its result type cannot follow its arguments. Add three default methods to `ScalarFunctionImpl`: - `accepts_any_args()`: the function takes its arguments as they are. - `accepts_arity(n)`: whether it takes `n` arguments. - `return_type_for(&[LogicalType])`: its result type for those arguments. `FunctionRegistry::resolve` still tries the declared overloads first, so existing functions resolve as before. Only when none accepts the call is a function of that name that accepts any arguments used; two such functions that both accept the call are reported as `AmbiguousFunction`. The binder does not cast the arguments of such a function, and the result type is read through `ScalarFunction::return_type` when binding and evaluating. Item 1 of #419. --- src/binder/expr.rs | 4 +- src/expression/evaluator.rs | 5 +- src/expression/function/mod.rs | 110 +++++++++++++++++++++++++- src/expression/function/scala.rs | 55 ++++++++++++- src/expression/function/table.rs | 4 +- src/expression/mod.rs | 4 +- tests/macros-test/src/main.rs | 130 +++++++++++++++++++++++++++++++ 7 files changed, 302 insertions(+), 10 deletions(-) diff --git a/src/binder/expr.rs b/src/binder/expr.rs index 31f6b5ec7..c2f20476c 100644 --- a/src/binder/expr.rs +++ b/src/binder/expr.rs @@ -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), diff --git a/src/expression/evaluator.rs b/src/expression/evaluator.rs index ba2a287fd..721a2e64d 100644 --- a/src/expression/evaluator.rs +++ b/src/expression/evaluator.rs @@ -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 { diff --git a/src/expression/function/mod.rs b/src/expression/function/mod.rs index cc5a84cb1..b084a8684 100644 --- a/src/expression/function/mod.rs +++ b/src/expression/function/mod.rs @@ -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(Vec<(FunctionSummary, V)>); @@ -109,6 +124,12 @@ impl FunctionRegistry { 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( &self, name: &str, @@ -117,14 +138,16 @@ impl FunctionRegistry { where T: Borrow, I: ExactSizeIterator + 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) @@ -159,6 +182,15 @@ impl FunctionRegistry { 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))) } @@ -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) -> FunctionSummary { FunctionSummary { name: name.into(), @@ -432,6 +480,64 @@ mod tests { assert_eq!(found(®istry, "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, 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(®istry, "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(®istry, "m", &mixed), Some("m_any")); + let dates = [ + LogicalType::Date, + LogicalType::DateTime, + LogicalType::SqlNull, + ]; + assert_eq!(found(®istry, "m", &dates), Some("m_any")); + assert_eq!( + found(®istry, "m", &[LogicalType::Boolean]), + Some("m_any") + ); + // A one-argument call no longer matches the summary's single VARCHAR exactly. + assert_eq!( + found(®istry, "m", std::slice::from_ref(&varchar)), + Some("m_any") + ); + assert_eq!(found(®istry, "m", &[]), None); + // The arity is checked by the function, not by its summary. + assert_eq!(found(®istry, "z", &[]), None); + assert_eq!(found(®istry, "z", &ints), Some("z_two")); + assert_eq!(found(®istry, "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(®istry, "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(); diff --git a/src/expression/function/scala.rs b/src/expression/function/scala.rs index 9160fb15d..e81325768 100644 --- a/src/expression/function/scala.rs +++ b/src/expression/function/scala.rs @@ -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; @@ -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 { + 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(&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::>(); + Cow::Owned(self.inner.return_type_for(&arg_types)) + } } diff --git a/src/expression/function/table.rs b/src/expression/function/table.rs index 891190c00..604fa9bdf 100644 --- a/src/expression/function/table.rs +++ b/src/expression/function/table.rs @@ -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}; @@ -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() diff --git a/src/expression/mod.rs b/src/expression/mod.rs index c8120981f..bea55bc95 100644 --- a/src/expression/mod.rs +++ b/src/expression/mod.rs @@ -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), } } diff --git a/tests/macros-test/src/main.rs b/tests/macros-test/src/main.rs index 6d33a1c4c..bf1c95967 100644 --- a/tests/macros-test/src/main.rs +++ b/tests/macros-test/src/main.rs @@ -3257,5 +3257,135 @@ mod test { Ok(()) } + + /// `greatest(a, b, ...)`: one or more arguments of any comparable types, NULL if any + /// argument is NULL, typed by the widest argument type. + #[derive(Debug)] + struct Greatest { + summary: FunctionSummary, + } + + impl Greatest { + fn new() -> std::sync::Arc { + std::sync::Arc::new(Self { + summary: FunctionSummary { + name: "greatest".into(), + // Identifies the function only: calls are not resolved by it. + arg_types: vec![LogicalType::SqlNull], + }, + }) + } + } + + impl ScalarFunctionImpl for Greatest { + fn eval( + &self, + args: &[kite_sql::planner::ExprRef], + arena: &(dyn MetaArena + '_), + tuple: Option<&dyn kite_sql::types::tuple::Input>, + ) -> Result { + use kite_sql::expression::TypeCast; + + let arg_types = args + .iter() + .map(|arg| arena.expression(*arg).return_type(arena).into_owned()) + .collect::>(); + let ty = self.return_type_for(&arg_types); + let mut greatest: Option = None; + for arg in args { + let value = arena.expression(*arg).eval(arena, tuple)?.into_owned(); + if value.is_null() { + return Ok(DataValue::Null); + } + let value = value.cast(&ty)?; + if greatest.as_ref().is_none_or(|max| value > *max) { + greatest = Some(value); + } + } + Ok(greatest.unwrap_or(DataValue::Null)) + } + + fn monotonicity(&self) -> Option { + None + } + + fn return_type(&self) -> &LogicalType { + &LogicalType::SqlNull + } + + fn summary(&self) -> &FunctionSummary { + &self.summary + } + + fn accepts_any_args(&self) -> bool { + true + } + + fn accepts_arity(&self, n: usize) -> bool { + n >= 1 + } + + fn return_type_for(&self, arg_types: &[LogicalType]) -> LogicalType { + arg_types.iter().fold(LogicalType::SqlNull, |ty, arg| { + LogicalType::max_logical_type(&ty, arg) + .map(Cow::into_owned) + .unwrap_or(ty) + }) + } + } + + #[test] + fn test_load_function_accepts_any_args() -> Result<(), DatabaseError> { + let temp_dir = TempDir::new().expect("create temp dir for function test"); + let mut database = DataBaseBuilder::path(temp_dir.path()).build_rocksdb()?; + database.load(kite_sql::db::CatalogKind::ScalarFunction(Greatest::new()))?; + + database.ddl( + "create table t_greatest (id int primary key, a int, b bigint, c double, \ + d date, e datetime, s varchar(10))", + )?; + drain_result_iter(database.run( + "insert into t_greatest values \ + (1, 3, 7, 2.5, '2026-01-02', '2026-01-01 10:00:00', 'kite'), \ + (2, 9, null, 1.5, '2026-03-04', '2026-05-06 07:08:09', 'sql')", + )?)?; + + // Any count of arguments, of any types, reaches the function uncast; the result type + // follows the arguments. + let rows = collect_result_tuples(database.run( + "select greatest(a), greatest(a, b), greatest(a, c, 4, 1, 0, 2), greatest(d, e), \ + greatest(s, 'kitesql') from t_greatest order by id", + )?)?; + assert_eq!(rows.len(), 2); + assert_eq!(rows[0][0], DataValue::Int32(3)); + assert_eq!(rows[0][1], DataValue::Int64(7)); + assert_eq!(rows[0][2], DataValue::Float64(4.0.into())); + // `DATE` and `DATETIME` arguments compare as `DATETIME`. + let expected = + collect_result_tuples(database.run("select cast('2026-01-02 00:00:00' as datetime)")?)?; + assert_eq!(rows[0][3], expected[0][0]); + assert_eq!(rows[0][4].utf8(), Some("kitesql")); + assert_eq!(rows[1][0], DataValue::Int32(9)); + // A NULL argument makes the result NULL. + assert_eq!(rows[1][1], DataValue::Null); + assert_eq!(rows[1][2], DataValue::Float64(9.0.into())); + + // The result type is used when binding the rest of the statement. + let rows = collect_result_tuples( + database.run("select id from t_greatest where greatest(a, b) + 1 > 7 order by id")?, + )?; + assert_eq!(rows.len(), 1); + assert_eq!(rows[0][0], DataValue::Int32(1)); + + // The function rejects an arity it does not accept. + assert!(matches!( + database + .run("select greatest()") + .and_then(collect_result_tuples), + Err(DatabaseError::FunctionNotFound { .. }) + )); + + Ok(()) + } } // GRCOV_EXCL_STOP