Skip to content

Call Java functions from SQL as scalar UDFs - #49

Merged
wudidapaopao merged 4 commits into
chdb-io:mainfrom
wudidapaopao:scalar-udf
Dec 2, 2026
Merged

wudidapaopao merged 4 commits into
chdb-io:mainfrom
wudidapaopao:scalar-udf

Conversation

@wudidapaopao

@wudidapaopao wudidapaopao commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Java functions can now be called from SQL as scalar user-defined functions. This uses the scalar function C ABI added in chdb-io/chdb-core#352, first released in v26.11.2-rc.3. The API follows duckdb-java's DuckDBFunctions.scalarFunction() builder, and it is the same feature chdb-io/chdb-go#92 adds to Go.

// Row style, in chdb-jdbc (no Arrow dependency):
RegisteredFunction f = ChdbFunctions.scalarFunction()
    .withName("plus_one").withParameter("Int64").withReturnType("Int64")
    .withFunction((Long x) -> x + 1)      // also Supplier, BiFunction, or withRowFunction(args -> ...)
    .register(connection);                // any chDB Connection, or one that wraps it

// Batch style, in chdb-arrow:
ArrowFunctions.scalarFunction()
    .withName("scale").withParameter("Float64").withReturnType("Float64")
    .withVectorizedFunction((VectorSchemaRoot args, BufferAllocator alloc) -> /* a FieldVector */)
    .register(connection);
  • Flags. Both builders have withVolatile(), withSpecialNullHandling() and withBinaryStrings().
  • Dropping. register returns a RegisteredFunction. Its close() drops the function only if the name still belongs to that registration. ChdbFunctions.dropScalarFunction(name) needs no connection.
  • Support check. isScalarFunctionSupported() checks support without trying a registration.
  • JDBC and pools. As in duckdb-java, register(Connection) unwraps to ChdbConnection, so plain JDBC code and pool proxies work.
  • Process-wide. chDB keeps functions for the whole process. docs/scalar-functions.md explains how this differs from DuckDB's per-connection functions.

Design

Threading

  • The shim runs the Java function directly on the engine thread.
  • Each engine thread is attached as a daemon on its first call, named after the engine thread, and detached through a pthread key when it exits.
  • No Java thread has to service anything, so a synchronous statement can never block on its own functions.

Calls back into chDB

  • This is the only possible deadlock. The driver refuses statements, connects, closes, registrations and drops from inside a function before taking any lock.
  • The shim also refuses every engine entry point on that thread, because chDB can run the function on the very thread that holds the connection's lock.

Exceptions

  • Nothing thrown in Java reaches the engine. Every Throwable becomes the query's error, as Class: message; caused by ....
  • An exception already pending on the thread is set aside around each upcall.
  • Each batch runs in its own JNI local frame.

Memory

  • Row style: chDB's argument buffers are copied, and no pointers into them are kept. Results are built in native memory that their release callbacks free.
  • Arrow style: arguments are imported without copying, which moves chDB's array into Arrow Java. Results are exported with Arrow Java's own release callbacks. The allocator belongs to the registration and is closed when chDB destroys the function. A test checks that it holds 0 bytes after a drop.
  • The function's global reference is deleted in chDB's destroy, on whatever thread runs it. A failed registration frees everything itself.

Arrow and modules

  • chdb-jdbc keeps no Arrow dependency, matching the repo's module split. The C++ side copies buffers per Arrow format, and Java decodes them, using the declared type to resolve ambiguous formats.
  • chdb-arrow uses arrow-c-data, which it already depended on.

Older engines

  • The two functions are looked up with dlsym through the existing optional-symbol mechanism.
  • Against v26.11.1 the library loads and ordinary queries run, and register/drop throw SQLFeatureNotSupportedException (SQLSTATE 0A000) naming the minimum engine. Loading an older engine at all still needs the existing -Dchdb.skipEngineVersionCheck=true.

Type mapping (row style)

