Skip to content

feat(function): resolve function arguments by implicit cast - #418

Merged
KKould merged 3 commits into
mainfrom
feat/function-implicit-cast
Dec 5, 2026
Merged

KKould merged 3 commits into
mainfrom
feat/function-implicit-cast

Conversation

@KKould

@KKould KKould commented Dec 3, 2026 •

Copy link
Copy Markdown
Member

What problem does this PR solve?

Function lookup in bind_function_call required an exact signature match, so an argument whose type was not exactly the declared parameter type missed: upper(s) on a VARCHAR(20) column, upper(null), or an INT argument to a BIGINT parameter all failed with function not found. This also made functions registered from another crate through Database::load hard to use.

Issue link: close #412

What is changed and how it works?

  • Sorted registry. ScalaFunctions / TableFunctions are now a FunctionRegistry<V>: a Vec<(FunctionSummary, V)> kept sorted on insert by name, then by the cast_rank of the argument types, a narrow -> wide order local to the registry. LogicalType and its serialized order are unchanged. insert / get / values keep their previous semantics, so storage decoding still uses an exact get.
  • Resolution. FunctionRegistry::resolve(name, &arg_types) considers the overloads of name with 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), or LogicalType::can_implicit_cast limited to the narrow -> wide direction of cast_rank, which excludes the lossy DATETIME/TIMESTAMP -> DATE/TIME casts. 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 favours VARCHAR, as MySQL treats a NULL literal as a string, and abs(null) resolves to abs(DOUBLE). If no overload is at least as good as all others, binding fails with DatabaseError::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.
  • CHAR -> VARCHAR. LogicalType::can_implicit_cast now allows CHAR to an unbounded VARCHAR, since CHAR does not keep trailing spaces, so upper(c) on a CHAR column works.
  • Casts. The binder wraps each non-exact argument in a TypeCast to the declared parameter type, so an implementation always sees the types it declared (e.g. abs does not cast internally).
  • Registration check. Database::load rejects parameter types that are not unbounded: CHAR, VARCHAR(n), VARCHAR in octets, VARBINARY(n), TIME(p), TIMESTAMP(p), DECIMAL(p, s). Built-in functions are unaffected.

Code changes

  • Has Rust code change
  • Has CI related scripts change

Check List

Tests

  • Unit test
  • Integration test
  • Manual test (add detailed scripts or steps below)
  • No code

Side effects

  • Performance regression: Consumes more CPU
  • Performance regression: Consumes more Memory
  • Breaking backward compatibility

Note for reviewer

  • Breaking: registering a function whose parameter type is not unbounded now fails at Database::load, and the public LogicalType::can_implicit_cast now returns true for CHAR -> VARCHAR. The on-disk format is unchanged.
  • NULL arguments: NULL takes the widest parameter by cast_rank. With both DOUBLE and DECIMAL overloads it picks DECIMAL, where MySQL would type the result as DOUBLE; the value is NULL either way.
  • Lookup cost: the exact lookup is a binary search on the name plus a scan of that name's overloads instead of a HashMap hit; it only runs at bind time. No TPC-C numbers yet.
  • Functions stay database-wide; no per-dialect function set and no UDAF extension point in this PR.

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
@KKould KKould self-assigned this Dec 3, 2026
@KKould
KKould requested a review from alexskinner December 3, 2026 20:06
@KKould

KKould commented Dec 3, 2026

Copy link
Copy Markdown
Member Author

@alexskinner
Apologies—I’ve been busy preparing for a trip, so I haven’t had much time to revise the code. This PR represents my re-evaluation of the current function implementation; it further simplifies the design while addressing the vast majority of the points raised in your issue. Could you take a look to see if it aligns with your expectations? I find it much easier to have a discussion when we have a concrete implementation to refer to.

@codecov

codecov Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.74055% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.03%. Comparing base (2ce67e6) to head (1442740).

