Repository navigation
feat(function): resolve function arguments by implicit cast - #418
Conversation
Function lookup required an exact signature match, so e.g. `upper()` on a VARCHAR(20) column, `upper(null)` or an INT argument to a BIGINT parameter failed with "function not found". - Store functions in a `FunctionRegistry` kept sorted by `FunctionSummary`, so overloads of one name are adjacent and ordered narrow to wide. - Reorder `LogicalType` variants to follow the implicit cast direction. - `resolve` scans the overloads of a name once: an exact signature wins, otherwise the first overload whose parameters accept every argument by `can_implicit_cast` (any VARCHAR also matches an unbounded VARCHAR). - The binder casts non-exact arguments to the declared parameter types. - Reject function parameter types that declare a length or precision. Closes #412
|
@alexskinner |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #418 +/- ##
==========================================
+ Coverage 92.98% 93.03% +0.05%
==========================================
Files 283 283
Lines 40118 40489 +371
==========================================
+ Hits 37304 37670 +366
- Misses 2814 2819 +5
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
`accepts` now limits `can_implicit_cast` to the narrow -> wide direction of the `LogicalType` order (`arg <= param`). With the current order this only excludes the lossy `DATETIME`/`TIMESTAMP -> DATE` casts, and an exact signature, when registered, is always the first accepting overload, so `resolve` no longer tracks an exact match and a fallback separately. Also simplify how the binder builds the argument type iterator.
alexskinner
left a comment
There was a problem hiding this comment.
Hi @KKould,
Thanks for picking this up, and safe travels. I built #418 (b8e4be5) and ran it against KiteSQL-MySQL, the dialect crate that motivated #412. It covers what we need from #412 and fixes the cases listed there. Below are a few observations and suggestions from testing, for you to take or leave as you see fit.
Test results
- KiteSQL at the PR head:
cargo test --all --features spill,sqlite-parsergives 660 passed, 0 failed, 2 ignored. This includes the new registry unit tests andtest_load_function_resolves_by_implicit_cast. The sqllogictest runner passes all 198 files intests/slt. - KiteSQL-MySQL (default features) with
kite_sqlpatched to the PR head: 43 passed, 0 failed. The same 43 pass against main, so nothing in our existing suite breaks. - I also loaded the MySQL functions into a small probe with columns
s VARCHAR(20),c CHAR(3),n INTandd DECIMAL(10,2), comparing main (2ce67e6) with the PR:
| Query | main | #418 |
|---|---|---|
upper(s), length(s), replace(s, 'a', 'x'), left(s, 1), hex(s) |
function not found | ok |
upper(null), abs(null), round(null) |
function not found | NULL |
plus1(n), plus1(5) with plus1(BIGINT) loaded |
function not found | ok |
upper(c), concat(s, c) (CHAR argument) |
function not found | function not found |
hex(d), round(d) (DECIMAL(10,2) argument) |
function not found | function not found |
Database::load of a function declared with VARCHAR(20), CHAR(3) or DECIMAL(10,2) |
ok | error: "must not declare a length or precision" |
What #412 asked for, and what #418 does
- Implicit resolution for
VARCHAR(n)->VARCHAR,SqlNull, and integer widening: covered, and the binder adds theTypeCasts (src/binder/expr.rs:764). - Most specific overload: approximated by the sort order. That works for single-argument numeric overloads.
- Ties: #412 floated reporting an error; #418 takes the first match instead, which the PR notes. A couple of examples below.
- Storage format and registration: #412 assumed both would stay as they are. Here
LogicalTypeis reordered, andDatabase::loadnow rejects some parameter types. - Database-wide functions, with per-dialect sets and UDAFs left for later: agreed. Neither is needed for KiteSQL-MySQL now.
Observations and suggestions
- The
LogicalTypereorder changes the on-disk format, which may be avoidable.ReferenceSerializationwrites an enum's position in the source as its tag (kite_sql_serde_macros/src/reference_serialization.rs:166-167), and an unknown tag hitsunreachable!()(:239). A data directory written by main and opened with #418 panics while loading the table catalog (src/serdes/option.rs:50, fromColumnDesc::decode). A directory written by #418 and opened with main fails withUnexpectedEof. The cast table already treats these codes as fixed ABI (src/types/evaluator/cast.rs:79-80). The reorder only exists so the derivedOrdfollows the cast direction. One option would be a rank local to the registry, which gives the same ordering without touching the stored tags:
/// Narrow -> wide implicit cast order, used only to sort function overloads.
fn cast_rank(ty: &LogicalType) -> u8 {
match ty {
LogicalType::SqlNull => 0,
LogicalType::Boolean => 1,
// ... Tinyint .. Double: 2 .. 11, same as today ...
LogicalType::Date => 12,
LogicalType::DateTime => 13,
LogicalType::TimeStamp(..) => 14,
LogicalType::Time(..) => 15,
LogicalType::Char(..) => 16,
LogicalType::Varchar(..) => 17,
LogicalType::Decimal(..) => 18,
LogicalType::Tuple(_) => 19,
LogicalType::Varbinary(_) => 20,
}
}Then FunctionRegistry sorts and searches with (s.name, s.arg_types.iter().map(cast_rank)), and accepts compares cast_rank(arg) <= cast_rank(param) instead of arg <= param. FunctionSummary can drop the Ord derive it gained in this PR.
Explicit discriminants also work, but need more care. The derive macro writes the variant's position in the source, not its discriminant, so keeping main's declaration order and giving explicit discriminants in the cast order (Date = 12, DateTime = 13, TimeStamp = 14, Time = 15, Char = 16, Varchar = 17, plus Decimal = 18, Tuple = 19, Varbinary = 20 so the later variants don't collide) gives the PR's ordering. It needs #[repr(u8)]. I tried this on top of main: data directories round-trip both ways with main, and the Ord results match the PR head (Char < Date is false, TimeStamp < Time is true). The local rank keeps LogicalType untouched, which might be the simpler of the two, but you know the codebase best.
- Arguments that carry a length or precision don't match their unbounded parameter. The special case in
accepts(src/expression/function/mod.rs:108-110) only coversVARCHAR. For the other types,Option's derived order putsNonebeforeSome(_), so e.g.Decimal(Some(10), Some(2)) <= Decimal(None, None)is false. At the same time,check_arg_types(:31-50) stops anyone registering aDECIMAL(p, s)overload. So these columns can't reach a function at all. Withp_dec(DECIMAL)loaded:
create table t (id int primary key, d decimal(10,2), vb varbinary(8));
select p_dec(d) from t; -- function `p_dec` not found
select p_dec(cast(d as decimal)) from t; -- okTIME(3), TIMESTAMP(3) and VARBINARY(8) columns behave the same way against TIME, TIMESTAMP and VARBINARY parameters. MySQL columns declared DECIMAL(10,2) or VARBINARY(8) keep their precision and length, so this affects hex(d) and round(d) in KiteSQL-MySQL. One way would be to extend the special case to the same type with an unbounded parameter:
matches!((arg, param),
(LogicalType::Varchar(..), LogicalType::Varchar(None, _))
| (LogicalType::Varbinary(..), LogicalType::Varbinary(None))
| (LogicalType::Decimal(..), LogicalType::Decimal(None, None))
| (LogicalType::Time(..), LogicalType::Time(None))
| (LogicalType::TimeStamp(..), LogicalType::TimeStamp(None, _)))Another would be to drop the registration check and let exact declared signatures work.
- Lossy
TIMESTAMP/DATETIME->TIMEis used for resolution. The new order putsTimeStampbeforeTime(src/types/mod.rs:70-71), so the direction check lets it through. With onlyk_time(TIME)loaded:
select k_time(ts) from t; -- ts TIMESTAMP '2026-01-02 03:04:05'
-- the implementation receives Time32(03:04:05)DATETIME does the same. The -> DATE direction is correctly excluded, but this one drops the date part just as silently. If that's not intended, it could be excluded explicitly in accepts.
- NULL literals and ties pick an overload without reporting it. With
n_str(VARCHAR)andn_str(BIGINT)both loaded,select n_str(null)calls the BIGINT overload, whichever order they were registered in. Withm(BIGINT, DOUBLE)andm(DOUBLE, BIGINT)loaded,select m(1, 2)callsm(BIGINT, DOUBLE). #412 suggested an error for ties. Picking the first seems reasonable for a first version; it might be worth keeping the removedTODOaboutSqlNullso the behaviour stays documented. One visible effect:round(null)andabs(null)have result typeTinyint.
Smaller points:
cast_function_argsrelies onExprRef::type_castbeing a no-op when the types are equal, which it is. A short comment would help.FunctionRegistryispubin a public module but only haspub(crate)methods. It could bepub(crate)too.
Things that could be follow-ups
CHARarguments toVARCHARparameters (upper(c)), sincecan_implicit_casthas noCHAR -> VARCHAR. The new slt file documents this.- Numeric or date arguments to
VARCHARparameters (e.g.concat(n, s)in MySQL), because those aren't implicit casts in core. - Reporting ties, a per-dialect function set, UDAFs, and variadic functions.
Of the points above, 1 and 2 are the ones that matter most for us. The direction looks good to me. Thanks again for taking #412 on.
- Keep `LogicalType` in its serialized order and sort overloads by a registry-local `cast_rank`, so existing data directories stay readable. - Match a bounded argument (`DECIMAL(10,2)`, `VARBINARY(8)`, `TIME(3)`, `TIMESTAMP(3)`) to the unbounded parameter of the same type via `LogicalType::unbounded`, and reject non-unbounded parameter types at registration. - Exclude the lossy `DATETIME`/`TIMESTAMP -> DATE`/`TIME` casts from resolution. - Allow the implicit cast `CHAR -> VARCHAR`. - A NULL argument prefers the widest parameter, with strings ranked last. - Report incomparable multi-argument overloads as `AmbiguousFunction`.
|
@alexskinner Thank you for the comment.
|
What problem does this PR solve?
Function lookup in
bind_function_callrequired an exact signature match, so an argument whose type was not exactly the declared parameter type missed:upper(s)on aVARCHAR(20)column,upper(null), or anINTargument to aBIGINTparameter all failed withfunction not found. This also made functions registered from another crate throughDatabase::loadhard to use.Issue link: close #412
What is changed and how it works?
ScalaFunctions/TableFunctionsare now aFunctionRegistry<V>: aVec<(FunctionSummary, V)>kept sorted on insert by name, then by thecast_rankof the argument types, a narrow -> wide order local to the registry.LogicalTypeand its serialized order are unchanged.insert/get/valueskeep their previous semantics, so storage decoding still uses an exactget.FunctionRegistry::resolve(name, &arg_types)considers the overloads ofnamewith the same arity whose parameters accept every argument: either the same type without its length or precision (LogicalType::unbounded, e.g.DECIMAL(10,2)->DECIMAL), orLogicalType::can_implicit_castlimited to the narrow -> wide direction ofcast_rank, which excludes the lossyDATETIME/TIMESTAMP -> DATE/TIMEcasts. It picks the overload that is at least as good at every argument: the narrowest parameter for a typed argument, the widest for a NULL argument. Strings rank last, so NULL favoursVARCHAR, as MySQL treats a NULL literal as a string, andabs(null)resolves toabs(DOUBLE). If no overload is at least as good as all others, binding fails withDatabaseError::AmbiguousFunction. Resolution is a single pass over the name's overloads; a second pass is only needed for a multi-argument call with a NULL argument. Argument types are borrowed as an iterator, so nothing is collected per call.LogicalType::can_implicit_castnow allowsCHARto an unboundedVARCHAR, sinceCHARdoes not keep trailing spaces, soupper(c)on aCHARcolumn works.TypeCastto the declared parameter type, so an implementation always sees the types it declared (e.g.absdoes not cast internally).Database::loadrejects parameter types that are not unbounded:CHAR,VARCHAR(n),VARCHARin octets,VARBINARY(n),TIME(p),TIMESTAMP(p),DECIMAL(p, s). Built-in functions are unaffected.Code changes
Check List
Tests
Side effects
Note for reviewer
Database::load, and the publicLogicalType::can_implicit_castnow returns true forCHAR -> VARCHAR. The on-disk format is unchanged.cast_rank. With bothDOUBLEandDECIMALoverloads it picksDECIMAL, where MySQL would type the result asDOUBLE; the value is NULL either way.HashMaphit; it only runs at bind time. No TPC-C numbers yet.