Repository navigation
Call Java functions from SQL as scalar UDFs - #49
Merged
Merged
Conversation
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.withVolatile(),withSpecialNullHandling()andwithBinaryStrings().registerreturns aRegisteredFunction. Itsclose()drops the function only if the name still belongs to that registration.ChdbFunctions.dropScalarFunction(name)needs no connection.isScalarFunctionSupported()checks support without trying a registration.register(Connection)unwraps toChdbConnection, so plain JDBC code and pool proxies work.docs/scalar-functions.mdexplains how this differs from DuckDB's per-connection functions.Design
Threading
Calls back into chDB
Exceptions
Throwablebecomes the query's error, asClass: message; caused by ....Memory
destroy, on whatever thread runs it. A failed registration frees everything itself.Arrow and modules
chdb-jdbckeeps 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-arrowusesarrow-c-data, which it already depended on.Older engines
dlsymthrough the existing optional-symbol mechanism.SQLFeatureNotSupportedException(SQLSTATE 0A000) naming the minimum engine. Loading an older engine at all still needs the existing-Dchdb.skipEngineVersionCheck=true.Type mapping (row style)
byte[]with binary strings)byte[]Time, Time64 and Variant parameters are refused at registration in the row style.
Commits
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'sSHA256SUMS.26.11.2-rc.3and version1.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.licenses/engine-third-party-26.11.2-rc.3.tsv: 1038 entries instead of 1081. The MPL-2.0webpki-roots0.26.1 is gone; the 1.0.x copies that remain are CDLA-Permissive. The copyleft set therefore drops from eleven to ten, andLicenseInventoryIT, the licence textbuild-native.shwrites, and the docs are updated to match. Please include this in the compliance review.Add scalar functions written in Java.
chdb_jni.cpp, the JNI-freechdb_jni_functions.{h,cpp},arrow_c_abi.h, optional-symbol entries and harness tests.chdb-jdbcandchdb-arrowgain the builders and callbacks.docs/scalar-functions.md, plus README sections.Name the Arrow batch method as duckdb-java does.
ArrowScalarFunctionBuilder.withFunctionbecomeswithVectorizedFunction. The row-stylewithFunctionoverloads already match duckdb-java.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:
FixedString, and time zones;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:
FixedStringargument that is not valid UTF-8 reached the function with U+FFFD replacement characters. chDB rejects an invalidStringbut passesFixedStringbytes through unchecked. The query now fails and points towithBinaryStrings(), as the javadoc already promised.NullPointerException.Tests
Run locally on Linux x86_64 with JDK 21 against v26.11.2-rc.3:
mvn -pl chdb-jdbc -am testmvn -pl chdb-integration-tests -am verify ...ScalarFunctionIT)mvn -pl chdb-arrow -am test -Dchdb.arrow.it=true ...All pass with 0 failures. Under the sanitizers:
The integration and Arrow tests assert
chdb_version()= 26.11.2-rc.3.The new tests cover:
Erroras query errorsmax_threads=8sumThe 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
🤖 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-arrowmodule offers vectorized, batch-at-a-time functions (ArrowFunctionCallback.java).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.SQLFeatureNotSupportedException(SQLState 0A000), to prevent deadlocks waiting on the invoking query.Macroscope summarized 8403d3b.