ClickHouse Java argument Accepted as result
Bool Boolean Boolean
Int8–Int64 Byte, Short, Integer, Long Byte, Short, Integer, Long, BigInteger
UInt8/16/32 Short, Integer, Long as Int64
UInt64, (U)Int128, (U)Int256 BigInteger as Int64 (decimal text when wider than 64 bits)
Float32, BFloat16, Float64 Float, Float, Double any Number
Decimal BigDecimal any Number or a String
String, FixedString String (byte[] with binary strings) String or byte[]
Enum String (the label) String
Date, Date32 LocalDate LocalDate
DateTime, DateTime64 Instant Instant, OffsetDateTime, ZonedDateTime
UUID UUID UUID or String
IPv4, IPv6 InetAddress InetAddress or String
Array, Tuple, Map List, Object[], Map Collection or array, Object[] or List, Map
JSON, Dynamic String String

Time, Time64 and Variant parameters are refused at registration in the row style.

Commits

  1. Pin chdb-core v26.11.2-rc.3. ⚠️ This is a pre-release engine. Keep this commit, or drop it and wait for a stable engine. It changes:

    • engine.properties: the tag and the four SHA-256s, which match GitHub's digests and the release's SHA256SUMS.
    • POMs: engine 26.11.2-rc.3 and version 1.2.0-SNAPSHOT, because 1.1.0 is released and a binding on an engine RC can only cut RCs.
    • chdb-jni/include/chdb.h: copied unchanged from the tarball.
    • The licence inventory, regenerated as licenses/engine-third-party-26.11.2-rc.3.tsv: 1038 entries instead of 1081. The MPL-2.0 webpki-roots 0.26.1 is gone; the 1.0.x copies that remain are CDLA-Permissive. The copyleft set therefore drops from eleven to ten, and LicenseInventoryIT, the licence text build-native.sh writes, and the docs are updated to match. Please include this in the compliance review.
  2. Add scalar functions written in Java.

    • Shim: the scalar function section in chdb_jni.cpp, the JNI-free chdb_jni_functions.{h,cpp}, arrow_c_abi.h, optional-symbol entries and harness tests.
    • The JNI ABI goes from 5 to 6. libpthread is now linked explicitly, as libdl already is, for the glibc 2.28 floor.
    • chdb-jdbc and chdb-arrow gain the builders and callbacks.
    • Docs: a new docs/scalar-functions.md, plus README sections.
  3. Name the Arrow batch method as duckdb-java does. ArrowScalarFunctionBuilder.withFunction becomes withVectorizedFunction. The row-style withFunction overloads already match duckdb-java.

  4. Test scalar functions without an engine, and fix what the tests found. Adds 31 unit tests, 9 chdb-arrow tests and 49 native-harness checks. They cover:

    • every integer width at its limits;
    • offsets and validity on every layout;
    • decimals, FixedString, and time zones;
    • nested containers, and zero-row batches;
    • the C Data layout of every encoder;
    • error causes and truncation;
    • the registration bookkeeping and the live counter;
    • the row callback;
    • Arrow batches with an allocator that checks every buffer is given back.

    Behaviour and locking are unchanged, apart from small refactors that make this logic reachable without the native library. These tests found two bugs, which this commit fixes:

    • A FixedString argument that is not valid UTF-8 reached the function with U+FFFD replacement characters. chDB rejects an invalid String but passes FixedString bytes through unchecked. The query now fails and points to withBinaryStrings(), as the javadoc already promised.
    • A zero-row UUID column without a data buffer threw NullPointerException.

Tests

Run locally on Linux x86_64 with JDK 21 against v26.11.2-rc.3:

Suite Before (pin commit) After
Unit, mvn -pl chdb-jdbc -am test 178 239 (61 new)
Integration, mvn -pl chdb-integration-tests -am verify ... 177 195 (18 new in ScalarFunctionIT)
Arrow, mvn -pl chdb-arrow -am test -Dchdb.arrow.it=true ... 30 48 (18 new)