Files with missing lines Patch % Lines
src/errors.rs 0.00% 3 Missing ⚠️
src/expression/function/mod.rs 99.40% 2 Missing ⚠️
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     
Flag Coverage Δ
rust 93.03% <98.74%> (+0.05%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/binder/expr.rs 94.09% <100.00%> (+0.12%) ⬆️
src/db.rs 94.13% <100.00%> (+0.02%) ⬆️
src/types/mod.rs 98.31% <100.00%> (+0.08%) ⬆️
src/expression/function/mod.rs 99.11% <99.40%> (+99.11%) ⬆️
src/errors.rs 93.21% <0.00%> (-1.01%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

`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 alexskinner left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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-parser gives 660 passed, 0 failed, 2 ignored. This includes the new registry unit tests and test_load_function_resolves_by_implicit_cast. The sqllogictest runner passes all 198 files in tests/slt.
  • KiteSQL-MySQL (default features) with kite_sql patched 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 INT and d 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 the TypeCasts (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 LogicalType is reordered, and Database::load now 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

  1. The LogicalType reorder changes the on-disk format, which may be avoidable. ReferenceSerialization writes an enum's position in the source as its tag (kite_sql_serde_macros/src/reference_serialization.rs:166-167), and an unknown tag hits unreachable!() (:239). A data directory written by main and opened with #418 panics while loading the table catalog (src/serdes/option.rs:50, from ColumnDesc::decode). A directory written by #418 and opened with main fails with UnexpectedEof. The cast table already treats these codes as fixed ABI (src/types/evaluator/cast.rs:79-80). The reorder only exists so the derived Ord follows 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.

  1. 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 covers VARCHAR. For the other types, Option's derived order puts None before Some(_), 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 a DECIMAL(p, s) overload. So these columns can't reach a function at all. With p_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;   -- ok

TIME(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.

  1. Lossy TIMESTAMP/DATETIME -> TIME is used for resolution. The new order puts TimeStamp before Time (src/types/mod.rs:70-71), so the direction check lets it through. With only k_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.

  1. NULL literals and ties pick an overload without reporting it. With n_str(VARCHAR) and n_str(BIGINT) both loaded, select n_str(null) calls the BIGINT overload, whichever order they were registered in. With m(BIGINT, DOUBLE) and m(DOUBLE, BIGINT) loaded, select m(1, 2) calls m(BIGINT, DOUBLE). #412 suggested an error for ties. Picking the first seems reasonable for a first version; it might be worth keeping the removed TODO about SqlNull so the behaviour stays documented. One visible effect: round(null) and abs(null) have result type Tinyint.

Smaller points:

  • cast_function_args relies on ExprRef::type_cast being a no-op when the types are equal, which it is. A short comment would help.
  • FunctionRegistry is pub in a public module but only has pub(crate) methods. It could be pub(crate) too.

Things that could be follow-ups

  • CHAR arguments to VARCHAR parameters (upper(c)), since can_implicit_cast has no CHAR -> VARCHAR. The new slt file documents this.
  • Numeric or date arguments to VARCHAR parameters (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`.
@KKould

KKould commented Dec 5, 2026

Copy link
Copy Markdown
Member Author

@alexskinner Thank you for the comment.

  1. LogicalType reorder changes the on-disk format: fixed. LogicalType is back to its original order. Overloads are sorted by cast_rank, a rank local to the registry, and FunctionSummary no longer derives Ord.
  2. Bounded arguments don't match unbounded parameters: fixed. LogicalType::unbounded() drops the length or precision, so DECIMAL(10,2), VARBINARY(8), TIME(3) and TIMESTAMP(3) match DECIMAL, VARBINARY, TIME and TIMESTAMP. The TIMESTAMP zone flag must still match. The registration check is now is_unbounded(), which also rejects a VARCHAR declared in octets.
  3. Lossy TIMESTAMP/DATETIME -> TIME: fixed. cast_rank puts TIME before DATETIME/TIMESTAMP, so the narrow -> wide check excludes both -> DATE and -> TIME.
  4. NULL and ties pick silently: changed.
    • A NULL argument takes the widest parameter, and strings rank last. This matches MySQL, where a NULL literal has a string result type: abs(null) -> abs(DOUBLE), n_str(null) -> n_str(VARCHAR).
    • Multi-argument overloads where neither is better are rejected with AmbiguousFunction, e.g. m(BIGINT, DOUBLE) / m(DOUBLE, BIGINT) called as m(1, 2).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

RFC: resolve function arguments by implicit cast, so externally registered functions are usable

2 participants