All pass with 0 failures. Under the sanitizers:

  • the native harness passes 210 checks under ASan, UBSan and LSan;
  • 191 integration tests pass under UBSan with 0 reports.

The integration and Arrow tests assert chdb_version() = 26.11.2-rc.3.

The new tests cover:

  • each type mapping, and both NULL modes
  • volatile vs folded zero-argument functions
  • exceptions, checked exceptions, NPE and Error as query errors
  • bad types and built-in or duplicate names failing registration
  • drop, drop again and re-register
  • the 2M-row max_threads=8 sum
  • four parallel queries meeting at a barrier inside the function
  • visibility across connections, and survival across an engine restart
  • SQL inside a function being refused
  • live registrations returning to 0 after a drop

The existing CI jobs run every new test once the pin lands: four platforms × JDK 11/17/21/25, AlmaLinux 8 and UBSan. The only workflow edit is a step description. macOS, aarch64 and the other JDKs were not run locally.

Known limitations

  • Row-style cost. Buffers are copied and values boxed. For the 2M-row sum: built-in 3 ms, Arrow style 29 ms, row style 48 ms.
  • Indirect calls back into chDB. A function that hands work to another thread, which calls chDB, and then waits for it can still deadlock. This is documented.
  • Untested. The detach of an engine thread when it exits is not exercised by a test.

🤖 Generated with Claude Code

Note

Add Java scalar UDF support callable from SQL

Lets Java code register scalar functions that SQL queries can call. Batches arrive as Arrow C Data structs; a row-oriented path decodes each row, calls the Java function, and encodes results (RowFunctionCallback.java), while the optional chdb-arrow module offers vectorized, batch-at-a-time functions (ArrowFunctionCallback.java).

  • Adds a builder API (ChdbFunctions / ArrowFunctions.scalarFunction) supporting declared ClickHouse parameter and return types, NULL handling, volatility, and binary strings. Registration is JVM-wide and tracked by a process-wide registry.
  • All JNI entrypoints (query, connect, stream operations, shutdown) refuse calls made from a scalar-function callback thread, throwing SQLFeatureNotSupportedException (SQLState 0A000), to prevent deadlocks waiting on the invoking query.
  • Pins the engine to chDB Core v26.11.2-rc.3, bumps JNI ABI from 5 to 6, and bumps the project version to 1.2.0-SNAPSHOT.
  • Behavioral Change: requires the v26.11.2-rc.3 engine for the scalar-function ABI; branch releases are limited to 1.2.0-rc versions until a stable core is pinned.

Macroscope summarized 8403d3b.

wudidapaopao and others added 4 commits December 1, 2026 06:10
v26.11.2-rc.3 adds the scalar function ABI (chdb_create_scalar_function
and chdb_drop_scalar_function, chdb-core #352) and the
restrict_local_filesystem_access connection option (#349) over v26.11.1,
and syncs ClickHouse master twice (#314, #348); version() still reports
26.11.1.1. It is a chdb-core pre-release, so work plan 4.3 applies: a
binding on it is an RC. The engine change plus the capability it brings
make the next binding version 1.2.0, so the POMs move from the released
1.1.0 to 1.2.0-SNAPSHOT and only 1.2.0-rc.<n> can be cut from here.

- engine.properties and <chdb.engine.version>: version, tag, asset base
  and the four libchdb SHA-256s. They are the release API digests, and
  the release's SHA256SUMS agrees with them. All four downloaded
  tarballs match, and chdb_version() of the linux-x86_64 library returns
  26.11.2-rc.3, the CHDB_VERSION in all four headers.
- chdb-jni/include/chdb.h: copied unchanged from the release tarball.
  Against v26.11.1 it differs in CHDB_VERSION, the
  restrict_local_filesystem_access notes on chdb_connect and the new
  "Scalar User-Defined Functions" section. All four platform libraries
  export the same 64 chdb_* symbols: v26.11.1's 62 plus the two above.
- licenses/engine-third-party-26.11.2-rc.3.tsv: regenerated from this
  engine's system.licenses on linux-x86_64. 1038 entries against 1081:
  66 names left, 22 arrived, all permissive apart from two "Third-party
  notices" entries for components already there. The MPL-2.0 copy of
  webpki-roots (0.26.1) is no longer vendored; its 1.0.x copies are
  CDLA-Permissive-2.0. LicenseInventoryIT's known copyleft set, the
  licence README build-native.sh writes and docs/publishing.md drop it,
  so the set is ten.
- Comments and docs that state the pinned baseline. Findings section 2
  gains a column: at the tag the in-tree constant reads 26.11.1.

Re-read from the new assets rather than carried over: macOS minos is
11.0 (arm64) and 10.15 (x86_64), the engine's glibc floor is GLIBC_2.4
(x86_64) and GLIBC_2.17 (aarch64), and the wheels keep their tags.
run-signal-window-test.sh measure 3 reported hostHandlersAtSigDfl=0/0/0
and stress 6 survived 6 of 6 on Linux x86_64. The URL-settings check in
docs/memory.md holds on this engine. On linux-x86_64 the shim built in
manylinux_2_28 needs glibc 2.25, and the 178 unit, 177 integration and
30 Arrow tests pass against the staged pair.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
chdb-core v26.11.2-rc.3 can call a host function from SQL through
chdb_create_scalar_function and chdb_drop_scalar_function. This makes Java
functions callable that way, in two styles sharing one callback:

- chdb-jdbc: ChdbFunctions.scalarFunction(), modelled on duckdb-java's
  DuckDBFunctions. withFunction(Supplier | Function | BiFunction) or
  withRowFunction(ChdbRowFunction) is called a row at a time with Java
  values -- the types getObject gives, with java.time for dates and
  timestamps -- and registered through any chDB Connection or one that
  wraps it. No Arrow dependency.
- chdb-arrow: ArrowFunctions.scalarFunction(), the same declaration
  computed a batch at a time with Arrow vectors, imported and exported
  through Arrow Java's C Data Interface.

Both take ClickHouse type names, offer withVolatile(),
withSpecialNullHandling() and withBinaryStrings(), and return a
RegisteredFunction whose close() drops the function while it is still
that registration. ChdbFunctions.dropScalarFunction(name) needs no
connection. Registrations are process-wide, unlike DuckDB's, and NULL
arguments are skipped by default, the opposite of its default; the docs
say so.

The shim:
- resolves the two entry points with dlsym, like the classifier, so an
  older libchdb still loads and registration fails with an
  SQLFeatureNotSupportedException naming v26.11.2-rc.3. Measured against
  the v26.11.1 release library.
- attaches an engine thread to the JVM as a daemon the first time it runs
  a function, named after the engine thread, and detaches it through a
  pthread key when it exits.
- holds the callback as a global reference until chDB's destroy, which may
  run on any thread and inside another chDB call, so an exception pending
  on the thread is set aside around every upcall.
- copies argument buffers onto the heap and builds results in native
  memory freed by their release callbacks. The layout and the result
  arrays are in chdb_jni_functions.cpp, without JNI, which chdb_jni_test
  runs under ASan.
- refuses every engine entry point on a thread running a function. The
  driver refuses statements, connects, closes, registrations and drops
  from inside a function before it takes any lock, so SQL in a function
  fails the query instead of deadlocking it on its own statement slot.

JNI ABI 6: five natives, and ArrowColumn's fields join the contract.
libpthread is linked explicitly, as libdl is, for the glibc 2.28 floor.

New tests: 30 unit tests for the Arrow decoder and encoder, the callback
and the builder; ScalarFunctionIT, 18 against the engine, covering every
type mapping, both NULL modes, volatility, errors, registration and drop,
the 2M-row parallel sum and four queries meeting at a barrier inside the
function; ArrowFunctionsTest, 9; and harness checks for buffer extents,
export and release, and the error buffer. On linux-x86_64 against the
staged rc.3 pair: 208 unit, 195 integration and 39 Arrow tests pass, the
harness passes 161 checks under ASan, UBSan and LSan, and the JDBC suite
passes under UBSan.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
ArrowScalarFunctionBuilder.withFunction becomes withVectorizedFunction,
duckdb-java's name for a function called once per batch. The row-style
withFunction overloads of ChdbScalarFunctionBuilder keep their names,
which already match duckdb-java's.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Unit tests for the scalar function code that need neither libchdb nor the
shim, filling the gaps the first round left, and the production changes
they needed or turned up.

Found by the tests:
- A FixedString argument that was not valid UTF-8 reached the function
  with U+FFFD in place of its bytes. chDB fails a query whose String
  argument is not valid UTF-8 but passes a FixedString's bytes unchecked,
  and ArrowDecoder decoded them leniently. It now decodes them strictly
  and fails the batch, pointing at withBinaryStrings(), which is what the
  builder's javadoc already promised. Measured against the engine first:
  toFixedString(unhex('FFFE'), 2) arrived as two U+FFFD.
- A UUID column of no rows whose data buffer was left out, which C Data
  allows for a buffer of zero bytes, threw NullPointerException when its
  reader was made.
- ArrowFunctionCallback.release() said a failed close leaves the
  allocator open. It closes it, and frees nothing that is in use.
- The harness's ownedInt64 passed null to memcpy for an empty vector,
  which UBSan reports.

Seams, so that tests can reach the logic without the native library:
- ChdbFunctions.Registry holds the name-to-handle bookkeeping and takes
  the drop as a parameter, under the same lock discipline as before.
- ScalarFunctionCallback.handOver counts a registration around its hand-
  over to chDB.
- RowFunctionCallback.compute runs a batch on the heap, between the
  shim's copy and its export.
- Both builders expose their flag bits to tests.

New tests:
- ArrowDecoderTest: integer limits at every width; offsets on every flat
  and nested layout, with validity bits that do not start a byte and an
  uncounted null count; decimal scales and 128/256-bit extremes;
  FixedString padding and invalid UTF-8; dates and instants under other
  JVM and column zones; nested Array/Tuple/Map with NULL rows; a batch of
  no rows with its buffers left out.
- ArrowEncoderTest: the C Data buffer layout of every encoder, for no
  rows and with NULLs; 64-bit integer limits; decimal text; bytes and
  text; instants from any zone and date limits; nested containers; wrong
  result types at depth.
- ScalarFunctionCallbackTest: cause chains cut at eight, the driver's
  report as a cause, standard UTF-8 for the shim, the chdb.h flag values,
  and the live count across hand-over, destroy and refusal.
- ChdbFunctionsTest: a handle drops only its own registration.
- ChdbScalarFunctionBuilderTest: flags, how a foreign connection is
  refused, and type names left for chDB to judge.
- RowFunctionCallbackTest: whole batches, without arguments or rows,
  binary strings, NULLs and failures.
- ArrowScalarFunctionBuilderTest: validation, flags and foreign
  connections, without the JVM options Arrow's allocator needs.
- ArrowFunctionCallbackTest: batches through Arrow's C Data, with the
  test as chDB and its allocator checking that every argument and result
  buffer is given back. Runs where java.nio is opened, as the Arrow CI
  step opens it.
- The harness: the remaining fixed widths and layouts, metadata keys,
  exports of no rows and of nested and fixed-size lists, and error
  messages cut at every UTF-8 character width.
- ScalarFunctionIT: an invalid FixedString fails the query.

On linux-x86_64 against the staged v26.11.2-rc.3 pair: 239 unit tests
(208 before), 195 integration tests (195), 48 chdb-arrow tests (39), and
210 harness checks (161) under ASan, UBSan and LSan, all passing.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@wudidapaopao
wudidapaopao merged commit 99e79f6 into chdb-io:main Dec 2, 2026
16 checks passed
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.

1 participant