From dd93ccff858fcd5c3faeb142bd3d28c538c5d093 Mon Sep 17 00:00:00 2001 From: wudidapaopao Date: Tue, 1 Dec 2026 06:10:59 +0000 Subject: [PATCH 1/4] Pin chdb-core v26.11.2-rc.3 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. can be cut from here. - engine.properties and : 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) --- README.md | 17 +- chdb-arrow/README.md | 12 +- chdb-arrow/pom.xml | 2 +- chdb-bom/pom.xml | 2 +- chdb-examples/pom.xml | 2 +- chdb-integration-tests/pom.xml | 2 +- .../java/org/chdb/it/LicenseInventoryIT.java | 7 +- chdb-jdbc/pom.xml | 2 +- .../java/org/chdb/internal/ChdbNative.java | 6 +- .../java/org/chdb/jdbc/ChdbStatement.java | 2 +- .../java/org/chdb/jdbc/StatementShape.java | 2 +- .../org/chdb/jdbc/StatementShapeTest.java | 2 +- chdb-jni/include/chdb.h | 162 ++- chdb-jni/src/chdb_jni.cpp | 2 +- chdb-jni/src/chdb_optional_api.h | 4 +- chdb-native-linux-aarch64-gnu/pom.xml | 2 +- chdb-native-linux-x86_64-gnu/pom.xml | 2 +- chdb-native-macos-aarch64/pom.xml | 2 +- chdb-native-macos-x86_64/pom.xml | 2 +- docs/memory.md | 8 +- docs/publishing.md | 30 +- docs/upstream-findings.md | 28 +- docs/v1-progress.md | 16 +- licenses/engine-third-party-26.11.2-rc.3.tsv | 1038 +++++++++++++++++ pom.xml | 4 +- scripts/build-native.sh | 6 +- scripts/engine.properties | 44 +- 27 files changed, 1320 insertions(+), 88 deletions(-) create mode 100644 licenses/engine-third-party-26.11.2-rc.3.tsv diff --git a/README.md b/README.md index 766a47e..accc8d1 100644 --- a/README.md +++ b/README.md @@ -47,12 +47,13 @@ the published macOS arm64 artifact was independently consumed from `maven.chdb.i engine does. Each package records the figure it was built against in its `manifest.properties`, and CI runs the whole test suite on AlmaLinux 8 to demonstrate the floor rather than infer it from symbol versions. -- **Engine in this source branch:** chDB Core **26.11.1**, pinned. Published Java - `1.1.0-rc.1` uses this core; the older `1.0.0-rc.2` uses `26.11.0-rc.2`. The C ABI is - version-locked, so the driver - refuses to run against a different engine build rather than risking a struct-layout mismatch. - This stable core meets the engine-release requirement for the planned Java `1.1.0`, but the - remaining Java release gates still apply ([work plan §4.3](CHDB_JAVA_V1_WORK_PLAN.md)). +- **Engine in this source branch:** chDB Core **26.11.2-rc.3**, pinned. It is a chdb-core + *pre-release*, pinned for its scalar function ABI. Java `1.1.0-rc.1` and `1.1.0` use stable + core `26.11.1`; the older `1.0.0-rc.2` uses `26.11.0-rc.2`. The C ABI is version-locked, so + the driver refuses to run against a different engine build rather than risking a + struct-layout mismatch. A binding on an engine RC is itself an RC, so only `1.2.0-rc.` + versions can be cut from this branch until a stable core is pinned + ([work plan §4.3](CHDB_JAVA_V1_WORK_PLAN.md)). - **Not supported:** Windows, musl (Alpine), 32-bit, GraalVM Native Image, Android. ## Installing @@ -117,8 +118,8 @@ in `1.1.0-rc.1`. There is no all-platforms package, on purpose: it would be the SemVer, on the binding alone: `1.1.0` is the first stable release and a major bump means a breaking change to the Java API. The engine version is not part of it — it is in each package's `manifest.properties`, pinned in [`scripts/engine.properties`](scripts/engine.properties) and -named in the release notes (`26.11.0-rc.2` for the published Java RC, `26.11.1` -in this development branch), and the driver refuses to load any other build. +named in the release notes (`26.11.1` for Java `1.1.0`, `26.11.2-rc.3` in this development +branch), and the driver refuses to load any other build. The first test versions were `1.0.0-rc.1` and `1.0.0-rc.2`; `1.0.0` GA is intentionally skipped. The first stable Maven release is planned as `1.1.0`. RCs use the permanent `com.clickhouse.chdb` groupId, diff --git a/chdb-arrow/README.md b/chdb-arrow/README.md index c70f58d..0bbe454 100644 --- a/chdb-arrow/README.md +++ b/chdb-arrow/README.md @@ -244,9 +244,9 @@ engine and JNI shim in the directory given by `-Dchdb.library.path`. The publish interchangeable. Arrow Java 19.0.0 on classpath also requires `--add-opens=java.base/java.nio=ALL-UNNAMED` on supported JDKs. -The current source pins stable chDB core `26.11.1`. For a macOS arm64 release-asset -smoke test, compile the Java side (`mvn -pl chdb-jdbc -am compile`), then run -`scripts/build-native.sh macos-aarch64`. That script downloads the exact v26.11.1 asset, +The current source pins chDB core `26.11.2-rc.3`, a pre-release. For a macOS arm64 +release-asset smoke test, compile the Java side (`mvn -pl chdb-jdbc -am compile`), then run +`scripts/build-native.sh macos-aarch64`. That script downloads the exact v26.11.2-rc.3 asset, verifies its SHA-256 and stages the engine plus JNI shim in `chdb-native-macos-aarch64/target/native/`. Run the opt-in test with the staged pair: @@ -269,7 +269,7 @@ platform, and run its `scripts/build-native.sh ` first. The earlier core `26.11.0-rc.2` omitted a `get_schema` release during registration: a value-correct Java scan left 148 bytes in the Arrow allocator. The later rc.3 fix -is included in v26.11.1, so the Arrow input and insert tests run on this baseline. CI exercises the -same suite on all four native platforms and Java 11/17/21/25 without a version -override. No production deployment should use a local `--local-engine` package or +is included in v26.11.1 and v26.11.2-rc.3, so the Arrow input and insert tests run on this +baseline. CI exercises the same suite on all four native platforms and Java 11/17/21/25 +without a version override. No production deployment should use a local `--local-engine` package or `chdb.skipEngineVersionCheck`. diff --git a/chdb-arrow/pom.xml b/chdb-arrow/pom.xml index 18c2796..cd20a07 100644 --- a/chdb-arrow/pom.xml +++ b/chdb-arrow/pom.xml @@ -6,7 +6,7 @@ com.clickhouse.chdb chdb-java-parent - 1.1.0 + 1.2.0-SNAPSHOT chdb-arrow diff --git a/chdb-bom/pom.xml b/chdb-bom/pom.xml index 96a16b6..485d122 100644 --- a/chdb-bom/pom.xml +++ b/chdb-bom/pom.xml @@ -7,7 +7,7 @@ com.clickhouse.chdb chdb-java-parent - 1.1.0 + 1.2.0-SNAPSHOT chdb-bom diff --git a/chdb-examples/pom.xml b/chdb-examples/pom.xml index 61b6bd8..7def40d 100644 --- a/chdb-examples/pom.xml +++ b/chdb-examples/pom.xml @@ -7,7 +7,7 @@ com.clickhouse.chdb chdb-java-parent - 1.1.0 + 1.2.0-SNAPSHOT chdb-examples diff --git a/chdb-integration-tests/pom.xml b/chdb-integration-tests/pom.xml index b853cf5..5b3e6bb 100644 --- a/chdb-integration-tests/pom.xml +++ b/chdb-integration-tests/pom.xml @@ -7,7 +7,7 @@ com.clickhouse.chdb chdb-java-parent - 1.1.0 + 1.2.0-SNAPSHOT chdb-integration-tests diff --git a/chdb-integration-tests/src/test/java/org/chdb/it/LicenseInventoryIT.java b/chdb-integration-tests/src/test/java/org/chdb/it/LicenseInventoryIT.java index 4fbd35d..8e2cf8b 100644 --- a/chdb-integration-tests/src/test/java/org/chdb/it/LicenseInventoryIT.java +++ b/chdb-integration-tests/src/test/java/org/chdb/it/LicenseInventoryIT.java @@ -143,6 +143,11 @@ void inventoryMatchesTheEngine() throws Exception { *

numactl (LGPL) was in this set through engine v26.7.3 and left it with v26.11.0-rc.1, * whose chdb-core tree no longer has {@code contrib/numactl} at all, so it is a component * gone from the engine rather than one relicensed. + * + *

webpki-roots (MPL-2.0) was in this set through engine v26.11.1 and left it with + * v26.11.2-rc.3. That engine no longer vendors {@code webpki-roots-0.26.1}, the copy under + * MPL-2.0; the {@code 1.0.x} copies it keeps are CDLA-Permissive-2.0, so the component is + * still in the inventory, under that licence only. */ private static Map> knownCopyleftOnly() { Map> known = new TreeMap<>(); @@ -157,7 +162,7 @@ private static Map> knownCopyleftOnly() { new TreeSet<>( java.util.Arrays.asList( "cbindgen", "defer-drop", "fortanix-sgx-abi", - "shuffling-allocator", "timer", "webpki-roots"))); + "shuffling-allocator", "timer"))); return known; } diff --git a/chdb-jdbc/pom.xml b/chdb-jdbc/pom.xml index ceb9831..6314d02 100644 --- a/chdb-jdbc/pom.xml +++ b/chdb-jdbc/pom.xml @@ -7,7 +7,7 @@ com.clickhouse.chdb chdb-java-parent - 1.1.0 + 1.2.0-SNAPSHOT chdb-jdbc diff --git a/chdb-jdbc/src/main/java/org/chdb/internal/ChdbNative.java b/chdb-jdbc/src/main/java/org/chdb/internal/ChdbNative.java index 97b0b9e..f274b16 100644 --- a/chdb-jdbc/src/main/java/org/chdb/internal/ChdbNative.java +++ b/chdb-jdbc/src/main/java/org/chdb/internal/ChdbNative.java @@ -58,7 +58,7 @@ private ChdbNative() { /** ABI version the loaded shim was built with. */ public static native int jniAbiVersion(); - /** {@code chdb_version()} of the loaded libchdb, e.g. {@code "26.11.1"}. */ + /** {@code chdb_version()} of the loaded libchdb, e.g. {@code "26.11.2-rc.3"}. */ public static native String engineVersion(); /** Build provenance of the shim: git commit, compiler, engine headers it compiled against. */ @@ -180,7 +180,7 @@ public static native long insertArrowStreamWithOptions( * {@code chdb_classify_query_n}. Decides whether a statement has a result set to stream * without executing it, using the engine's own parser. * - *

Optional symbol: it landed in chdb-core v26.7.2-rc.2, so the pinned v26.11.1 + *

Optional symbol: it landed in chdb-core v26.7.2-rc.2, so the pinned v26.11.2-rc.3 * baseline has it, so it is resolved by {@code dlsym} rather than linked. It is present on * the baseline; the null path is what an older engine gets, and means the caller must fall * back to {@code StatementShape}'s own analysis. @@ -242,7 +242,7 @@ public static native long rowBinaryOpen( * every result destroyed first, and the engine cannot be used again in this process. * *

Optional symbol, like {@link #classifyQuery(long, byte[])}: it landed in chdb-core - * v26.7.2-rc.2, so the pinned v26.11.1 baseline has it, and it is resolved by {@code + * v26.7.2-rc.2, so the pinned v26.11.2-rc.3 baseline has it, and it is resolved by {@code * dlsym} rather than linked. Not having it is not a failure -- the threads it would join are * reaped by process exit either way. * diff --git a/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbStatement.java b/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbStatement.java index 19ac20f..175d8cf 100644 --- a/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbStatement.java +++ b/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbStatement.java @@ -365,7 +365,7 @@ private void checkDeadlineSurvivedTheOpen(String sql) throws SQLException { private StatementShape.Route route(String sql) throws SQLException { int[] analysis; try { - // Null when the engine predates chdb_classify_query_n, which the v26.11.1 + // Null when the engine predates chdb_classify_query_n, which the v26.11.2-rc.3 // baseline does not -- but a loader pointed at another libchdb still can, in which // case StatementShape falls back to its keyword scan. analysis = ChdbNative.classifyQuery(connection.handle(), Utf8.encode(sql)); diff --git a/chdb-jdbc/src/main/java/org/chdb/jdbc/StatementShape.java b/chdb-jdbc/src/main/java/org/chdb/jdbc/StatementShape.java index e8333df..148dc03 100644 --- a/chdb-jdbc/src/main/java/org/chdb/jdbc/StatementShape.java +++ b/chdb-jdbc/src/main/java/org/chdb/jdbc/StatementShape.java @@ -29,7 +29,7 @@ *

    *
  1. {@code chdb_classify_query_n}, which parses the SQL with the engine's own parser and * settings and executes nothing. Available from engine v26.7.2-rc.2, so present on the - * pinned v26.11.1 baseline and asked in practice. Authoritative about + * pinned v26.11.2-rc.3 baseline and asked in practice. Authoritative about * whether there is a result set, but silent on which door delivers it: * {@code CHDB_QUERY_READ_ONLY} covers a {@code SELECT} and a {@code SHOW} alike, so it * cannot tell the two entry points apart. See {@link #route(int[], String)}. diff --git a/chdb-jdbc/src/test/java/org/chdb/jdbc/StatementShapeTest.java b/chdb-jdbc/src/test/java/org/chdb/jdbc/StatementShapeTest.java index 34e8297..8611785 100644 --- a/chdb-jdbc/src/test/java/org/chdb/jdbc/StatementShapeTest.java +++ b/chdb-jdbc/src/test/java/org/chdb/jdbc/StatementShapeTest.java @@ -13,7 +13,7 @@ * an entry point that refuses it -- which is what issue #12 was -- so all three are covered in * both directions. * - *

    The pinned v26.11.1 baseline does export chdb_classify_query_n, so the scan is no + *

    The pinned v26.11.2-rc.3 baseline does export chdb_classify_query_n, so the scan is no * longer the only thing deciding. It is still what decides whether a result set is streamed or * materialized, because the classifier does not distinguish those, as well as * deciding both halves whenever the classifier is absent or refuses the text -- hence the cases diff --git a/chdb-jni/include/chdb.h b/chdb-jni/include/chdb.h index a12d326..0a032ac 100644 --- a/chdb-jni/include/chdb.h +++ b/chdb-jni/include/chdb.h @@ -12,7 +12,7 @@ extern "C" { #define CHDB_EXPORT __attribute__((visibility("default"))) -#define CHDB_VERSION "26.11.1" +#define CHDB_VERSION "26.11.2-rc.3" /** * Returns the version of the linked chDB library. @@ -375,6 +375,30 @@ CHDB_EXPORT void chdb_streaming_cancel_query(struct chdb_conn * conn, chdb_strea * options (--path=..., --user_scripts_path=..., logging options, ...) are consumed by * the connection that boots the engine and ignored afterwards. * + * --restrict_local_filesystem_access[=1] denies this connection's SQL the + * local files and programs it reaches through: file(), url('file://...'), + * filesystem(), INTO OUTFILE, FROM INFILE, file descriptors, SQLite, ODBC, + * JDBC and local data lakes, schema and template files outside + * format_schema_path, executable functions and engines, dictionaries with a + * FILE, EXECUTABLE, EXECUTABLE_POOL, LIBRARY, ODBC, JDBC or YAMLREGEXPTREE + * source or an SSD_CACHE layout, custom disks, BACKUP and RESTORE on File or + * Disk, Backup databases, restoring tables on such engines, and SYSTEM + * SHUTDOWN and KILL. The engine's own files (metadata, temporary data, + * caches), the credential files cloud clients load, and BACKUP and RESTORE on + * object storage keep working. Queries run as the user + * chdb_restricted_local_filesystem, a copy of default with the grants of its + * roles and its row policies and quotas; a CLICKHOUSE dictionary source runs + * as that user too. The option is fixed for the connection's lifetime and + * covers every query function on it; no SET, SETTINGS or chdb_set() lifts it. + * + * It is not a sandbox. Tables and SQL SECURITY DEFINER views that another + * connection created keep the access they were created with, and client + * libraries of network sources read the local files their own options name + * (e.g. TLS certificates). chdb_get(conn, "restrict_local_filesystem_access") + * returns "1" when the option is in force; versions without the option + * return NULL. An invalid value, or an engine that cannot set up the + * restriction, fails the connection. + * * @param argc Number of command-line arguments * @param argv Command-line arguments array (--path= to specify database location) * @return Pointer to connection pointer, or NULL on failure @@ -997,6 +1021,142 @@ CHDB_EXPORT chdb_result * chdb_insert_arrow_stream( chdb_arrow_stream arrow_stream, const chdb_arrow_insert_options * options); +//===--------------------------------------------------------------------===// +// Scalar User-Defined Functions +//===--------------------------------------------------------------------===// + +/** + * Evaluates a scalar function registered with chdb_create_scalar_function() + * on one batch of rows. chDB calls it once per block of rows, not per row, + * and only for the rows it needs (see CHDB_SCALAR_FUNCTION_SPECIAL_NULL_HANDLING). + * + * Data travels through the Arrow C Data Interface (struct ArrowSchema and + * struct ArrowArray from arrow/c/abi.h, behind the chdb_arrow_* handles): + * + * - argument_schema / arguments: a struct array with one child per argument, + * in declaration order, holding arguments->length rows. A function without + * arguments still gets a struct array, with no children. Each argument has + * the Arrow type its declared ClickHouse type maps to, as for + * chdb_query_arrow() with the default options, except that DateTime is an + * Arrow timestamp("s", tz), Enum and 128/256-bit integers are strings, and + * BFloat16 is float32. The callback owns both structs during the call: it + * may release them, or move their contents out to keep the data longer, + * following the C Data Interface's move semantics. chDB releases whatever + * is left in them when the callback returns; the structs themselves are not + * valid after it returns. + * + * - result_schema / result: zeroed by chDB. On success the callback fills both + * with an array of exactly arguments->length values, of any Arrow type chDB + * can read: chDB converts it to the declared return type like CAST does, + * except that a value which does not fit (an integer out of range, a + * fraction for an integer type) is an error rather than a wrapped value. + * Precision lost on the way to a float type is not an error. chDB takes + * ownership of both structs and releases them. On failure chDB releases + * whatever the callback left in them. + * + * - error / error_size: a buffer of error_size bytes, empty on entry. On + * failure the callback may write a NUL-terminated message into it, which + * becomes the query's error. + * + * The callback may run on any thread, concurrently with itself, including + * threads the host did not create. It must not call back into chDB. + * + * @return 0 on success; any other value fails the query + */ +typedef int (*chdb_scalar_function_callback)( + void * user_data, + chdb_arrow_schema argument_schema, + chdb_arrow_array arguments, + chdb_arrow_schema result_schema, + chdb_arrow_array result, + char * error, + size_t error_size); + +typedef enum chdb_scalar_function_flag +{ + // The function may return different results for the same arguments, like + // rand(): chDB evaluates it for every row instead of folding a call with + // constant arguments into one value. Without it the function is assumed + // to return the same result for the same arguments within a query. chDB + // never reuses a result across queries, since a function can be replaced. + CHDB_SCALAR_FUNCTION_VOLATILE = 1u << 0, + // Pass NULL arguments to the callback, as Arrow nulls, and return the + // declared type unchanged; an argument that can be NULL is then rejected + // for a declared type that cannot hold one, e.g. Array. Without it, a row + // with any NULL argument never reaches the callback and yields NULL, and + // the return type becomes Nullable when an argument can be NULL (unless + // the type cannot be inside Nullable, e.g. Array, in which case such a row + // yields the type's default). + CHDB_SCALAR_FUNCTION_SPECIAL_NULL_HANDLING = 1u << 1, + // Pass every String value, at any depth, as Arrow binary, and so the text + // of Enum and 128/256-bit integer arguments too. Without it they are Arrow + // UTF-8 strings, and a value that is not valid UTF-8 fails the query. + CHDB_SCALAR_FUNCTION_BINARY_STRINGS = 1u << 2 +} chdb_scalar_function_flag; + +// What chdb_create_scalar_function() registers. Versioned by size: set +// struct_size to sizeof the struct you compiled against, so that a newer +// engine knows which fields it has. +typedef struct chdb_scalar_function_options +{ + size_t struct_size; // sizeof(chdb_scalar_function_options) + const char * const * argument_types; // ClickHouse type names, e.g. "Int64", "Array(String)" + size_t argument_count; + const char * return_type; // ClickHouse type name, e.g. "Nullable(Float64)" + uint32_t flags; // chdb_scalar_function_flag, OR-ed + chdb_scalar_function_callback callback; + void * user_data; // passed to callback and destroy + void (*destroy)(void * user_data); // optional +} chdb_scalar_function_options; + +/** + * Registers a scalar function implemented by the host, callable from SQL by + * name in every connection of this process, including connections opened + * later. It stays registered until chdb_drop_scalar_function(), across engine + * restarts too. + * + * Argument types are checked when a query is analyzed: an argument must be of + * the declared type or of one that converts to it without loss, e.g. Int32 + * for an Int64 parameter; it reaches the callback converted. A declared + * Nullable or LowCardinality argument type means the same as its base type, + * and so does a LowCardinality return type. + * + * The name must not be taken by a built-in or aggregate function, a SQL or + * executable user-defined function, a Python UDF, or another function + * registered here. A later SQL `CREATE FUNCTION` with the name fails, and a + * later executable UDF with it makes calls to that name fail as ambiguous. + * + * Ownership: on success chDB owns options->user_data and calls + * options->destroy(user_data) exactly once, after the function is dropped and + * nothing uses it anymore: no running query, and no table whose definition + * calls it. destroy may then run on any thread, also inside another chDB + * call, so like the callback it must not call into chDB. chDB does not + * destroy registered functions at process exit. On failure the caller keeps + * ownership and destroy is not called. The options struct and the strings it + * points to are only read during the call. + * + * @param conn Active connection + * @param name Function name; case-sensitive + * @param options What to register + * @return chdb_result carrying only an error, if any; destroy it with + * chdb_destroy_query_result() + */ +CHDB_EXPORT chdb_result * chdb_create_scalar_function( + chdb_connection conn, const char * name, + const chdb_scalar_function_options * options); + +/** + * Unregisters a function registered with chdb_create_scalar_function(). A + * query that already uses it finishes with it. + * + * @param conn Not needed: may be NULL or closed, e.g. after chdb_shutdown(), + * since registrations outlive the engine + * @param name Function name + * @return chdb_result carrying only an error, if any (a name that is not + * registered is one); destroy it with chdb_destroy_query_result() + */ +CHDB_EXPORT chdb_result * chdb_drop_scalar_function(chdb_connection conn, const char * name); + //===--------------------------------------------------------------------===// // Backup, Restore and Statement Classification //===--------------------------------------------------------------------===// diff --git a/chdb-jni/src/chdb_jni.cpp b/chdb-jni/src/chdb_jni.cpp index 290b723..4f32d39 100644 --- a/chdb-jni/src/chdb_jni.cpp +++ b/chdb-jni/src/chdb_jni.cpp @@ -1096,7 +1096,7 @@ Java_org_chdb_internal_ChdbNative_classifyQuery(JNIEnv * env, jclass, jlong conn { try { - // Optional symbol: present from v26.7.2-rc.2, so on the pinned v26.11.1 baseline, + // Optional symbol: present from v26.7.2-rc.2, so on the pinned v26.11.2-rc.3 baseline, // absent on anything older. Null tells the Java side to use its own statement-shape // heuristic rather than failing the query. const auto classify = optionalApi().classify_query_n; diff --git a/chdb-jni/src/chdb_optional_api.h b/chdb-jni/src/chdb_optional_api.h index ac970e9..e65e7f3 100644 --- a/chdb-jni/src/chdb_optional_api.h +++ b/chdb-jni/src/chdb_optional_api.h @@ -1,6 +1,6 @@ // chDB C API entry points the shim resolves at runtime rather than linking. // -// The baseline is chdb-core v26.11.1 (work plan section 2.1). Both of these arrived in +// The baseline is chdb-core v26.11.2-rc.3 (work plan section 2.1). Both of these arrived in // v26.7.2-rc.2 -- neither is in v26.7.0 or v26.7.1-rc.1, whose export lists and headers have // neither name -- and both are exported by the current baseline, checked in its release // library rather than in an export list: @@ -44,7 +44,7 @@ struct QueryAnalysisV1 uint32_t query_class; }; -// chdb_query_class values, as of v26.11.1. Kept in sync with ChdbNative.classifyQuery's +// chdb_query_class values, as of v26.11.2-rc.3. Kept in sync with ChdbNative.classifyQuery's // documented return contract. enum QueryClass : uint32_t { diff --git a/chdb-native-linux-aarch64-gnu/pom.xml b/chdb-native-linux-aarch64-gnu/pom.xml index 6cd3ff7..1616521 100644 --- a/chdb-native-linux-aarch64-gnu/pom.xml +++ b/chdb-native-linux-aarch64-gnu/pom.xml @@ -7,7 +7,7 @@ com.clickhouse.chdb chdb-java-parent - 1.1.0 + 1.2.0-SNAPSHOT chdb-native-linux-aarch64-gnu diff --git a/chdb-native-linux-x86_64-gnu/pom.xml b/chdb-native-linux-x86_64-gnu/pom.xml index 2672d32..3706e43 100644 --- a/chdb-native-linux-x86_64-gnu/pom.xml +++ b/chdb-native-linux-x86_64-gnu/pom.xml @@ -7,7 +7,7 @@ com.clickhouse.chdb chdb-java-parent - 1.1.0 + 1.2.0-SNAPSHOT chdb-native-linux-x86_64-gnu diff --git a/chdb-native-macos-aarch64/pom.xml b/chdb-native-macos-aarch64/pom.xml index 553300e..43568b1 100644 --- a/chdb-native-macos-aarch64/pom.xml +++ b/chdb-native-macos-aarch64/pom.xml @@ -7,7 +7,7 @@ com.clickhouse.chdb chdb-java-parent - 1.1.0 + 1.2.0-SNAPSHOT chdb-native-macos-aarch64 diff --git a/chdb-native-macos-x86_64/pom.xml b/chdb-native-macos-x86_64/pom.xml index fb1f1fe..8bf32b4 100644 --- a/chdb-native-macos-x86_64/pom.xml +++ b/chdb-native-macos-x86_64/pom.xml @@ -7,7 +7,7 @@ com.clickhouse.chdb chdb-java-parent - 1.1.0 + 1.2.0-SNAPSHOT chdb-native-macos-x86_64 diff --git a/docs/memory.md b/docs/memory.md index 09d393b..a1ba089 100644 --- a/docs/memory.md +++ b/docs/memory.md @@ -33,12 +33,12 @@ docker run --memory=4g \ jdbc:chdb:/data?max_memory_usage=2000000000 ``` -That URL form works on the pinned v26.11.0-rc.2 baseline. First measured on v26.7.2-rc.2 with +That URL form works on the pinned v26.11.2-rc.3 baseline. First measured on v26.7.2-rc.2 with `?max_threads=7&max_result_rows=13&max_block_size=4096`: `system.settings` reports 7, 13 and 4096 with `changed = 1`, and the cap is enforced rather than merely reported — a 100-row `SELECT` under `max_result_rows=13` fails with ClickHouse error 396. Re-measured the same way, -with `max_memory_usage=2000000000` added, on v26.11.0-rc.1 and again on v26.11.0-rc.2 (Linux -x86_64). +with `max_memory_usage=2000000000` added, on v26.11.0-rc.1, v26.11.0-rc.2 and v26.11.2-rc.3 +(Linux x86_64). **On v26.7.0 and v26.7.1-rc.1 it was silently inert**, if you are pointing the loader at one of those: settings in the connect argument vector never reached a session, so the same URL left @@ -206,7 +206,7 @@ int result = org.chdb.internal.ChdbNative.shutdown(); A process that simply exits does not need to call it while the driver's shutdown hook is installed, which is the default. A host that turns the hook off should close its connections and call it before exiting, rather than leave the engine to tear itself down from its own exit -handlers with connections open. The pinned 26.11.0-rc.3 engine exports it, so 2 is what an older engine returns; see +handlers with connections open. The pinned 26.11.2-rc.3 engine exports it, so 2 is what an older engine returns; see [upstream findings §6](upstream-findings.md). The driver's shutdown hook already calls it after closing the connections it knows about, so a host that leaves the hook installed does not need to. diff --git a/docs/publishing.md b/docs/publishing.md index 7904972..c640f3c 100644 --- a/docs/publishing.md +++ b/docs/publishing.md @@ -268,8 +268,8 @@ Apache-2.0, `LICENSE` in the repository, declared in the POM. Nothing to do. ### The redistributed engine Each platform package ships a ~326 MB `libchdb.so` verbatim from a chdb-core release. It -statically links ClickHouse and **1081 third-party components** on v26.11.1 and v26.11.0-rc.3 -(1082 on v26.11.0-rc.1/rc.2; 968 through v26.7.3). +statically links ClickHouse and **1038 third-party components** on v26.11.2-rc.3 (1081 on +v26.11.1 and v26.11.0-rc.3; 1082 on v26.11.0-rc.1/rc.2; 968 through v26.7.3). That number, and the licence of each one, comes from the engine itself: @@ -318,18 +318,27 @@ The sixth, for stable v26.11.1, was regenerated from its macOS arm64 release bin byte-identical to rc.3: 1081 entries and the same inventory SHA-256. The remaining three platform binaries still need the Java release CI inventory check. +The seventh, for the v26.11.2-rc.3 pre-release, differs again: 1038 entries, regenerated from +its Linux x86_64 release binary. 66 component names left, most of them vendored Rust crates +(`axum`, `tonic`, `objc2`, the `cap-*` family and others), and 22 arrived (`pest`, `ucd-trie`, +`serde_norway`, versioned `toml*` entries and others), with `gdeflate` back. Every arrival is +permissive, apart from two `Third-party notices` entries pointing at the +`THIRD_PARTY_NOTICES` files of `mongo-c-driver` and `zxc`, both components that were already +there under Apache and BSD. One copyleft entry left: the MPL-2.0 `webpki-roots-0.26.1` is no +longer vendored, and the `webpki-roots` 1.0.x copies that remain are CDLA-Permissive-2.0. The +copyleft set below is therefore ten, down from eleven. + ### The one open question Reading the inventory rather than guessing at it: most components are permissive, and several that a filename scan calls GPL are dual licensed with the permissive half in force — `zstd` is BSD-3, `rocksdb` is Apache-2.0, `liburing` is MIT, `ittapi` is `GPL-2.0-only OR BSD-3-Clause`. -Eleven carry a copyleft licence with no permissive alternative, in two families: +Ten carry a copyleft licence with no permissive alternative, in two families: ``` lemmagen-c libgsasl libssh mariadb-connector-c xz (LGPL) -cbindgen defer-drop fortanix-sgx-abi shuffling-allocator timer webpki-roots - (MPL-2.0) +cbindgen defer-drop fortanix-sgx-abi shuffling-allocator timer (MPL-2.0) ``` LGPL carries obligations under **static** linking that it does not under dynamic, and @@ -340,7 +349,7 @@ relinking requirement, so the obligation is to offer the source of any modified Several of the MPL components are plainly build-time Rust tooling — `cbindgen` generates headers, `fortanix-sgx-abi` is for SGX enclaves — and are unlikely to be in a chDB build at all. But *unlikely* is not *established*, which is the same problem as with the LGPL five: -whether any of the eleven is actually in the binary cannot be settled from the binary. It is +whether any of the ten is actually in the binary cannot be settled from the binary. It is stripped to 582 dynamic symbols and links statically. `nm` finds no `ssh_`, `mysql_`, `numa_`, `lzma_` or `gsasl_` symbols, which proves nothing either way. That question belongs to the engine build configuration. @@ -354,9 +363,10 @@ So the task is to **inherit and verify**, not to derive an answer here: 2. If there is not, that is a finding about all three distributions, and should be raised as such rather than solved inside this repository. -`LicenseInventoryIT.copyleftComponentsAreTheKnownSet` pins the set to exactly those eleven, so a -twelfth appearing in a future engine fails CI rather than shipping unnoticed — as does one -leaving, which is how `numactl`'s removal surfaced. It matches a copyleft *family* pattern — +`LicenseInventoryIT.copyleftComponentsAreTheKnownSet` pins the set to exactly those ten, so an +eleventh appearing in a future engine fails CI rather than shipping unnoticed — as does one +leaving, which is how the removals of `numactl` and the MPL-2.0 `webpki-roots` surfaced. It +matches a copyleft *family* pattern — AGPL, GPL, LGPL, MPL, EPL, CDDL, CPL, OSL, SSPL, EUPL, CeCILL, QPL — and then subtracts an explicit allowlist of dual-licensed strings, so a new component under a licence nobody here anticipated is caught rather than ignored. An earlier version asked only for @@ -413,7 +423,7 @@ Each step can invalidate the next, so: | `com.clickhouse.chdb` namespace permission | ClickHouse Central workspace admin | required before stable release | | Sonatype account and portal token | any maintainer | no | | A publishing-limit exception | Sonatype support | yes, if the numbers need it | -| **Position on the eleven copyleft components** | **chdb-io / ClickHouse legal** | **yes — the only real gate** | +| **Position on the ten copyleft components** | **chdb-io / ClickHouse legal** | **yes — the only real gate** | | Whether chDB is "commercial" for Central | whoever owns the Sonatype relationship | yes | --- diff --git a/docs/upstream-findings.md b/docs/upstream-findings.md index 7768b19..7dea3b1 100644 --- a/docs/upstream-findings.md +++ b/docs/upstream-findings.md @@ -5,7 +5,7 @@ arm64 while implementing work-plan phases 0–8 against what was then the pinned **v26.7.0**. They are recorded here because every one of them is a decision the driver's code depends on, and because several belong upstream rather than in a Java driver. -The baseline has since moved four times. First to **v26.7.2-rc.2** (issue #8, for +The baseline has since moved seven times. First to **v26.7.2-rc.2** (issue #8, for `chdb_shutdown()`), and four of these entries changed with it rather than being carried over: - **§2 was wrong about who was at fault** and is rewritten. The released header was always @@ -43,6 +43,12 @@ Then to **v26.11.0-rc.2**, the same baseline plus chdb-core #312: - **§9's `MergeTree` note is fixed upstream**: `chdb_shutdown()` returns 0 after `MergeTree` use once every connection is closed, and it now stops jemalloc's background threads too. +Then, by way of v26.11.0-rc.3 and the stable v26.11.1, to **v26.11.2-rc.3**, a pre-release +pinned for the scalar function ABI (chdb-core #352): + +- **§2's table gained a sixth column**: at the tag the in-tree constant reads `26.11.1`, one + release behind the tarball again. + The rest still hold on the new engine, and the tests named against each are what demonstrates that — they run in `mvn verify` against whichever engine is pinned. @@ -215,13 +221,13 @@ inverted. `chdb.h` exists in two places and they do not agree: -| | v26.7.0 | v26.7.2-rc.2 | v26.7.3 | v26.11.0-rc.1 | v26.11.0-rc.2 | -|---|---|---|---|---|---| -| `programs/local/chdb.h` at the git tag | `26.5.1-rc.3` | `26.7.2` | `26.7.2` | `26.11.0-dev` | `26.11.0-dev` | -| `chdb.h` inside the release tarball | `26.7.0` | `26.7.2-rc.2` | `26.7.3` | `26.11.0-rc.1` | `26.11.0-rc.2` | -| `chdb_version()` from that tarball's library | `26.7.0` | `26.7.2-rc.2` | `26.7.3` | `26.11.0-rc.1` | `26.11.0-rc.2` | +| | v26.7.0 | v26.7.2-rc.2 | v26.7.3 | v26.11.0-rc.1 | v26.11.0-rc.2 | v26.11.2-rc.3 | +|---|---|---|---|---|---|---| +| `programs/local/chdb.h` at the git tag | `26.5.1-rc.3` | `26.7.2` | `26.7.2` | `26.11.0-dev` | `26.11.0-dev` | `26.11.1` | +| `chdb.h` inside the release tarball | `26.7.0` | `26.7.2-rc.2` | `26.7.3` | `26.11.0-rc.1` | `26.11.0-rc.2` | `26.11.2-rc.3` | +| `chdb_version()` from that tarball's library | `26.7.0` | `26.7.2-rc.2` | `26.7.3` | `26.11.0-rc.1` | `26.11.0-rc.2` | `26.11.2-rc.3` | -Five releases, five disagreements, and the v26.7.3 column is the cleanest demonstration yet: +Six releases, six disagreements, and the v26.7.3 column is the cleanest demonstration yet: the in-tree constant did not move at all between v26.7.2-rc.2 and v26.7.3, so a header vendored from the git tag would have declared `26.7.2` for an engine whose `chdb_version()` returns `26.7.3` — a mismatch the loader refuses. Vendoring from the tarball is therefore not a @@ -233,7 +239,7 @@ tag v26.7.0, stale constant included, rather than to the header inside the relea **Consequence for this binding:** `chdb-jni/include/chdb.h` is now taken from the release tarball, which is the artifact this binding is built beside and ships against, and -`shim.built.against.engine.header` reads `26.11.0-rc.3` in this development branch. The rule is recorded in +`shim.built.against.engine.header` reads `26.11.2-rc.3` in this development branch. The rule is recorded in `chdb-jni/CMakeLists.txt` where the vendored header is included: copy it from the tarball, not from the source tree, and do not edit it — its value is being byte-identical to what upstream shipped, which is what makes the next comparison able to detect drift. This finding was made @@ -365,9 +371,9 @@ recognize. Validating values without validating names catches the rarer mistake. **Severity: expected; still handled as optional symbols.** -Neither is in v26.7.0 or v26.7.1-rc.1. Both are in v26.7.2-rc.2, in v26.7.3, in v26.11.0-rc.1 -and in v26.11.0-rc.2 — exported by all four of its platform libraries. The current -rc.3 baseline must be checked by the new CI matrix. +Neither is in v26.7.0 or v26.7.1-rc.1. Both are in v26.7.2-rc.2, in v26.7.3, in v26.11.0-rc.1, +in v26.11.0-rc.2 and in the pinned v26.11.2-rc.3 — exported by all four of its platform +libraries, read with `llvm-nm` from the four release tarballs. Checked in the release library rather than in the source's export list, because the two are not the same claim: diff --git a/docs/v1-progress.md b/docs/v1-progress.md index 0d3b9b0..62cc87d 100644 --- a/docs/v1-progress.md +++ b/docs/v1-progress.md @@ -14,11 +14,15 @@ sanitizer runs on one Linux and one macOS toolchain. Sixteen platform-and-JDK co green. The baseline subsequently moved to **engine 26.7.2-rc.2** (issue #8), **26.7.3**, -**26.11.0-rc.1** and **26.11.0-rc.2**. This development branch now targets -**26.11.1**, the stable release after the Arrow registration fixes. The `1.1.0-rc.1` tag -passed its four-platform build and Arrow checks, and its Maven repository was published on -2026-11-17. The older sixteen-way result above describes 26.7.0; the new baseline also passed -the main branch Java 11/17/21/25 platform matrix before tagging. +**26.11.0-rc.1**, **26.11.0-rc.2** and **26.11.1**, the stable release after the Arrow +registration fixes that `1.1.0` is built on. The `1.1.0-rc.1` tag passed its four-platform +build and Arrow checks, and its Maven repository was published on 2026-11-17. The older +sixteen-way result above describes 26.7.0; 26.11.1 also passed the main branch Java +11/17/21/25 platform matrix before tagging. + +This development branch now targets **26.11.2-rc.3**, a chdb-core **pre-release** that adds the +scalar function ABI, so §4.3 applies again: only `1.2.0-rc.` versions can be cut from it, and +a stable core has to be pinned before `1.2.0`. It needs its own four-platform CI matrix. 26.7.3 is a **stable** chdb-core release, which cleared the [work plan §4.3 ](../CHDB_JAVA_V1_WORK_PLAN.md) bar that 26.7.2-rc.2 could not: a binding built on an engine @@ -54,7 +58,7 @@ consumer check completed after upload. | ✅ | Four glibc/macOS platforms | `Platform`, with musl detected and refused | | ✅ | Direct JNI is the mainline, ADBC the experiment | no Arrow Java dependency anywhere | | ✅ | Engine release, dynamic-library checksum and symbol set pinned | `scripts/engine.properties`, SHA-256 per platform from the GitHub release digests | -| 🟡 | Consistency check across `chdb_version()`, tag and header version | The v26.11.1 macOS arm64 release tarball header is now vendored byte-for-byte and reports `26.11.1`; its runtime agrees. The other platforms need CI confirmation. The `26.5.1-rc.3` constant blamed on upstream turned out to be ours: the vendored header had been copied from chdb-core's source tree instead of its release tarball — [findings §2](upstream-findings.md). Still enforced against `engine.properties` rather than the header | +| 🟡 | Consistency check across `chdb_version()`, tag and header version | The v26.11.2-rc.3 release tarball header is now vendored byte-for-byte and reports `26.11.2-rc.3`, identical in all four platform tarballs; the Linux x86_64 runtime agrees. The other platforms need CI confirmation. The `26.5.1-rc.3` constant blamed on upstream turned out to be ours: the vendored header had been copied from chdb-core's source tree instead of its release tarball — [findings §2](upstream-findings.md). Still enforced against `engine.properties` rather than the header | | ✅ | C API split into required and optional symbols | 18 required, linker- and load-checked; `chdb_classify_query_n` and `chdb_shutdown` optional via `dlsym`, and present on the current baseline | | ⬜ | C ABI version and compatibility promise confirmed with Core | needs upstream agreement | | ✅ | Signal-handler requirement raised upstream | reproduced, measured and written up in [findings §1](upstream-findings.md), filed as chdb-core #221, and fixed by chdb-core #224 in engine v26.7.3 — the shim's guard now reports no handler to repair, and `run-signal-window-test.sh measure` reports zero | diff --git a/licenses/engine-third-party-26.11.2-rc.3.tsv b/licenses/engine-third-party-26.11.2-rc.3.tsv new file mode 100644 index 0000000..a413b93 --- /dev/null +++ b/licenses/engine-third-party-26.11.2-rc.3.tsv @@ -0,0 +1,1038 @@ +abseil-cpp Apache +addr2line Apache-2.0 OR MIT +adler2 0BSD OR MIT OR Apache-2.0 +aead MIT OR Apache-2.0 +aes MIT OR Apache-2.0 +aes-gcm Apache-2.0 OR MIT +ahash MIT OR Apache-2.0 +aho-corasick Unlicense OR MIT +ai-sdk-cpp Apache +alloc-no-stdlib BSD-3-Clause +alloc-stdlib BSD-3-Clause +alloca MIT +allocator-api2 MIT OR Apache-2.0 +alp Apache-2.0 +AMQP-CPP Apache +android_system_properties MIT OR Apache-2.0 +android_system_properties MIT/Apache-2.0 +anes MIT OR Apache-2.0 +anstream MIT OR Apache-2.0 +anstyle MIT OR Apache-2.0 +anstyle-parse MIT OR Apache-2.0 +anstyle-query MIT OR Apache-2.0 +anstyle-wincon MIT OR Apache-2.0 +antlr4-cpp-runtime BSD 2-clause +anyhow MIT OR Apache-2.0 +approx Apache-2.0 +ar_archive_writer Apache-2.0 WITH LLVM-exception +arbitrary MIT OR Apache-2.0 +arbtest MIT OR Apache-2.0 +arc-swap MIT OR Apache-2.0 +arcref MIT +ariadne MIT +arrayvec MIT OR Apache-2.0 +arrow Apache +arrow Apache-2.0 +arrow-arith Apache-2.0 +arrow-array Apache-2.0 +arrow-array Apache-2.0 AND MIT +arrow-buffer Apache-2.0 +arrow-cast Apache-2.0 +arrow-csv Apache-2.0 +arrow-data Apache-2.0 +arrow-ipc Apache-2.0 +arrow-json Apache-2.0 +arrow-ord Apache-2.0 +arrow-row Apache-2.0 +arrow-schema Apache-2.0 +arrow-select Apache-2.0 +arrow-string Apache-2.0 +arrow-testing Apache +ascii Apache-2.0 OR MIT +async-channel Apache-2.0 OR MIT +async-executor Apache-2.0 OR MIT +async-fs Apache-2.0 OR MIT +async-io Apache-2.0 OR MIT +async-lock Apache-2.0 OR MIT +async-net Apache-2.0 OR MIT +async-process Apache-2.0 OR MIT +async-signal Apache-2.0 OR MIT +async-stream MIT +async-stream-impl MIT +async-task Apache-2.0 OR MIT +async-trait MIT OR Apache-2.0 +atoi MIT +atomic-waker Apache-2.0 OR MIT +autocfg Apache-2.0 OR MIT +avro Apache +aws Apache +aws-c-auth Apache +aws-c-cal Apache +aws-c-common Apache +aws-c-compression Apache +aws-c-event-stream Apache +aws-c-http Apache +aws-c-io Apache +aws-c-mqtt Apache +aws-c-s3 Apache +aws-c-sdkutils Apache +aws-checksums Apache +aws-crt-cpp Apache +aws-lc-rs ISC AND (Apache-2.0 OR ISC) +aws-lc-sys ISC AND (Apache-2.0 OR ISC) AND Apache-2.0 AND MIT AND BSD-3-Clause AND (Apache-2.0 OR ISC OR MIT) AND (Apache-2.0 OR ISC OR MIT-0) +azure MIT +backtrace MIT OR Apache-2.0 +base64 MIT OR Apache-2.0 +base64ct Apache-2.0 OR MIT +bech32 MIT +beef MIT OR Apache-2.0 +better_io Apache-2.0 +bindgen BSD-3-Clause +bit-set Apache-2.0 OR MIT +bit-vec Apache-2.0 OR MIT +bitflags MIT OR Apache-2.0 +bitflags MIT/Apache-2.0 +bitvec MIT +block-buffer MIT OR Apache-2.0 +block-padding MIT OR Apache-2.0 +blocking Apache-2.0 OR MIT +boost Boost +brotli BSD-3-Clause AND MIT +brotli MIT +brotli-decompressor BSD-3-Clause/MIT +bs-thread-pool MIT +bstr MIT OR Apache-2.0 +bumpalo MIT OR Apache-2.0 +by_address MIT OR Apache-2.0 +bytemuck Zlib OR Apache-2.0 OR MIT +byteorder Unlicense OR MIT +bytes MIT +bytesize Apache-2.0 +bzip2 MIT/Apache-2.0 +bzip2 bzip2 +bzip2-sys MIT/Apache-2.0 +c-ares MIT +camino MIT OR Apache-2.0 +capnproto MIT +capstone MIT +capstone-sys MIT +cargo-platform MIT OR Apache-2.0 +cargo_metadata MIT +cast MIT OR Apache-2.0 +castaway MIT +cbc MIT OR Apache-2.0 +cbindgen MPL-2.0 +cc MIT OR Apache-2.0 +cccl Apache +cctz Apache +cexpr Apache-2.0/MIT +cfg-if MIT OR Apache-2.0 +cfg-if MIT/Apache-2.0 +cfg_aliases MIT +chacha20 MIT OR Apache-2.0 +chdig MIT +chrono MIT OR Apache-2.0 +chrono-tz MIT OR Apache-2.0 +chrono-tz-build MIT OR Apache-2.0 +chumsky MIT +chunked_transfer MIT OR Apache-2.0 +ciborium Apache-2.0 +ciborium-io Apache-2.0 +ciborium-ll Apache-2.0 +cipher MIT OR Apache-2.0 +cityhash102 MIT +clang-sys Apache-2.0 +clap MIT OR Apache-2.0 +clap_builder MIT OR Apache-2.0 +clap_complete MIT OR Apache-2.0 +clap_derive MIT OR Apache-2.0 +clap_lex MIT OR Apache-2.0 +cld2 Apache +clickhouse-rs-1.1.0 MIT +clickhouse-rs-cityhash-sys MIT +clickstack MIT +cmake MIT OR Apache-2.0 +cobs MIT OR Apache-2.0 +codespan-reporting Apache-2.0 +colorchoice MIT OR Apache-2.0 +combine MIT +comfy-table MIT +compact_str MIT +concurrent-queue Apache-2.0 OR MIT +const-random MIT OR Apache-2.0 +const-random-macro MIT OR Apache-2.0 +const_for MIT +constant_time_eq CC0-1.0 +convert_case MIT +core-foundation MIT OR Apache-2.0 +core-foundation-sys MIT OR Apache-2.0 +core_detect MIT/Apache-2.0 +corrosion MIT +cpp_demangle MIT OR Apache-2.0 +cppkafka BSD 2-clause +cpufeatures MIT OR Apache-2.0 +crc MIT OR Apache-2.0 +crc-catalog MIT OR Apache-2.0 +crc32-s390x Apache +crc32-vpmsum Apache +crc32c BSD 3-clause +crc32fast MIT OR Apache-2.0 +criterion Apache-2.0 OR MIT +criterion-plot Apache-2.0 OR MIT +criterion-plot MIT/Apache-2.0 +critical-section MIT OR Apache-2.0 +croaring Apache +crossbeam MIT OR Apache-2.0 +crossbeam-channel MIT OR Apache-2.0 +crossbeam-deque MIT OR Apache-2.0 +crossbeam-epoch MIT OR Apache-2.0 +crossbeam-queue MIT OR Apache-2.0 +crossbeam-utils MIT OR Apache-2.0 +crossterm MIT +crossterm_winapi MIT +crunchy MIT +crypto-common MIT OR Apache-2.0 +csv Unlicense/MIT +csv-core Unlicense/MIT +ctr MIT OR Apache-2.0 +cty MIT OR Apache-2.0 +cucascade Apache +cuCollections Apache +cudf Apache +custom-labels Apache-2.0 +cxx MIT OR Apache-2.0 +cxx-build MIT OR Apache-2.0 +cxxbridge-cmd MIT OR Apache-2.0 +cxxbridge-flags MIT OR Apache-2.0 +cxxbridge-macro MIT OR Apache-2.0 +cyrus-sasl BSD 2-clause +darling MIT +darling_core MIT +darling_macro MIT +darts-clone BSD +dashmap MIT +datasketches-cpp Apache +datatest-stable MIT OR Apache-2.0 +debugid Apache-2.0 +defer-drop MPL-2.0 +delta-kernel-rs Apache +der Apache-2.0 OR MIT +deranged MIT OR Apache-2.0 +derive_arbitrary MIT/Apache-2.0 +derive_builder MIT OR Apache-2.0 +derive_builder_core MIT OR Apache-2.0 +derive_builder_macro MIT OR Apache-2.0 +derive_more MIT +derive_more-impl MIT +des MIT OR Apache-2.0 +dhat MIT OR Apache-2.0 +digest MIT OR Apache-2.0 +directories-next MIT OR Apache-2.0 +dirs-next MIT OR Apache-2.0 +dirs-sys-next MIT OR Apache-2.0 +displaydoc MIT OR Apache-2.0 +dlmalloc MIT/Apache-2.0 +dlpack Apache +dmlc-core Apache +dns-lookup MIT/Apache-2.0 +document-features MIT OR Apache-2.0 +double-conversion BSD 3-clause +driftsort Apache +dtype_dispatch Apache-2.0 +dunce CC0-1.0 OR MIT-0 OR Apache-2.0 +dyn-clone MIT OR Apache-2.0 +easy-smt MIT OR Apache-2.0 +egg MIT +either MIT OR Apache-2.0 +embedded-io MIT OR Apache-2.0 +encoding_rs (Apache-2.0 OR MIT) AND BSD-3-Clause +enum-as-inner MIT/Apache-2.0 +enum-iterator 0BSD +enum-iterator-derive 0BSD +env_filter MIT OR Apache-2.0 +env_home MIT OR Apache-2.0 +env_logger MIT OR Apache-2.0 +equivalent Apache-2.0 OR MIT +errno MIT OR Apache-2.0 +escape8259 MIT +event-listener Apache-2.0 OR MIT +event-listener-strategy Apache-2.0 OR MIT +ext-trait Zlib OR MIT OR Apache-2.0 +ext-trait-proc_macros Zlib OR MIT OR Apache-2.0 +extension-traits Zlib OR MIT OR Apache-2.0 +fancy-regex MIT +fast_float MIT +fastlanes Apache-2.0 +fastops MIT +fastrand Apache-2.0 OR MIT +file-per-thread-logger Apache-2.0 WITH LLVM-exception +filecheck Apache-2.0 WITH LLVM-exception +filedescriptor MIT +filetime MIT/Apache-2.0 +find-msvc-tools MIT OR Apache-2.0 +fixedbitset MIT/Apache-2.0 +flagset Apache-2.0 +flamelens MIT +flatbuffers Apache +flatbuffers Apache-2.0 +flate2 MIT OR Apache-2.0 +flexi_logger MIT OR Apache-2.0 +fmtlib MIT +fnv Apache-2.0 / MIT +foldhash Zlib +foreign-types MIT/Apache-2.0 +foreign-types-shared MIT/Apache-2.0 +form_urlencoded MIT OR Apache-2.0 +fortanix-sgx-abi MPL-2.0 +FP16 MIT +fs_extra MIT +fslock MIT +fsst-rs Apache-2.0 +funty MIT +futures MIT OR Apache-2.0 +futures-channel MIT OR Apache-2.0 +futures-core MIT OR Apache-2.0 +futures-executor MIT OR Apache-2.0 +futures-io MIT OR Apache-2.0 +futures-lite Apache-2.0 OR MIT +futures-macro MIT OR Apache-2.0 +futures-sink MIT OR Apache-2.0 +futures-task MIT OR Apache-2.0 +futures-timer MIT/Apache-2.0 +futures-util MIT OR Apache-2.0 +fuzzy-matcher MIT +fxprof-processed-profile MIT OR Apache-2.0 +g2gen MIT/Apache-2.0 +g2p MIT/Apache-2.0 +g2poly MIT/Apache-2.0 +gdbstub MIT OR Apache-2.0 +gdbstub_arch MIT OR Apache-2.0 +gdeflate Apache +generic-array MIT +getopts MIT OR Apache-2.0 +getrandom MIT OR Apache-2.0 +ghash Apache-2.0 OR MIT +gimli MIT OR Apache-2.0 +glob MIT OR Apache-2.0 +google-benchmark Apache +google-cloud-cpp Apache +google-protobuf BSD 3-clause +googletest BSD 3-clause +grpc Apache +gzip-header MIT/Apache-2.0 +h2 MIT +h3 Apache +half MIT OR Apache-2.0 +hashbrown MIT OR Apache-2.0 +hdfs-native Apache-2.0 +hdfs-native-object-store Apache-2.0 +heck MIT OR Apache-2.0 +heks MIT +hermit-abi MIT OR Apache-2.0 +hex MIT OR Apache-2.0 +hive-metastore Apache +hmac MIT OR Apache-2.0 +home MIT OR Apache-2.0 +hostname MIT +http MIT OR Apache-2.0 +http-body MIT +http-body-util MIT +httparse MIT OR Apache-2.0 +httpdate MIT OR Apache-2.0 +httpdate MIT/Apache-2.0 +humansize MIT/Apache-2.0 +humantime MIT OR Apache-2.0 +humantime MIT/Apache-2.0 +hyper MIT +hyper-rustls Apache-2.0 OR ISC OR MIT +hyper-tls MIT/Apache-2.0 +hyper-util MIT +iana-time-zone MIT OR Apache-2.0 +iana-time-zone-haiku MIT OR Apache-2.0 +icu Public Domain +icu_collections Unicode-3.0 +icu_locale_core Unicode-3.0 +icu_locid Unicode-3.0 +icu_locid_transform Unicode-3.0 +icu_locid_transform_data Unicode-3.0 +icu_normalizer Unicode-3.0 +icu_normalizer_data Unicode-3.0 +icu_properties Unicode-3.0 +icu_properties_data Unicode-3.0 +icu_provider Unicode-3.0 +icu_provider_macros Unicode-3.0 +icudata Public Domain +id-arena MIT/Apache-2.0 +ident_case MIT/Apache-2.0 +idna MIT +idna MIT OR Apache-2.0 +idna_adapter Apache-2.0 OR MIT +indexmap Apache-2.0 OR MIT +indoc MIT OR Apache-2.0 +inout MIT OR Apache-2.0 +instability MIT +instant BSD-3-Clause +integer-encoding MIT +inventory MIT OR Apache-2.0 +ipcrypt2 ISC +ipnet MIT OR Apache-2.0 +ipnsort Apache +is-terminal MIT +is_terminal_polyfill MIT OR Apache-2.0 +isa-l BSD 3-clause +itertools MIT OR Apache-2.0 +itertools MIT/Apache-2.0 +itoa MIT OR Apache-2.0 +ittapi GPL-2.0-only OR BSD-3-Clause +ittapi-sys GPL-2.0-only OR BSD-3-Clause +jemalloc BSD 2-clause +Jieba-CPP MIT +jiff Unlicense OR MIT +jiff-core Unlicense OR MIT +jiff-static Unlicense OR MIT +jiff-tzdb Unlicense OR MIT +jiff-tzdb-platform Unlicense OR MIT +jni MIT OR Apache-2.0 +jni-macros MIT OR Apache-2.0 +jni-sys MIT OR Apache-2.0 +jni-sys-macros MIT OR Apache-2.0 +jobserver MIT OR Apache-2.0 +js-sys MIT OR Apache-2.0 +json-from-wast Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +jwt-cpp MIT +kanal MIT +kasuari MIT OR Apache-2.0 +krb5 BSD +kvikio Apache +lasso MIT OR Apache-2.0 +lazy_static MIT OR Apache-2.0 +lazy_static MIT/Apache-2.0 +leb128 Apache-2.0/MIT +leb128fmt MIT OR Apache-2.0 +lemmagen-c LGPL +lending-iterator Zlib OR MIT OR Apache-2.0 +lending-iterator-proc_macros Zlib OR MIT OR Apache-2.0 +lexical-core MIT/Apache-2.0 +lexical-parse-float MIT/Apache-2.0 +lexical-parse-integer MIT/Apache-2.0 +lexical-util MIT/Apache-2.0 +lexical-write-float MIT/Apache-2.0 +lexical-write-integer MIT/Apache-2.0 +libarchive Apache +libbcrypt Public Domain +libc MIT OR Apache-2.0 +libcotp Apache +libcpuid BSD 2-clause +libdeflate MIT +libdivide Boost +libfarmhash MIT +libfiu Public Domain +libfuzzer-sys (MIT OR Apache-2.0) AND NCSA +libgsasl LGPL +libhdfs3 Apache +libloading ISC +libm MIT +libmetrohash Apache +libpqxx BSD 3-clause +libprotobuf-mutator Apache +librdkafka Apache +libredox MIT +librseq BSD +librtcx Apache +libssh LGPL +libstemmer_c BSD 3-clause +libtest-mimic MIT/Apache-2.0 +libucontext ISC +liburing MIT +libuv BSD +libxml2 MIT +line-clipping MIT OR Apache-2.0 +link-cplusplus MIT OR Apache-2.0 +linux-raw-sys Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +litemap Unicode-3.0 +litrs MIT OR Apache-2.0 +llvm-project Apache +lock_api MIT OR Apache-2.0 +log MIT OR Apache-2.0 +logos MIT OR Apache-2.0 +logos-codegen MIT OR Apache-2.0 +logos-derive MIT OR Apache-2.0 +lru MIT +lru-slab MIT OR Apache-2.0 OR Zlib +lz4 BSD +lz4 MIT +lz4-sys-1.11.1+lz4 MIT +lz4_flex MIT +mach2 BSD-2-Clause OR MIT OR Apache-2.0 +macro-string MIT OR Apache-2.0 +macro_rules_attribute MIT +macro_rules_attribute-proc_macro MIT +magic_enum MIT +managed 0BSD +mapbox-geometry ISC +mariadb-connector-c LGPL +match_cfg MIT/Apache-2.0 +matchers MIT +matrixmultiply MIT/Apache-2.0 +md-5 MIT OR Apache-2.0 +MeCab BSD +memchr Unlicense OR MIT +memfd MIT OR Apache-2.0 +memmap2 MIT OR Apache-2.0 +mime MIT OR Apache-2.0 +minimal-lexical MIT/Apache-2.0 +miniselect Boost +miniz_oxide MIT OR Zlib OR Apache-2.0 +minizip-ng zLib +mintex Apache-2.0 +mio MIT +moka (MIT OR Apache-2.0) AND Apache-2.0 +mongo-c-driver Apache +mongo-c-driver Third-party notices +mongo-cxx-driver Apache +morton-nd MIT +moto-rt MIT OR Apache-2.0 +msgpack-c Boost +multiversion_no_op Apache-2.0 OR MIT +murmurhash Public Domain +musl Public Domain +mutatis MIT OR Apache-2.0 +mutatis-derive MIT OR Apache-2.0 +nanoarrow Apache +native-tls MIT OR Apache-2.0 +nats-io Apache +ndarray MIT OR Apache-2.0 +never-say-never Zlib OR MIT OR Apache-2.0 +nix MIT +nlohmann-json MIT +nom MIT +nougat Zlib OR MIT OR Apache-2.0 +nougat-proc_macros Zlib OR MIT OR Apache-2.0 +nu-ansi-term MIT +num-bigint MIT OR Apache-2.0 +num-complex MIT OR Apache-2.0 +num-conv MIT OR Apache-2.0 +num-integer MIT OR Apache-2.0 +num-traits MIT OR Apache-2.0 +num_cpus MIT OR Apache-2.0 +num_enum BSD-3-Clause OR MIT OR Apache-2.0 +num_enum_derive BSD-3-Clause OR MIT OR Apache-2.0 +num_threads MIT OR Apache-2.0 +NuRaft Apache +nvtx Apache +object Apache-2.0 OR MIT +object_store MIT/Apache-2.0 +ocaml-boxroot-sys MIT +ocaml-interop MIT +ocaml-sys ISC +once_cell MIT OR Apache-2.0 +once_cell_polyfill MIT OR Apache-2.0 +oneshot MIT OR Apache-2.0 +onpair Apache-2.0 +oorandom MIT +opaque-debug MIT OR Apache-2.0 +openldap OpenLDAP Version 2.8 +openssl Apache +openssl Apache-2.0 +openssl-macros MIT/Apache-2.0 +openssl-probe MIT OR Apache-2.0 +openssl-probe MIT/Apache-2.0 +openssl-sys MIT +openvino Apache-2.0 +openvino-finder Apache-2.0 +openvino-sys Apache-2.0 +optimized-routines Apache +ordered-float MIT +ort-2.0.0 MIT OR Apache-2.0 +ort-sys-2.0.0 MIT OR Apache-2.0 +page_size MIT/Apache-2.0 +palette MIT OR Apache-2.0 +palette_derive MIT OR Apache-2.0 +palette_math MIT OR Apache-2.0 +parking Apache-2.0 OR MIT +parking_lot MIT OR Apache-2.0 +parking_lot_core MIT OR Apache-2.0 +parquet Apache-2.0 +parquet-testing Apache +parse-zoneinfo MIT +password-hash MIT OR Apache-2.0 +paste MIT OR Apache-2.0 +pastey MIT OR Apache-2.0 +pbkdf2 MIT OR Apache-2.0 +pco Apache-2.0 +pcodec Apache +pdqsort zLib +pem-rfc7468 Apache-2.0 OR MIT +percent-encoding MIT OR Apache-2.0 +perfetto_protos Apache-2.0 +pest MIT OR Apache-2.0 +pest_derive MIT OR Apache-2.0 +pest_generator MIT OR Apache-2.0 +pest_meta MIT OR Apache-2.0 +petgraph MIT OR Apache-2.0 +phf MIT +phf_codegen MIT +phf_generator MIT +phf_shared MIT +pin-project Apache-2.0 OR MIT +pin-project-internal Apache-2.0 OR MIT +pin-project-lite Apache-2.0 OR MIT +pin-utils MIT OR Apache-2.0 +piper MIT OR Apache-2.0 +pkg-config MIT OR Apache-2.0 +plain MIT/Apache-2.0 +plotters MIT +plotters-backend MIT +plotters-svg MIT +pocketfft BSD 3-clause +poco Boost +polling Apache-2.0 OR MIT +polonius-the-crab Zlib OR MIT OR Apache-2.0 +polyglot-sql MIT +polyval Apache-2.0 OR MIT +portable-atomic Apache-2.0 OR MIT +portable-atomic-util Apache-2.0 OR MIT +postcard MIT OR Apache-2.0 +postgres PostgreSQL +potential_utf Unicode-3.0 +powerfmt MIT OR Apache-2.0 +ppv-lite86 MIT OR Apache-2.0 +ppv-lite86 MIT/Apache-2.0 +prettyplease MIT OR Apache-2.0 +proc-macro-crate MIT OR Apache-2.0 +proc-macro2 MIT OR Apache-2.0 +prometheus-protobufs Apache +prometheus-protobufs-gogo BSD 3-clause +proptest MIT OR Apache-2.0 +prost Apache-2.0 +prost-derive Apache-2.0 +prost-types Apache-2.0 +protobuf MIT +protobuf-codegen MIT +protobuf-parse MIT +protobuf-support MIT +protoc-bin-vendored MIT +protoc-bin-vendored-linux-aarch_64 MIT +protoc-bin-vendored-linux-ppcle_64 MIT +protoc-bin-vendored-linux-s390_64 MIT +protoc-bin-vendored-linux-x86_32 MIT +protoc-bin-vendored-linux-x86_64 MIT +protoc-bin-vendored-macos-aarch_64 MIT +protoc-bin-vendored-macos-x86_64 MIT +protoc-bin-vendored-win32 MIT +prqlc Apache-2.0 +prqlc-parser Apache-2.0 +psm MIT OR Apache-2.0 +pulldown-cmark MIT +pybind11 BSD 3-clause +pybind11-upstream BSD 3-clause +quick-error MIT/Apache-2.0 +quick-xml MIT +quinn MIT OR Apache-2.0 +quinn-proto MIT OR Apache-2.0 +quinn-udp MIT OR Apache-2.0 +quote MIT OR Apache-2.0 +r-efi MIT OR Apache-2.0 OR LGPL-2.1-or-later +r-efi-alloc MIT OR Apache-2.0 OR LGPL-2.1-or-later +radium MIT +rand MIT OR Apache-2.0 +rand_chacha MIT OR Apache-2.0 +rand_core MIT OR Apache-2.0 +rand_pcg MIT OR Apache-2.0 +rand_xorshift MIT OR Apache-2.0 +rand_xoshiro MIT OR Apache-2.0 +rapidjson BSD +rapids-logger Apache +ratatui MIT +ratatui-core MIT +ratatui-crossterm MIT +ratatui-widgets MIT +raw-cpuid MIT +rawpointer MIT/Apache-2.0 +rayon MIT OR Apache-2.0 +rayon-core MIT OR Apache-2.0 +re2 BSD 3-clause +recursive MIT +recursive-proc-macro-impl MIT +redox_syscall MIT +redox_users MIT +ref-cast MIT OR Apache-2.0 +ref-cast-impl MIT OR Apache-2.0 +regalloc2 Apache-2.0 WITH LLVM-exception +regex MIT OR Apache-2.0 +regex-automata MIT OR Apache-2.0 +regex-syntax MIT OR Apache-2.0 +region MIT +relative-path MIT OR Apache-2.0 +replxx BSD 3-clause +reqwest MIT OR Apache-2.0 +ring Apache-2.0 AND ISC +rmm Apache +roaring MIT OR Apache-2.0 +rocksdb BSD 3-clause +roxmltree MIT OR Apache-2.0 +rstest MIT OR Apache-2.0 +rstest_macros MIT OR Apache-2.0 +rstest_reuse MIT OR Apache-2.0 +rustc-demangle MIT/Apache-2.0 +rustc-hash Apache-2.0 OR MIT +rustc-hash Apache-2.0/MIT +rustc-literal-escaper Apache-2.0 OR MIT +rustc_version MIT OR Apache-2.0 +rustix Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +rustix-linux-procfs Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +rustls Apache-2.0 OR ISC OR MIT +rustls-native-certs Apache-2.0 OR ISC OR MIT +rustls-pemfile Apache-2.0 OR ISC OR MIT +rustls-pki-types MIT OR Apache-2.0 +rustls-platform-verifier MIT OR Apache-2.0 +rustls-platform-verifier-android MIT OR Apache-2.0 +rustls-webpki ISC +rustversion MIT OR Apache-2.0 +rusty-fork MIT/Apache-2.0 +ryu Apache-2.0 OR BSL-1.0 +s2geometry Apache +safetensors Apache-2.0 +same-file Unlicense/MIT +schannel MIT +schemars MIT +schemars_derive MIT +scopeguard MIT OR Apache-2.0 +scratch MIT OR Apache-2.0 +security-framework MIT OR Apache-2.0 +security-framework-sys MIT OR Apache-2.0 +semver MIT OR Apache-2.0 +seq-macro MIT OR Apache-2.0 +serde MIT OR Apache-2.0 +serde_core MIT OR Apache-2.0 +serde_derive MIT OR Apache-2.0 +serde_derive_internals MIT OR Apache-2.0 +serde_json MIT OR Apache-2.0 +serde_norway MIT OR Apache-2.0 +serde_spanned MIT OR Apache-2.0 +serde_urlencoded MIT/Apache-2.0 +serde_yaml MIT OR Apache-2.0 +sha1 MIT OR Apache-2.0 +sha2 MIT OR Apache-2.0 +SHA3IUF MIT +sharded-slab MIT +shell-quote Apache-2.0 +shlex MIT OR Apache-2.0 +shuffling-allocator MPL-2.0 +signal-hook Apache-2.0/MIT +signal-hook-mio MIT OR Apache-2.0 +signal-hook-registry Apache-2.0/MIT +signal-hook-registry MIT OR Apache-2.0 +silk Apache +simd-adler32 MIT +simd_cesu8 Apache-2.0 OR MIT +simdcomp BSD 3-clause +simdjson MIT +simdutf MIT +simdutf8 MIT OR Apache-2.0 +similar Apache-2.0 +SimSIMD Apache +siphasher MIT OR Apache-2.0 +siphasher MIT/Apache-2.0 +size MIT +sketches-ddsketch Apache-2.0 +skim MIT +skim-common MIT +skim-tuikit MIT +slab MIT +smallvec MIT OR Apache-2.0 +smallvec-2.0.0 MIT OR Apache-2.0 +smol Apache-2.0 OR MIT +snap BSD-3-Clause +snappy BSD 3-clause +socket2 MIT OR Apache-2.0 +socks MIT/Apache-2.0 +souper-ir MIT OR Apache-2.0 +sparsehash-c11 BSD 3-clause +spdlog MIT +spin MIT +spmc MIT OR Apache-2.0 +sqids-cpp MIT +sql-console Apache +sqlformat MIT OR Apache-2.0 +sqlite-amalgamation BSD 3-clause +sqlparser Apache-2.0 +stable_deref_trait MIT OR Apache-2.0 +stable_deref_trait MIT/Apache-2.0 +stacker MIT OR Apache-2.0 +static_assertions MIT OR Apache-2.0 +strfmt MIT +string-interner MIT/Apache-2.0 +StringZilla Apache +strsim MIT +strum MIT +strum_macros MIT +substrait Apache +subtle BSD-3-Clause +symbolic_expressions MIT/Apache-2.0 +syn MIT OR Apache-2.0 +sync_wrapper Apache-2.0 +synstructure MIT +system-configuration MIT OR Apache-2.0 +system-configuration-sys MIT OR Apache-2.0 +sz3 BSD +tagptr MIT/Apache-2.0 +tap MIT +tar MIT OR Apache-2.0 +target-lexicon Apache-2.0 WITH LLVM-exception +target-triple MIT OR Apache-2.0 +tch MIT/Apache-2.0 +tempfile MIT OR Apache-2.0 +term MIT OR Apache-2.0 +term MIT/Apache-2.0 +termcolor Unlicense OR MIT +terminal_size MIT OR Apache-2.0 +termtree MIT +test-case MIT +test-case-core MIT +test-case-macros MIT +test-log Apache-2.0 OR MIT +test-log-core Apache-2.0 OR MIT +test-log-macros Apache-2.0 OR MIT +thiserror MIT OR Apache-2.0 +thiserror-impl MIT OR Apache-2.0 +thousands MIT/Apache-2.0 +thread_local Apache-2.0/MIT +thread_local MIT OR Apache-2.0 +thrift Apache +thrift Apache-2.0 +time MIT OR Apache-2.0 +time-core MIT OR Apache-2.0 +time-macros MIT OR Apache-2.0 +timer MPL-2.0 +tiny-keccak CC0-1.0 +tiny_http MIT OR Apache-2.0 +tinystr Unicode-3.0 +tinytemplate Apache-2.0 OR MIT +tinyvec Zlib OR Apache-2.0 OR MIT +tinyvec_macros MIT OR Apache-2.0 OR Zlib +tokio MIT +tokio-macros MIT +tokio-native-tls MIT +tokio-openssl MIT/Apache-2.0 +tokio-rustls MIT OR Apache-2.0 +tokio-util MIT +toml-0.9.12+spec MIT OR Apache-2.0 +toml-1.1.2+spec MIT OR Apache-2.0 +toml-1.1.4+spec MIT OR Apache-2.0 +toml_datetime-0.7.5+spec MIT OR Apache-2.0 +toml_datetime-1.1.1+spec MIT OR Apache-2.0 +toml_edit-0.25.11+spec MIT OR Apache-2.0 +toml_edit-0.25.13+spec MIT OR Apache-2.0 +toml_parser-1.1.2+spec MIT OR Apache-2.0 +toml_parser-1.1.3+spec MIT OR Apache-2.0 +toml_parser-1.1.5+spec MIT OR Apache-2.0 +toml_writer-1.1.1+spec MIT OR Apache-2.0 +toml_writer-1.1.2+spec MIT OR Apache-2.0 +toml_writer-1.2.0+spec MIT OR Apache-2.0 +torch-sys MIT/Apache-2.0 +tower MIT +tower-http MIT +tower-layer MIT +tower-service MIT +tracing MIT +tracing-attributes MIT +tracing-core MIT +tracing-log MIT +tracing-serde MIT +tracing-subscriber MIT +try-lock MIT +trybuild MIT OR Apache-2.0 +tui-input MIT +twox-hash MIT +typenum MIT OR Apache-2.0 +ucd-trie MIT OR Apache-2.0 +unarray MIT OR Apache-2.0 +unicase MIT OR Apache-2.0 +unicode-ident (MIT OR Apache-2.0) AND Unicode-3.0 +unicode-segmentation MIT OR Apache-2.0 +unicode-segmentation MIT/Apache-2.0 +unicode-truncate MIT OR Apache-2.0 +unicode-width MIT OR Apache-2.0 +unicode-width MIT/Apache-2.0 +unicode-xid MIT OR Apache-2.0 +unicode_categories MIT OR Apache-2.0 +universal-hash MIT OR Apache-2.0 +unsafe-libyaml MIT +unsafe-libyaml-norway MIT +untrusted ISC +unwinding MIT OR Apache-2.0 +ureq MIT OR Apache-2.0 +ureq-proto MIT OR Apache-2.0 +url MIT OR Apache-2.0 +usearch Apache +utf-8 MIT OR Apache-2.0 +utf16_iter Apache-2.0 OR MIT +utf8-zero MIT OR Apache-2.0 +utf8_iter Apache-2.0 OR MIT +utf8parse Apache-2.0 OR MIT +utf8proc MIT +utf_types Apache-2.0 OR MIT +uuid Apache-2.0 OR MIT +v8 MIT +valuable MIT +vcpkg MIT/Apache-2.0 +vectorscan Boost +vergen MIT OR Apache-2.0 +vergen-gitcl MIT OR Apache-2.0 +vergen-lib MIT OR Apache-2.0 +version_check MIT/Apache-2.0 +vex-sdk MIT +vortex Apache-2.0 +vortex-alp Apache-2.0 +vortex-array Apache-2.0 +vortex-array-macros Apache-2.0 +vortex-arrow Apache-2.0 +vortex-btrblocks Apache-2.0 +vortex-buffer Apache-2.0 +vortex-bytebool Apache-2.0 +vortex-compressor Apache-2.0 +vortex-compute Apache-2.0 +vortex-datetime-parts Apache-2.0 +vortex-decimal-byte-parts Apache-2.0 +vortex-edition Apache-2.0 +vortex-error Apache-2.0 +vortex-fastlanes Apache-2.0 +vortex-file Apache-2.0 +vortex-flatbuffers Apache-2.0 +vortex-fsst Apache-2.0 +vortex-io Apache-2.0 +vortex-ipc Apache-2.0 +vortex-layout Apache-2.0 +vortex-mask Apache-2.0 +vortex-metrics Apache-2.0 +vortex-onpair Apache-2.0 +vortex-pco Apache-2.0 +vortex-proto Apache-2.0 +vortex-runend Apache-2.0 +vortex-scan Apache-2.0 +vortex-sequence Apache-2.0 +vortex-session Apache-2.0 +vortex-sparse Apache-2.0 +vortex-utils Apache-2.0 +vortex-zigzag Apache-2.0 +vortex-zstd Apache-2.0 +vte Apache-2.0 OR MIT +wagyu Boost +wait-timeout MIT/Apache-2.0 +waker-fn Apache-2.0 OR MIT +walkdir Unlicense/MIT +want MIT +wasi-0.11.0+wasi-snapshot Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wasi-0.11.1+wasi-snapshot Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wasi-0.13.3+wasi Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wasi-nn Apache-2.0 +wasip1 Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wasip2-1.0.0+wasi Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wasip2-1.0.3+wasi Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wasip2-1.0.4+wasi Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wasip2-2.0.1+wasi Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wasip3-0.4.0+wasi-0.3.0-rc-2026-01 Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wasip3-0.9.0+wasi Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wasite Apache-2.0 OR BSL-1.0 OR MIT +wasm-bindgen MIT OR Apache-2.0 +wasm-bindgen-futures MIT OR Apache-2.0 +wasm-bindgen-macro MIT OR Apache-2.0 +wasm-bindgen-macro-support MIT OR Apache-2.0 +wasm-bindgen-shared MIT OR Apache-2.0 +wasm-compose Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wasm-encoder Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wasm-metadata Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wasm-mutate Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wasm-smith Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wasm-streams MIT OR Apache-2.0 +wasm-wave Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wasmi MIT/Apache-2.0 +wasmi_collections MIT/Apache-2.0 +wasmi_core MIT/Apache-2.0 +wasmi_ir MIT/Apache-2.0 +wasmparser Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wasmprinter Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wasmtime Apache +wast Apache-2.0 WITH LLVM-exception +wast Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wat Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +web-sys MIT OR Apache-2.0 +web-time MIT OR Apache-2.0 +webpki-root-certs CDLA-Permissive-2.0 +webpki-roots CDLA-Permissive-2.0 +which MIT +whoami Apache-2.0 OR BSL-1.0 OR MIT +winapi MIT/Apache-2.0 +winapi-i686-pc-windows-gnu MIT/Apache-2.0 +winapi-util Unlicense OR MIT +winapi-util Unlicense/MIT +winapi-x86_64-pc-windows-gnu MIT/Apache-2.0 +windows MIT OR Apache-2.0 +windows-core MIT OR Apache-2.0 +windows-implement MIT OR Apache-2.0 +windows-interface MIT OR Apache-2.0 +windows-link MIT OR Apache-2.0 +windows-registry MIT OR Apache-2.0 +windows-result MIT OR Apache-2.0 +windows-strings MIT OR Apache-2.0 +windows-sys MIT OR Apache-2.0 +windows-targets MIT OR Apache-2.0 +windows_aarch64_gnullvm MIT OR Apache-2.0 +windows_aarch64_msvc MIT OR Apache-2.0 +windows_i686_gnu MIT OR Apache-2.0 +windows_i686_gnullvm MIT OR Apache-2.0 +windows_i686_msvc MIT OR Apache-2.0 +windows_x86_64_gnu MIT OR Apache-2.0 +windows_x86_64_gnullvm MIT OR Apache-2.0 +windows_x86_64_msvc MIT OR Apache-2.0 +winnow MIT +winsafe MIT +wit-bindgen Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wit-bindgen-core Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wit-bindgen-rt Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wit-bindgen-rust Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wit-bindgen-rust-macro Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wit-component Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +wit-parser Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT +witx Apache-2.0 +write16 Apache-2.0 OR MIT +writeable Unicode-3.0 +wstd Apache-2.0 WITH LLVM-exception +wstd-macro Apache-2.0 WITH LLVM-exception +wyhash Public Domain +wyz MIT +xattr MIT OR Apache-2.0 +xed-sys-0.6.0+xed Apache-2.0 +xgboost Apache +xsimd BSD 3-clause +xxHash BSD +xz LGPL +yaml-cpp MIT +yansi MIT OR Apache-2.0 +yoke Unicode-3.0 +yoke-derive Unicode-3.0 +z85 MIT/Apache-2.0 +zerocopy BSD-2-Clause OR Apache-2.0 OR MIT +zerocopy-derive BSD-2-Clause OR Apache-2.0 OR MIT +zerofrom Unicode-3.0 +zerofrom-derive Unicode-3.0 +zeroize Apache-2.0 OR MIT +zerotrie Unicode-3.0 +zerovec Unicode-3.0 +zerovec-derive Unicode-3.0 +zigzag MIT +zip MIT +zlib-ng zLib +zlib-rs Zlib +zmij MIT +zstd BSD +zstd BSD-3-Clause +zstd MIT +zstd-safe BSD-3-Clause +zstd-safe MIT OR Apache-2.0 +zstd-safe MIT/Apache-2.0 +zstd-sys BSD-3-Clause AND BSD-2-Clause +zstd-sys MIT/Apache-2.0 +zxc BSD +zxc Third-party notices diff --git a/pom.xml b/pom.xml index 7c43d91..1775fcd 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.clickhouse.chdb chdb-java-parent - 1.1.0 + 1.2.0-SNAPSHOT pom chDB Java Binding (parent) @@ -65,7 +65,7 @@ mirrors them for the shell/CMake side. Changing engine.version requires a new Maven version (work plan section 4.3) and a full platform re-test. --> - 26.11.1 + 26.11.2-rc.3 1 5 diff --git a/scripts/build-native.sh b/scripts/build-native.sh index d6c5107..cba51ee 100755 --- a/scripts/build-native.sh +++ b/scripts/build-native.sh @@ -369,18 +369,18 @@ else Most entries are permissively licensed, and several that a filename scan would call GPL are dual licensed with the permissive half in force: zstd is BSD-3, rocksdb is - Apache-2.0, liburing is MIT, ittapi is BSD-3-Clause. Eleven carry a copyleft licence + Apache-2.0, liburing is MIT, ittapi is BSD-3-Clause. Ten carry a copyleft licence with no permissive alternative: lemmagen-c, libgsasl, libssh, mariadb-connector-c, xz (LGPL) cbindgen, defer-drop, fortanix-sgx-abi, shuffling-allocator, - timer, webpki-roots (MPL-2.0) + timer (MPL-2.0) MPL-2.0 is file-level copyleft and its obligations are lighter than LGPL's, which attach differently under static linking than under dynamic. - Whether any of the eleven is actually linked into this binary cannot be determined + Whether any of the ten is actually linked into this binary cannot be determined from the binary: it is stripped, and static linking leaves no dynamic symbols to inspect. That question belongs to the engine build. diff --git a/scripts/engine.properties b/scripts/engine.properties index 8f18e05..c59d59a 100644 --- a/scripts/engine.properties +++ b/scripts/engine.properties @@ -6,17 +6,21 @@ # keep this file in sync with in the root pom.xml. # # Checksums are the release asset digests published by GitHub for the tag below -# (gh api repos/chdb-io/chdb-core/releases/tags/v26.11.1 --jq '.assets[].digest'), and +# (gh api repos/chdb-io/chdb-core/releases/tags/v26.11.2-rc.3 --jq '.assets[].digest'), and # the release's SHA256SUMS asset agrees with them. # # engine.version is what chdb_version() returns from the shared library, not the tag with # its 'v' stripped and not the version in the wheel file names. The loader compares the two -# and refuses a mismatch. The vendored header must come from a v26.11.1 release +# and refuses a mismatch. The vendored header must come from a v26.11.2-rc.3 release # tarball; the runtime version and all four platforms must pass the real-JAR matrix. # -# v26.11.1 is a stable chdb-core release (published 2026-11-16), tag commit -# bc9c42e6edf4f394884a6a0458aa49abff85f1b6. It follows the rc.3 Arrow fixes. -# The previous published Java 1.0.0-rc.2 remains pinned to v26.11.0-rc.2. +# v26.11.2-rc.3 is a chdb-core PRE-RELEASE (published 2026-11-30), tag commit +# eb9986c3ee39afc7665b734d8daabc57d481b833. Over v26.11.1 it adds the scalar function ABI +# (chdb_create_scalar_function / chdb_drop_scalar_function, chdb-core #352) and the +# restrict_local_filesystem_access connection option (#349), and syncs ClickHouse master +# twice (#314, #348) although version() still reports 26.11.1.1. A Java binding pinned to +# this core RC is itself an RC (work plan section 4.3): only 1.2.0-rc. can be cut from it. +# Java 1.1.0 stays on v26.11.1. # # chdb-core #224, the fix for the signal-handler window reported as chdb-core #221 and # tracked here as issue #14, arrived in v26.7.3: scripts/run-signal-window-test.sh measure @@ -27,12 +31,14 @@ # over ~1.08M samples a run, and stress 6 survived 6 of 6 with 0 killed. # Re-run on v26.11.0-rc.2, on linux-x86_64: measure 3 reported hostHandlersAtSigDfl=0/0/0 # over ~1.11-1.25M samples a run, and stress 6 survived 6 of 6 with 0 killed. -# v26.11.1 must be retested in the four-platform CI before a Java release. +# Re-run on v26.11.2-rc.3, on linux-x86_64: measure 3 reported hostHandlersAtSigDfl=0/0/0 +# over ~1.20-1.24M samples a run, and stress 6 survived 6 of 6 with 0 killed. +# v26.11.2-rc.3 must be retested in the four-platform CI before a Java release. -engine.version=26.11.1 -engine.tag=v26.11.1 +engine.version=26.11.2-rc.3 +engine.tag=v26.11.2-rc.3 engine.repo=chdb-io/chdb-core -engine.asset.base=https://github.com/chdb-io/chdb-core/releases/download/v26.11.1 +engine.asset.base=https://github.com/chdb-io/chdb-core/releases/download/v26.11.2-rc.3 # platform id -> release asset name asset.macos-aarch64=macos-arm64-libchdb.tar.gz @@ -41,10 +47,10 @@ asset.linux-x86_64-gnu=linux-x86_64-libchdb.tar.gz asset.linux-aarch64-gnu=linux-aarch64-libchdb.tar.gz # platform id -> SHA-256 of the release asset -sha256.macos-aarch64=c0a4df14c10369ce86b5e58f6b9cfade30b155cea6908cc7556c2a73ef18cd08 -sha256.macos-x86_64=ace512c37c673075b59b551574d3c77edf159a8bf2d1b9d829ef0721a9ececd8 -sha256.linux-x86_64-gnu=210f34d85596f8580176bee4c58b688e05d9389d87eb51f4ff94ae08294c65a7 -sha256.linux-aarch64-gnu=86a618b092036ceca5f41b2bfdb6b38253ab2d704a1dd577a3cbb351a0256698 +sha256.macos-aarch64=3e38152b3c6cc9b7a49827e233e64dfae4a0ce101a39f56d921acadc06a129da +sha256.macos-x86_64=474a02ad54f46432c4302ccffa9bf9d2aeb53d6c5a33c7ca9e136ea6052eba01 +sha256.linux-x86_64-gnu=cd07ba6f07882bfd0007128e187cfdad36e0998f49fa184b183b2bda8283a8a7 +sha256.linux-aarch64-gnu=9426e4fda66ad44fda2e5f33699b2b3f7293c7d7d60a7ca2e4a022c26bf38703 # platform id -> the libchdb file name inside the extracted tarball / the name we ship libname.macos-aarch64=libchdb.so @@ -56,11 +62,12 @@ libname.linux-aarch64-gnu=libchdb.so # # Must not exceed what the engine supports, or the package refuses to load for users in # between. These are the versions chdb-core's own release wheels declare -# (chdb_core-26.11.1-cp39-abi3-macosx_11_0_arm64.whl and ...-macosx_10_15_x86_64.whl), and +# (chdb_core-26.11.2-cp39-abi3-macosx_11_0_arm64.whl and ...-macosx_10_15_x86_64.whl), and # build-native.sh fails the build if the shim ends up above the engine's. # -# These targets were measured against earlier 26.11 builds. Build-native.sh checks the v26.11.1 -# assets on their respective CI runners and refuses a shim whose minimum exceeds its engine. +# Re-read from the v26.11.2-rc.3 dylibs themselves: LC_BUILD_VERSION minos is 11.0 on arm64 and +# 10.15 on x86_64, as before. build-native.sh still checks the assets on their own CI runners +# and refuses a shim whose minimum exceeds its engine. # # Left unset, the target follows the build machine's SDK: an unpinned build on a macOS 26 # host produced a shim demanding macOS 26 beside an engine that runs on 11. @@ -78,8 +85,9 @@ deployment.target.macos-x86_64=10.15 # below it is out of support: RHEL 7 (2.17) ended June 2024 and Amazon Linux 2 (2.26) June # 2026. Everything above it is already covered. # -# The last v26.11.0-rc.2 measurements had room under this ceiling. The v26.11.1 -# engine and newly linked shim are remeasured by build-native.sh in Linux CI. +# The v26.11.2-rc.3 engines need GLIBC_2.4 (x86_64) and GLIBC_2.17 (aarch64), read from their +# dynamic symbol tables, unchanged from v26.11.1. The newly linked shim is remeasured by +# build-native.sh in Linux CI. # # What this cannot check from a macOS host is the *shim's* floor, which is the thing the # ceiling actually guards. That is measured in the Linux jobs, where build-native.sh reads it From f04a8bb6fe59b858858bbb412c071f593ea4e996 Mon Sep 17 00:00:00 2001 From: wudidapaopao Date: Tue, 1 Dec 2026 06:42:50 +0000 Subject: [PATCH 2/4] Add scalar functions written in Java 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) --- .agents/skills/chdb-arrow/SKILL.md | 1 + .github/workflows/build.yml | 5 +- README.md | 36 +- chdb-arrow/README.md | 48 +- .../org/chdb/arrow/ArrowFunctionCallback.java | 60 ++ .../java/org/chdb/arrow/ArrowFunctions.java | 38 + .../org/chdb/arrow/ArrowScalarFunction.java | 32 + .../arrow/ArrowScalarFunctionBuilder.java | 139 ++++ .../org/chdb/arrow/ArrowFunctionsTest.java | 316 ++++++++ .../java/org/chdb/it/ScalarFunctionIT.java | 536 +++++++++++++ .../java/org/chdb/internal/ArrowColumn.java | 74 ++ .../java/org/chdb/internal/ArrowDecoder.java | 362 +++++++++ .../java/org/chdb/internal/ArrowEncoder.java | 532 +++++++++++++ .../java/org/chdb/internal/ChdbNative.java | 53 +- .../chdb/internal/ScalarFunctionCallback.java | 143 ++++ .../internal/ScalarFunctionException.java | 18 + .../java/org/chdb/jdbc/ChdbConnection.java | 48 ++ .../java/org/chdb/jdbc/ChdbExceptions.java | 17 + .../java/org/chdb/jdbc/ChdbFunctions.java | 190 +++++ .../java/org/chdb/jdbc/ChdbRowFunction.java | 26 + .../chdb/jdbc/ChdbScalarFunctionBuilder.java | 207 +++++ .../org/chdb/jdbc/RowFunctionCallback.java | 47 ++ .../java/org/chdb/jdbc/StatementSlot.java | 9 + .../org/chdb/internal/ArrowDecoderTest.java | 288 +++++++ .../org/chdb/internal/ArrowEncoderTest.java | 229 ++++++ .../internal/ScalarFunctionCallbackTest.java | 116 +++ .../jdbc/ChdbScalarFunctionBuilderTest.java | 83 ++ chdb-jni/CMakeLists.txt | 17 +- chdb-jni/src/arrow_c_abi.h | 61 ++ chdb-jni/src/chdb_jni.cpp | 727 ++++++++++++++++++ chdb-jni/src/chdb_jni_functions.cpp | 455 +++++++++++ chdb-jni/src/chdb_jni_functions.h | 79 ++ chdb-jni/src/chdb_jni_handles.h | 4 +- chdb-jni/src/chdb_optional_api.cpp | 3 + chdb-jni/src/chdb_optional_api.h | 46 ++ chdb-jni/test/chdb_jni_test.cpp | 305 ++++++++ docs/scalar-functions.md | 292 +++++++ docs/unsupported.md | 3 +- docs/upstream-findings.md | 11 + docs/v1-progress.md | 2 +- pom.xml | 2 +- 41 files changed, 5644 insertions(+), 16 deletions(-) create mode 100644 chdb-arrow/src/main/java/org/chdb/arrow/ArrowFunctionCallback.java create mode 100644 chdb-arrow/src/main/java/org/chdb/arrow/ArrowFunctions.java create mode 100644 chdb-arrow/src/main/java/org/chdb/arrow/ArrowScalarFunction.java create mode 100644 chdb-arrow/src/main/java/org/chdb/arrow/ArrowScalarFunctionBuilder.java create mode 100644 chdb-arrow/src/test/java/org/chdb/arrow/ArrowFunctionsTest.java create mode 100644 chdb-integration-tests/src/test/java/org/chdb/it/ScalarFunctionIT.java create mode 100644 chdb-jdbc/src/main/java/org/chdb/internal/ArrowColumn.java create mode 100644 chdb-jdbc/src/main/java/org/chdb/internal/ArrowDecoder.java create mode 100644 chdb-jdbc/src/main/java/org/chdb/internal/ArrowEncoder.java create mode 100644 chdb-jdbc/src/main/java/org/chdb/internal/ScalarFunctionCallback.java create mode 100644 chdb-jdbc/src/main/java/org/chdb/internal/ScalarFunctionException.java create mode 100644 chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbFunctions.java create mode 100644 chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbRowFunction.java create mode 100644 chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbScalarFunctionBuilder.java create mode 100644 chdb-jdbc/src/main/java/org/chdb/jdbc/RowFunctionCallback.java create mode 100644 chdb-jdbc/src/test/java/org/chdb/internal/ArrowDecoderTest.java create mode 100644 chdb-jdbc/src/test/java/org/chdb/internal/ArrowEncoderTest.java create mode 100644 chdb-jdbc/src/test/java/org/chdb/internal/ScalarFunctionCallbackTest.java create mode 100644 chdb-jdbc/src/test/java/org/chdb/jdbc/ChdbScalarFunctionBuilderTest.java create mode 100644 chdb-jni/src/arrow_c_abi.h create mode 100644 chdb-jni/src/chdb_jni_functions.cpp create mode 100644 chdb-jni/src/chdb_jni_functions.h create mode 100644 docs/scalar-functions.md diff --git a/.agents/skills/chdb-arrow/SKILL.md b/.agents/skills/chdb-arrow/SKILL.md index 57669f4..9a25b6b 100644 --- a/.agents/skills/chdb-arrow/SKILL.md +++ b/.agents/skills/chdb-arrow/SKILL.md @@ -9,4 +9,5 @@ Java Database Connectivity (JDBC) returns row-oriented `ResultSet` values. Arrow - Keep row-oriented applications on `chdb-jdbc`. For Java Arrow objects use optional `chdb-arrow` and `ArrowSession`; a caller-owned `VectorSchemaRoot` uses `registerBatch(root, allocator)` and `source.fromSql()`. A one-shot `ArrowReader` uses `registerOwnedReader(reader, allocator)`, which takes ownership of the reader. Keep the allocator alive after the source and query are closed. - Typed output: `queryArrowMaterialized(sql, allocator)` returns a closable reader after the query; `queryArrow(sql, allocator)` returns `ArrowQuery`, whose `loadNextBatch()` reuses its current root. Bulk insert into an existing table: `insertBatch(table, root, allocator)` or `insertOwnedReader(table, reader, allocator)`. Prefer try-with-resources. +- Java code called from SQL as a scalar function: `ChdbFunctions.scalarFunction()` in chdb-jdbc computes it a row at a time with Java values and needs no Arrow; `ArrowFunctions.scalarFunction()` in chdb-arrow computes it a batch at a time with Arrow vectors. Both need chdb-core v26.11.2-rc.3 or later and register for the whole JVM, not the connection; `docs/scalar-functions.md` has the rules. - Use a verified Java ADBC driver-manager pairing when an application already requires standard ADBC result streams or bulk ingest. General ADBC `BindStream` binds parameters, not a temporary `FROM` source; it does not replace `registerOwnedReader`. Do not force Arrow dependencies on JDBC-only consumers. Start with `chdb-arrow/README.md` for this binding's documentation map and examples. diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c3b7de3..b76c91d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -470,8 +470,9 @@ jobs: run: scripts/fetch-libchdb.sh ${{ matrix.platform }} target/engine/${{ matrix.platform }} - name: ASan and UBSan over the shim's own logic - # chdb_jni_test: the handle registry and the signal guard, with no JVM and no engine - # in the process, so ASan's allocator interception is safe. + # chdb_jni_test: the handle registry, the signal guard, and the Arrow buffer sizing and + # result arrays behind scalar functions, with no JVM and no engine in the process, so + # ASan's allocator interception is safe. run: scripts/run-sanitizer-tests.sh ${{ matrix.platform }} address,undefined - name: UBSan over the whole JDBC suite diff --git a/README.md b/README.md index accc8d1..7c8526b 100644 --- a/README.md +++ b/README.md @@ -203,6 +203,38 @@ have their own, and the driver refuses with a diagnosis rather than mapping a se engine. In Tomcat, Spark or Flink this decides where the driver goes. See [docs/classloaders.md](docs/classloaders.md). +## Scalar functions written in Java + +Java code can be called from SQL as a scalar function. The API follows duckdb-java's: + +```java +ChdbFunctions.scalarFunction() + .withName("plus_one") + .withParameter("Int64") + .withReturnType("Int64") + .withFunction((Long x) -> x + 1) + .register(connection); +// SELECT plus_one(toInt64(number)) FROM numbers(3) -> 1, 2, 3 +``` + +Types are ClickHouse type names, and values reach the function as the Java types `getObject` +gives, with `java.time` for dates and timestamps. Three things differ from what you might expect: + +- **One registry per JVM.** A function belongs to the engine, not to the connection that + registered it: every connection sees it, and it stays until it is dropped, with + `ChdbFunctions.dropScalarFunction(name)` or by closing what `register` returned. +- **NULLs are skipped by default.** A row with a NULL argument yields NULL without a call, the + opposite of duckdb-java's default; `withSpecialNullHandling()` passes them. +- **It runs on the engine's threads**, several at once, so it must be thread-safe, and it must + not use chDB: a statement started from inside it is refused rather than left to deadlock. + +`withVolatile()` stops chDB folding a call into one value, and `withBinaryStrings()` passes +`String` arguments as `byte[]`. The optional `chdb-arrow` module adds `ArrowFunctions`, the same +declaration computed a batch at a time with Arrow vectors. It needs chdb-core **v26.11.2-rc.3** +or later; against an older engine everything else works and registering a function fails with a +message saying so. [docs/scalar-functions.md](docs/scalar-functions.md) has the whole type mapping +and the rules. + ## What works today | | | @@ -216,6 +248,7 @@ engine. In Tomcat, Spark or Flink this decides where the driver goes. See | ✅ | Bounded memory on results far larger than the heap | | ✅ | Host JVM signal handlers preserved — see [signal handlers](docs/signal-handlers.md) | | ✅ | Native loading from the platform JAR, or a directory you point at | +| ✅ | Scalar functions written in Java, row at a time or with Arrow batches — see [scalar functions](docs/scalar-functions.md) | | 🚧 | Framework smoke tests — HikariCP, MyBatis and jOOQ pass, and nothing on the full `DatabaseMetaData` surface throws; Spring `JdbcTemplate` is not yet verified, and ShardingSphere cannot parse a `jdbc:chdb:` URL at all — see [under a framework](docs/unsupported.md#under-a-framework) | | 🚧 | Soak tests; full-process ASan, which needs an upstream sanitizer build of chdb-core | | ❌ | Transactions, batch updates, scrollable/updatable result sets, `CallableStatement` | @@ -269,6 +302,7 @@ but not exercised on an old macOS, because no such runner exists. | | | |---|---| | [Type mapping](docs/type-mapping.md) | ClickHouse ↔ JDBC ↔ Java, and how timezones are decided | +| [Scalar functions](docs/scalar-functions.md) | Java functions called from SQL: the API, the type mapping, NULLs, threads and the JVM-wide registry | | [Unsupported JDBC](docs/unsupported.md) | What throws `SQLFeatureNotSupportedException`, and what to do instead | | [Native loading](docs/native-loading.md) | Where libraries come from, cache layout, system properties, error messages | | [Signal handlers](docs/signal-handlers.md) | What chDB does to your JVM's handlers, what the driver does about it, what you lose | @@ -317,7 +351,7 @@ The resulting package is stamped `engine.source=local` and must not be published ``` chdb-jdbc/ pure-Java driver, loader and type mapping -chdb-jni/ the JNI shim (C++17, ~1400 lines) +chdb-jni/ the JNI shim (C++17, ~3300 lines) chdb-native-/ one Maven package per platform chdb-bom/ legacy RC BOM (not published to Central) chdb-integration-tests/ tests that need a real engine diff --git a/chdb-arrow/README.md b/chdb-arrow/README.md index 0bbe454..dfc6c4b 100644 --- a/chdb-arrow/README.md +++ b/chdb-arrow/README.md @@ -11,6 +11,7 @@ It exchanges Arrow data through the native C Data/C Stream interfaces rather tha | Query an in-memory Java Arrow batch or reader | [Query a caller-owned Arrow batch](#query-a-caller-owned-arrow-batch) and [API and ownership notes](#api-and-ownership-notes) below | | Read typed results or insert a batch | [Read SQL results as Arrow batches](#read-sql-results-as-arrow-batches), [Insert a batch](#insert-a-batch-into-an-existing-table), and [`ArrowSessionTest`](src/test/java/org/chdb/arrow/ArrowSessionTest.java) | | Check output type options | [`ArrowOptions`](src/main/java/org/chdb/arrow/ArrowOptions.java) and [its tests](src/test/java/org/chdb/arrow/ArrowOptionsTest.java) | +| Call Java from SQL as a scalar function, a batch at a time | [Scalar functions on Arrow batches](#scalar-functions-on-arrow-batches) below, the [scalar function guide](../docs/scalar-functions.md) and [`ArrowFunctionsTest`](src/test/java/org/chdb/arrow/ArrowFunctionsTest.java) | | Decide on Arrow Database Connectivity (ADBC) instead | An existing, verified Java ADBC client can use standard Arrow results or bulk ingest. It does not replace `registerOwnedReader` for a temporary SQL `FROM` source; Java Database Connectivity (JDBC) `ResultSet` is a separate row-oriented API. | This module README is the Java binding's Arrow entry point. See the [core ownership contract](https://github.com/chdb-io/chdb-core/blob/main/docs/NATIVE_ARROW_BINDING_CONTRACT.md) for native ABI details; the standard JDBC docs are not Arrow usage instructions. @@ -74,6 +75,7 @@ import org.apache.arrow.memory.RootAllocator; import org.apache.arrow.vector.BigIntVector; import org.apache.arrow.vector.VectorSchemaRoot; import org.apache.arrow.vector.ipc.ArrowReader; +import org.chdb.arrow.ArrowFunctions; import org.chdb.arrow.ArrowQuery; import org.chdb.arrow.ArrowSession; import org.chdb.arrow.RegisteredArrowSource; @@ -171,6 +173,44 @@ the engine default. For example, ArrowInsertOptions.REJECT_NULL_AS_DEFAULT)`. Validate source and destination types before ingest. +### Scalar functions on Arrow batches + +`ArrowFunctions.scalarFunction()` registers a Java function that SQL calls with a batch of rows +at a time: it receives the arguments as a `VectorSchemaRoot`, one vector per declared parameter +in order, and returns one `FieldVector` holding a value per row. Parameters and the result are +ClickHouse type names, and the result vector may be any Arrow type chDB converts to the declared +one. This needs chdb-core v26.11.2-rc.3 or later. + +```java +try (Connection connection = DriverManager.getConnection("jdbc:chdb::memory:")) { + ArrowFunctions.scalarFunction() + .withName("add") + .withParameters("Int64", "Int64") + .withReturnType("Int64") + .withFunction((arguments, allocator) -> { + BigIntVector left = (BigIntVector) arguments.getVector(0); + BigIntVector right = (BigIntVector) arguments.getVector(1); + BigIntVector sum = new BigIntVector("sum", allocator); + sum.allocateNew(arguments.getRowCount()); + for (int i = 0; i < arguments.getRowCount(); i++) { + sum.set(i, left.get(i) + right.get(i)); + } + sum.setValueCount(arguments.getRowCount()); + return sum; + }) + .register(connection); +} +``` + +The arguments are imported through the C Data Interface without a copy and closed when the call +returns; the result is exported the same way and then owned by chDB. The `allocator` passed in +belongs to the registration, which closes it once chDB has released the function. A function is +registered for the whole JVM rather than for the connection, sees no NULL argument unless +registered `withSpecialNullHandling()`, and runs on the engine's threads, several at once, where +it must not use chDB. chdb-jdbc's `ChdbFunctions` is the row-at-a-time form of the same API, and +drops either kind; [the scalar function guide](../docs/scalar-functions.md) has the rules and +the Arrow types chDB sends. + ## API and ownership notes `ArrowSession.openInMemory()` opens a dedicated JDBC-managed connection to the process-wide @@ -238,10 +278,10 @@ associated copy/allocation cost. ## Testing from source -The test `ArrowSessionTest` is opt-in (`-Dchdb.arrow.it=true`) and requires a matching -engine and JNI shim in the directory given by `-Dchdb.library.path`. The published -`1.1.0-rc.1` platform JAR has JNI ABI 5; the older `1.0.0-rc.2` ABI 2 package is not -interchangeable. Arrow Java 19.0.0 on classpath also requires +The tests `ArrowSessionTest` and `ArrowFunctionsTest` are opt-in (`-Dchdb.arrow.it=true`) and +require a matching engine and JNI shim in the directory given by `-Dchdb.library.path`. This +source builds JNI ABI 6; the published `1.1.0-rc.1` platform JAR has ABI 5 and the older +`1.0.0-rc.2` ABI 2, so neither is interchangeable with it. Arrow Java 19.0.0 on classpath also requires `--add-opens=java.base/java.nio=ALL-UNNAMED` on supported JDKs. The current source pins chDB core `26.11.2-rc.3`, a pre-release. For a macOS arm64 diff --git a/chdb-arrow/src/main/java/org/chdb/arrow/ArrowFunctionCallback.java b/chdb-arrow/src/main/java/org/chdb/arrow/ArrowFunctionCallback.java new file mode 100644 index 0000000..b0d90f9 --- /dev/null +++ b/chdb-arrow/src/main/java/org/chdb/arrow/ArrowFunctionCallback.java @@ -0,0 +1,60 @@ +package org.chdb.arrow; + +import org.apache.arrow.c.ArrowArray; +import org.apache.arrow.c.ArrowSchema; +import org.apache.arrow.c.Data; +import org.apache.arrow.memory.BufferAllocator; +import org.apache.arrow.memory.RootAllocator; +import org.apache.arrow.vector.FieldVector; +import org.apache.arrow.vector.VectorSchemaRoot; +import org.chdb.internal.ScalarFunctionCallback; +import org.chdb.internal.ScalarFunctionException; + +/** + * Runs an {@link ArrowScalarFunction} over each batch chDB passes, through Arrow Java's C Data + * Interface: the arguments are imported without a copy, and the result is exported the same way. + * + *

    Memory

    + * Importing moves chDB's argument array into Arrow Java, which releases it back to chDB when the + * imported vectors close. Exporting hands chDB a reference to the result's buffers, which chDB + * drops by calling the array's release -- on an engine thread, after this call returned. So the + * buffers have to come from an allocator that outlives every batch: one owned by the registration, + * and closed only when chDB destroys the function, after the last query that used it. + */ +final class ArrowFunctionCallback extends ScalarFunctionCallback { + + private final ArrowScalarFunction function; + private final BufferAllocator allocator = new RootAllocator(); + + ArrowFunctionCallback(ArrowScalarFunction function) { + this.function = function; + } + + @Override + protected void apply(long argumentSchema, long arguments, long resultSchema, long result) throws Exception { + try (VectorSchemaRoot batch = Data.importVectorSchemaRoot( + allocator, ArrowArray.wrap(arguments), ArrowSchema.wrap(argumentSchema), null)) { + FieldVector values = function.apply(batch, allocator); + if (values == null) { + throw new ScalarFunctionException("the function returned null instead of a vector"); + } + try { + if (values.getValueCount() != batch.getRowCount()) { + throw new ScalarFunctionException("the function returned " + values.getValueCount() + + " values for a batch of " + batch.getRowCount() + " rows"); + } + Data.exportVector(allocator, values, null, ArrowArray.wrap(result), ArrowSchema.wrap(resultSchema)); + } finally { + // The export holds its own references to the buffers, until chDB releases them. + values.close(); + } + } + } + + @Override + protected void release() { + // Throws if a function kept a buffer past its call -- a transferred argument it never + // closed -- and the allocator then stays open with it rather than freeing memory in use. + allocator.close(); + } +} diff --git a/chdb-arrow/src/main/java/org/chdb/arrow/ArrowFunctions.java b/chdb-arrow/src/main/java/org/chdb/arrow/ArrowFunctions.java new file mode 100644 index 0000000..54fd7cb --- /dev/null +++ b/chdb-arrow/src/main/java/org/chdb/arrow/ArrowFunctions.java @@ -0,0 +1,38 @@ +package org.chdb.arrow; + +/** + * Scalar user-defined functions computed with Arrow vectors, a batch of rows per call. + * + *
    {@code
    + * ArrowFunctions.scalarFunction()
    + *         .withName("weighted")
    + *         .withParameters("Float64", "Float64")
    + *         .withReturnType("Float64")
    + *         .withFunction((arguments, allocator) -> {
    + *             Float8Vector values = (Float8Vector) arguments.getVector(0);
    + *             Float8Vector weights = (Float8Vector) arguments.getVector(1);
    + *             Float8Vector out = new Float8Vector("weighted", allocator);
    + *             out.allocateNew(arguments.getRowCount());
    + *             for (int i = 0; i < arguments.getRowCount(); i++) {
    + *                 out.set(i, values.get(i) * weights.get(i));
    + *             }
    + *             out.setValueCount(arguments.getRowCount());
    + *             return out;
    + *         })
    + *         .register(connection);
    + * }
    + * + *

    The arguments arrive as chDB sends them, through Arrow's C Data Interface without a copy; + * the result goes back the same way. The registry, the flags and the threading are chdb-jdbc's: + * see {@code org.chdb.jdbc.ChdbFunctions}, which also drops these functions. + */ +public final class ArrowFunctions { + + private ArrowFunctions() { + } + + /** Starts declaring a scalar function computed a batch at a time. */ + public static ArrowScalarFunctionBuilder scalarFunction() { + return new ArrowScalarFunctionBuilder(); + } +} diff --git a/chdb-arrow/src/main/java/org/chdb/arrow/ArrowScalarFunction.java b/chdb-arrow/src/main/java/org/chdb/arrow/ArrowScalarFunction.java new file mode 100644 index 0000000..5f1bb14 --- /dev/null +++ b/chdb-arrow/src/main/java/org/chdb/arrow/ArrowScalarFunction.java @@ -0,0 +1,32 @@ +package org.chdb.arrow; + +import org.apache.arrow.memory.BufferAllocator; +import org.apache.arrow.vector.FieldVector; +import org.apache.arrow.vector.VectorSchemaRoot; + +/** + * A scalar function computed one batch of rows at a time, with Arrow vectors. Registered with + * {@link ArrowScalarFunctionBuilder#withFunction}. + * + *

    chDB calls it from several of its own threads at once, so it must be safe for concurrent + * use, and it runs inside a query, so it must not use chDB. + */ +@FunctionalInterface +public interface ArrowScalarFunction { + + /** + * Computes one batch. + * + * @param arguments one vector per declared parameter, in declaration order -- read them by + * index, since their names are chDB's {@code c0}, {@code c1}, ... -- holding the batch's + * rows. Valid only during the call: it is closed when the call returns, so transfer what + * you keep. + * @param allocator for the result, and for anything else the call allocates. It belongs to the + * registration, which closes it once chDB has dropped the function. + * @return a vector of exactly {@code arguments.getRowCount()} values, of any Arrow type chDB + * converts to the declared return type. The result is exported to chDB and then closed, + * so it must not be used afterwards. It may be one of the argument vectors. + * @throws Exception to fail the query, with the exception as its error message + */ + FieldVector apply(VectorSchemaRoot arguments, BufferAllocator allocator) throws Exception; +} diff --git a/chdb-arrow/src/main/java/org/chdb/arrow/ArrowScalarFunctionBuilder.java b/chdb-arrow/src/main/java/org/chdb/arrow/ArrowScalarFunctionBuilder.java new file mode 100644 index 0000000..1ec50f4 --- /dev/null +++ b/chdb-arrow/src/main/java/org/chdb/arrow/ArrowScalarFunctionBuilder.java @@ -0,0 +1,139 @@ +package org.chdb.arrow; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import org.chdb.internal.ScalarFunctionCallback; +import org.chdb.jdbc.ChdbConnection; +import org.chdb.jdbc.ChdbFunctions; + +/** + * Declares a scalar function computed a batch at a time with Arrow vectors, and registers it. + * From {@link ArrowFunctions#scalarFunction()}. + * + *

    The same declaration as chdb-jdbc's {@code ChdbScalarFunctionBuilder} -- ClickHouse type + * names, the same flags, the same process-wide registration -- with an {@link ArrowScalarFunction} + * in place of a function of Java values. Use it for nested types, for types the row-at-a-time + * mapping does not cover, or to avoid a call per row. + */ +public final class ArrowScalarFunctionBuilder { + + private String name; + private final List parameters = new ArrayList<>(); + private String returnType; + private int flags; + private ArrowScalarFunction function; + + ArrowScalarFunctionBuilder() { + } + + /** The name SQL calls the function by. Case-sensitive. */ + public ArrowScalarFunctionBuilder withName(String name) { + Objects.requireNonNull(name, "name"); + if (name.trim().isEmpty()) { + throw new IllegalArgumentException("a scalar function name cannot be empty"); + } + this.name = name; + return this; + } + + /** Declares the next parameter, as a ClickHouse type name. */ + public ArrowScalarFunctionBuilder withParameter(String clickHouseType) { + parameters.add(typeName(clickHouseType)); + return this; + } + + /** Declares the next parameters, in order. */ + public ArrowScalarFunctionBuilder withParameters(String... clickHouseTypes) { + for (String type : clickHouseTypes) { + withParameter(type); + } + return this; + } + + /** + * The ClickHouse type of the result. The vector the function returns is converted to it the + * way CAST does, and a value that does not fit fails the query. + */ + public ArrowScalarFunctionBuilder withReturnType(String clickHouseType) { + this.returnType = typeName(clickHouseType); + return this; + } + + /** As {@code ChdbScalarFunctionBuilder.withVolatile()}: never folded into one call for all rows. */ + public ArrowScalarFunctionBuilder withVolatile() { + flags |= ScalarFunctionCallback.VOLATILE; + return this; + } + + /** + * Passes rows with NULL arguments to the function, as Arrow nulls, and keeps the return type + * as declared. By default such a row yields NULL without reaching the function. + */ + public ArrowScalarFunctionBuilder withSpecialNullHandling() { + flags |= ScalarFunctionCallback.SPECIAL_NULL_HANDLING; + return this; + } + + /** + * Passes {@code String} arguments, at any depth, as Arrow binary ({@code VarBinaryVector}) + * instead of UTF-8 ({@code VarCharVector}), for data that is not valid UTF-8. + */ + public ArrowScalarFunctionBuilder withBinaryStrings() { + flags |= ScalarFunctionCallback.BINARY_STRINGS; + return this; + } + + /** The function. */ + public ArrowScalarFunctionBuilder withFunction(ArrowScalarFunction function) { + this.function = Objects.requireNonNull(function, "function"); + return this; + } + + /** + * Registers the function through {@code connection}, which must be a chDB connection or wrap + * one. The registration is process-wide and outlives the connection; close what this returns, + * or call {@link ChdbFunctions#dropScalarFunction}, to drop it. + * + * @throws IllegalStateException if the name, the return type or the function is missing + * @throws SQLException if chDB refuses the registration, or the loaded engine cannot register + * functions + */ + public ChdbFunctions.RegisteredFunction register(Connection connection) throws SQLException { + Objects.requireNonNull(connection, "connection"); + if (name == null || returnType == null || function == null) { + throw new IllegalStateException( + "a scalar function needs withName, withReturnType and withFunction before register"); + } + ChdbConnection chdb; + try { + chdb = connection.unwrap(ChdbConnection.class); + } catch (SQLException e) { + throw new SQLException("Scalar functions are registered through a chDB connection, and " + + connection.getClass().getName() + " is not one and does not wrap one", "HY000", e); + } + ArrowFunctionCallback callback = new ArrowFunctionCallback(function); + boolean registered = false; + try { + ChdbFunctions.RegisteredFunction handle = + chdb.registerScalarFunctionNative(name, parameters, returnType, flags, callback); + registered = true; + return handle; + } finally { + if (!registered) { + // Never reached chDB, so chDB will never destroy it: close its allocator here. + callback.abandon(); + } + } + } + + private static String typeName(String clickHouseType) { + Objects.requireNonNull(clickHouseType, "clickHouseType"); + if (clickHouseType.trim().isEmpty()) { + throw new IllegalArgumentException("a ClickHouse type name cannot be empty"); + } + return clickHouseType; + } +} diff --git a/chdb-arrow/src/test/java/org/chdb/arrow/ArrowFunctionsTest.java b/chdb-arrow/src/test/java/org/chdb/arrow/ArrowFunctionsTest.java new file mode 100644 index 0000000..02c5072 --- /dev/null +++ b/chdb-arrow/src/test/java/org/chdb/arrow/ArrowFunctionsTest.java @@ -0,0 +1,316 @@ +package org.chdb.arrow; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import org.apache.arrow.memory.BufferAllocator; +import org.apache.arrow.vector.BigIntVector; +import org.apache.arrow.vector.BitVector; +import org.apache.arrow.vector.DateDayVector; +import org.apache.arrow.vector.FieldVector; +import org.apache.arrow.vector.Float8Vector; +import org.apache.arrow.vector.TimeStampSecTZVector; +import org.apache.arrow.vector.UInt8Vector; +import org.apache.arrow.vector.VarBinaryVector; +import org.apache.arrow.vector.VarCharVector; +import org.apache.arrow.vector.complex.ListVector; +import org.chdb.internal.ChdbNative; +import org.chdb.internal.ScalarFunctionCallback; +import org.chdb.jdbc.ChdbFunctions; +import org.chdb.jdbc.ChdbFunctions.RegisteredFunction; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; + +/** + * Scalar functions computed with Arrow vectors. Run with a matching libchdb and JNI shim via + * -Dchdb.library.path, like {@code ArrowSessionTest}; the engine must have the scalar function ABI. + */ +@EnabledIfSystemProperty(named = "chdb.arrow.it", matches = "true") +class ArrowFunctionsTest { + + private final List registered = new ArrayList<>(); + private Connection connection; + + @BeforeEach + void open() throws SQLException { + connection = DriverManager.getConnection("jdbc:chdb::memory:"); + assertTrue(ChdbFunctions.isScalarFunctionSupported(), + "engine " + ChdbNative.engineVersion() + " lacks the scalar function ABI"); + } + + @AfterEach + void dropAndClose() throws SQLException { + for (RegisteredFunction function : registered) { + function.close(); + } + connection.close(); + assertEquals(0, ScalarFunctionCallback.liveCount(), "scalar functions chDB has not destroyed"); + } + + private void register(ArrowScalarFunctionBuilder builder) throws SQLException { + registered.add(builder.register(connection)); + } + + private static ArrowScalarFunctionBuilder function(String name, String returnType, String... parameters) { + return ArrowFunctions.scalarFunction().withName(name).withReturnType(returnType).withParameters(parameters); + } + + private List query(String sql) throws SQLException { + return query(connection, sql); + } + + private static List query(Connection on, String sql) throws SQLException { + List rows = new ArrayList<>(); + try (Statement statement = on.createStatement(); ResultSet rs = statement.executeQuery(sql)) { + while (rs.next()) { + rows.add(rs.getString(1)); + } + } + return rows; + } + + private static BigIntVector longs(BufferAllocator allocator, int rows) { + BigIntVector out = new BigIntVector("out", allocator); + out.allocateNew(rows); + out.setValueCount(rows); + return out; + } + + @Test + void addsBatchesAcrossTheEngineThreads() throws SQLException { + AtomicInteger batches = new AtomicInteger(); + register(function("a_add", "Int64", "Int64", "Int64").withFunction((arguments, allocator) -> { + batches.incrementAndGet(); + BigIntVector left = (BigIntVector) arguments.getVector(0); + BigIntVector right = (BigIntVector) arguments.getVector(1); + BigIntVector out = longs(allocator, arguments.getRowCount()); + for (int i = 0; i < arguments.getRowCount(); i++) { + out.set(i, left.get(i) + right.get(i)); + } + return out; + })); + assertEquals(Arrays.asList("2000001000000"), + query("SELECT sum(a_add(toInt64(number), 1)) FROM numbers(2000000) SETTINGS max_threads = 8")); + assertTrue(batches.get() >= 2, "one call per block, not per row: " + batches.get() + " calls"); + } + + @Test + void zeroArgumentFunctionsAndVolatility() throws SQLException { + AtomicLong counter = new AtomicLong(); + ArrowScalarFunction next = (arguments, allocator) -> { + BigIntVector out = longs(allocator, arguments.getRowCount()); + for (int i = 0; i < arguments.getRowCount(); i++) { + out.set(i, counter.incrementAndGet()); + } + return out; + }; + register(function("a_next", "Int64").withFunction(next)); + register(function("a_next_volatile", "Int64").withVolatile().withFunction(next)); + assertEquals(Arrays.asList("1"), query("SELECT count(DISTINCT a_next()) FROM numbers(5)")); + assertEquals(Arrays.asList("5"), query("SELECT count(DISTINCT a_next_volatile()) FROM numbers(5)")); + } + + @Test + void stringsBinaryStringsAndReturningAnArgument() throws SQLException { + AtomicReference> argument = new AtomicReference<>(); + register(function("a_echo", "String", "String").withFunction((arguments, allocator) -> { + argument.set(arguments.getVector(0).getClass()); + return (FieldVector) arguments.getVector(0); + })); + assertEquals(Arrays.asList("0", "héllo"), query("SELECT a_echo(arrayJoin(['0', 'héllo']))")); + assertEquals(VarCharVector.class, argument.get()); + + register(function("a_byte_length", "UInt64", "String").withBinaryStrings().withFunction((arguments, allocator) -> { + argument.set(arguments.getVector(0).getClass()); + VarBinaryVector bytes = (VarBinaryVector) arguments.getVector(0); + UInt8Vector out = new UInt8Vector("out", allocator); + out.allocateNew(arguments.getRowCount()); + for (int i = 0; i < arguments.getRowCount(); i++) { + out.set(i, bytes.get(i).length); + } + out.setValueCount(arguments.getRowCount()); + return out; + })); + assertEquals(Arrays.asList("3"), query("SELECT a_byte_length(unhex('FF00FF'))")); + assertEquals(VarBinaryVector.class, argument.get()); + } + + @Test + void nullHandling() throws SQLException { + AtomicLong nullsSeen = new AtomicLong(); + register(function("a_plus_one", "Int64", "Int64").withFunction((arguments, allocator) -> { + BigIntVector in = (BigIntVector) arguments.getVector(0); + nullsSeen.addAndGet(in.getNullCount()); + BigIntVector out = longs(allocator, arguments.getRowCount()); + for (int i = 0; i < arguments.getRowCount(); i++) { + out.set(i, in.get(i) + 1); + } + return out; + })); + assertEquals(Arrays.asList(null, "2", null, "4"), + query("SELECT a_plus_one(if(number % 2 = 0, NULL, toInt64(number))) FROM numbers(4)")); + assertEquals(0, nullsSeen.get(), "a row with a NULL argument does not reach the function by default"); + + register(function("a_is_null", "Bool", "Int64").withSpecialNullHandling().withFunction((arguments, allocator) -> { + FieldVector in = arguments.getVector(0); + BitVector out = new BitVector("out", allocator); + out.allocateNew(arguments.getRowCount()); + for (int i = 0; i < arguments.getRowCount(); i++) { + out.set(i, in.isNull(i) ? 1 : 0); + } + out.setValueCount(arguments.getRowCount()); + return out; + })); + assertEquals(Arrays.asList("false", "true", "false"), + query("SELECT a_is_null(if(number = 1, NULL, toInt64(number))) FROM numbers(3)")); + assertEquals(Arrays.asList("Bool"), query("SELECT toTypeName(a_is_null(toNullable(toInt64(1))))")); + } + + @Test + void nestedAndTemporalArgumentsArriveAsArrowTypes() throws SQLException { + register(function("a_array_sum", "Int64", "Array(Int64)").withFunction((arguments, allocator) -> { + ListVector lists = (ListVector) arguments.getVector(0); + BigIntVector elements = (BigIntVector) lists.getDataVector(); + BigIntVector out = longs(allocator, arguments.getRowCount()); + for (int i = 0; i < arguments.getRowCount(); i++) { + long sum = 0; + for (int j = lists.getElementStartIndex(i); j < lists.getElementEndIndex(i); j++) { + sum += elements.get(j); + } + out.set(i, sum); + } + return out; + })); + assertEquals(Arrays.asList("6", "0"), query("SELECT a_array_sum(arrayJoin([[1, 2, 3], []]))")); + + AtomicReference zone = new AtomicReference<>(); + register(function("a_seconds", "Int64", "DateTime('Asia/Shanghai')", "Date").withFunction((arguments, allocator) -> { + TimeStampSecTZVector times = (TimeStampSecTZVector) arguments.getVector(0); + DateDayVector days = (DateDayVector) arguments.getVector(1); + zone.set(times.getTimeZone()); + BigIntVector out = longs(allocator, arguments.getRowCount()); + for (int i = 0; i < arguments.getRowCount(); i++) { + out.set(i, times.get(i) - days.get(i) * 86400L); + } + return out; + })); + assertEquals(Arrays.asList("10800"), + query("SELECT a_seconds(toDateTime('2024-01-02 11:00:00', 'Asia/Shanghai'), toDate('2024-01-02'))")); + assertEquals("Asia/Shanghai", zone.get()); + } + + @Test + void resultsConvertToTheDeclaredType() throws SQLException { + // Any Arrow type chDB converts without loss: a float64 for Float32, text for a Decimal. + register(function("a_third", "Float32", "Float64").withFunction((arguments, allocator) -> { + Float8Vector in = (Float8Vector) arguments.getVector(0); + Float8Vector out = new Float8Vector("out", allocator); + out.allocateNew(arguments.getRowCount()); + for (int i = 0; i < arguments.getRowCount(); i++) { + out.set(i, in.get(i) / 3); + } + out.setValueCount(arguments.getRowCount()); + return out; + })); + assertEquals(Arrays.asList("Float32"), query("SELECT toTypeName(a_third(1))")); + register(function("a_price", "Decimal(10, 2)", "Int64").withFunction((arguments, allocator) -> { + VarCharVector out = new VarCharVector("out", allocator); + out.allocateNew(arguments.getRowCount()); + for (int i = 0; i < arguments.getRowCount(); i++) { + out.set(i, "12.34".getBytes(StandardCharsets.UTF_8)); + } + out.setValueCount(arguments.getRowCount()); + return out; + })); + assertEquals(Arrays.asList("12.34"), query("SELECT toString(a_price(1))")); + } + + @Test + void failuresBecomeQueryErrors() throws SQLException { + register(function("a_throws", "Int64", "Int64").withFunction((arguments, allocator) -> { + throw new IllegalStateException("no batches today"); + })); + register(function("a_null", "Int64", "Int64").withFunction((arguments, allocator) -> null)); + register(function("a_long", "Int64", "Int64").withFunction((arguments, allocator) -> + longs(allocator, arguments.getRowCount() + 1))); + SQLException thrown = assertThrows(SQLException.class, () -> query("SELECT a_throws(1)")); + assertTrue(thrown.getMessage().contains("java.lang.IllegalStateException: no batches today"), thrown.getMessage()); + SQLException nothing = assertThrows(SQLException.class, () -> query("SELECT a_null(1)")); + assertTrue(nothing.getMessage().contains("returned null instead of a vector"), nothing.getMessage()); + SQLException tooLong = assertThrows(SQLException.class, () -> query("SELECT a_long(1)")); + assertTrue(tooLong.getMessage().contains("returned 2 values for a batch of 1 rows"), tooLong.getMessage()); + assertEquals(Arrays.asList("1"), query("SELECT 1")); + } + + @Test + void concurrentQueriesShareTheFunction() throws Exception { + register(function("a_double", "Int64", "Int64").withFunction((arguments, allocator) -> { + BigIntVector in = (BigIntVector) arguments.getVector(0); + BigIntVector out = longs(allocator, arguments.getRowCount()); + for (int i = 0; i < arguments.getRowCount(); i++) { + out.set(i, in.get(i) * 2); + } + return out; + })); + ExecutorService pool = Executors.newFixedThreadPool(4); + try { + List>> results = new ArrayList<>(); + for (int t = 0; t < 4; t++) { + results.add(pool.submit(() -> { + try (Connection own = DriverManager.getConnection("jdbc:chdb::memory:")) { + List last = null; + for (int run = 0; run < 3; run++) { + last = query(own, "SELECT sum(a_double(toInt64(number))) FROM numbers(300000)"); + } + return last; + } + })); + } + for (Future> result : results) { + assertEquals(Arrays.asList("89999700000"), result.get(60, TimeUnit.SECONDS)); + } + } finally { + pool.shutdownNow(); + } + } + + @Test + void theAllocatorIsEmptyOnceTheFunctionIsDropped() throws SQLException { + AtomicReference used = new AtomicReference<>(); + RegisteredFunction function = function("a_length", "Int64", "String").withFunction((arguments, allocator) -> { + used.set(allocator); + VarCharVector in = (VarCharVector) arguments.getVector(0); + BigIntVector out = longs(allocator, arguments.getRowCount()); + for (int i = 0; i < arguments.getRowCount(); i++) { + out.set(i, in.get(i).length); + } + return out; + }).register(connection); + assertEquals(Arrays.asList("10"), query("SELECT sum(a_length(toString(number))) FROM numbers(10)")); + assertEquals(1, ScalarFunctionCallback.liveCount()); + function.close(); + // The imported arguments went back to chDB and chDB released every exported result, so the + // allocator closed with nothing in it. + assertEquals(0, ScalarFunctionCallback.liveCount()); + assertEquals(0, used.get().getAllocatedMemory()); + } +} diff --git a/chdb-integration-tests/src/test/java/org/chdb/it/ScalarFunctionIT.java b/chdb-integration-tests/src/test/java/org/chdb/it/ScalarFunctionIT.java new file mode 100644 index 0000000..b476e9c --- /dev/null +++ b/chdb-integration-tests/src/test/java/org/chdb/it/ScalarFunctionIT.java @@ -0,0 +1,536 @@ +package org.chdb.it; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.lang.reflect.Proxy; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.net.InetAddress; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLFeatureNotSupportedException; +import java.sql.Statement; +import java.time.Duration; +import java.time.Instant; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import org.chdb.internal.ChdbNative; +import org.chdb.internal.ScalarFunctionCallback; +import org.chdb.jdbc.ChdbFunctions; +import org.chdb.jdbc.ChdbFunctions.RegisteredFunction; +import org.chdb.jdbc.ChdbScalarFunctionBuilder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +/** + * Scalar functions computed one row at a time, against the real engine. + * + *

    Every function a test registers is dropped after it, and {@link NativeTestBase} then checks + * that chDB destroyed them all: a registration chDB still holds is a leaked global reference. + * The engine must have the scalar function ABI; a run against one without it fails here rather + * than skipping, as the Arrow tests do for their ABI. + */ +@Timeout(value = 2, unit = TimeUnit.MINUTES) +class ScalarFunctionIT extends NativeTestBase { + + private final List registered = new ArrayList<>(); + private Connection connection; + + @BeforeAll + static void engineHasTheAbi() throws SQLException { + // Asserted rather than trusted: a libchdb picked up from anywhere but the staged pair + // would make every result below meaningless. + assertEquals(System.getProperty("chdb.it.engine.version"), ChdbNative.engineVersion()); + assertTrue(ChdbFunctions.isScalarFunctionSupported(), "the pinned engine must export the scalar function ABI"); + } + + @BeforeEach + void open() throws SQLException { + connection = openMemory(); + } + + @AfterEach + void dropAndClose() throws SQLException { + for (RegisteredFunction function : registered) { + function.close(); + } + connection.close(); + // Dropped with no query using them, so chDB destroys them inside the drop. + assertEquals(0, ScalarFunctionCallback.liveCount(), "scalar functions chDB has not destroyed"); + } + + private RegisteredFunction register(ChdbScalarFunctionBuilder builder) throws SQLException { + RegisteredFunction function = builder.register(connection); + registered.add(function); + return function; + } + + private static ChdbScalarFunctionBuilder function(String name, String returnType, String... parameters) { + return ChdbFunctions.scalarFunction().withName(name).withReturnType(returnType).withParameters(parameters); + } + + /** The first column of every row, as text. */ + private List query(String sql) throws SQLException { + return query(connection, sql); + } + + private static List query(Connection on, String sql) throws SQLException { + List rows = new ArrayList<>(); + try (Statement statement = on.createStatement(); ResultSet rs = statement.executeQuery(sql)) { + while (rs.next()) { + rows.add(rs.getString(1)); + } + } + return rows; + } + + private Object single(String sql) throws SQLException { + try (Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(sql)) { + assertTrue(rs.next()); + return rs.getObject(1); + } + } + + private SQLException failure(String sql) { + return assertThrows(SQLException.class, () -> query(sql), sql); + } + + private static void assertContains(String expected, Throwable failure) { + assertTrue(failure.getMessage().contains(expected), "expected \"" + expected + "\" in: " + failure.getMessage()); + } + + @Test + @DisplayName("functions of zero, one, two and any number of arguments") + void arities() throws SQLException { + register(function("j_answer", "Int64").withFunction(() -> 42L)); + register(function("j_plus_one", "Int64", "Int64").withFunction((Long x) -> x + 1)); + register(function("j_add", "Int64", "Int64", "Int64").withFunction((Long x, Long y) -> x + y)); + register(function("j_join", "String", "String", "String", "String") + .withRowFunction(args -> args[0] + "-" + args[1] + "-" + args[2])); + + assertEquals(Arrays.asList("42"), query("SELECT j_answer()")); + assertEquals(Arrays.asList("1", "2", "3"), query("SELECT j_plus_one(toInt64(number)) FROM numbers(3)")); + assertEquals(Arrays.asList("10"), query("SELECT j_add(4, 6)")); + assertEquals(Arrays.asList("a-b-c"), query("SELECT j_join('a', 'b', 'c')")); + assertEquals(Arrays.asList("Int64"), query("SELECT toTypeName(j_plus_one(1))")); + } + + @Test + @DisplayName("integer and float arguments arrive as their getObject types, and convert from narrower columns") + void numbers() throws SQLException { + AtomicReference> seen = new AtomicReference<>(); + register(function("j_int32", "Int32", "Int32").withFunction((Integer x) -> { + seen.set(x.getClass()); + return x * 2; + })); + assertEquals(-14, single("SELECT j_int32(toInt32(-7))")); + assertEquals(Integer.class, seen.get()); + + // An Int32 column converts to an Int64 parameter; a UInt64 one does not, and says so. + register(function("j_int64", "Int64", "Int64").withFunction((Long x) -> x)); + assertEquals(Arrays.asList("-5"), query("SELECT j_int64(toInt32(-5))")); + assertContains("does not convert to the declared Int64", failure("SELECT j_int64(toUInt64(1))")); + + // UInt64 beyond Long.MAX_VALUE, both ways, as BigInteger. + register(function("j_uint64", "UInt64", "UInt64").withFunction((BigInteger x) -> x.subtract(BigInteger.ONE))); + assertEquals(Arrays.asList("18446744073709551614"), query("SELECT j_uint64(toUInt64('18446744073709551615'))")); + + register(function("j_half", "Float64", "Float64").withFunction((Double x) -> x / 2)); + assertEquals(Arrays.asList("1.25"), query("SELECT j_half(2.5)")); + + // A result is narrowed to the declared type, and one that does not fit fails the query. + register(function("j_times_hundred", "UInt8", "Int64").withFunction((Long x) -> x * 100)); + assertEquals(Arrays.asList("200"), query("SELECT j_times_hundred(2)")); + assertContains("while converting the result of Scalar function 'j_times_hundred'", + failure("SELECT j_times_hundred(3)")); + } + + @Test + @DisplayName("Bool and String, with UTF-8 intact, and binary strings as byte[]") + void boolsAndStrings() throws SQLException { + register(function("j_not", "Bool", "Bool").withFunction((Boolean b) -> !b)); + assertEquals(Arrays.asList("true", "false"), query("SELECT j_not(toBool(number)) FROM numbers(2)")); + + register(function("j_upper", "String", "String").withFunction((String s) -> s.toUpperCase())); + assertEquals(Arrays.asList("HÉLLO 😀"), query("SELECT j_upper('héllo 😀')")); + // Text that is not valid UTF-8 cannot become a String... + assertContains("not valid UTF-8", failure("SELECT j_upper(unhex('FF'))")); + + // ...which binary strings are for. + register(function("j_byte_length", "UInt64", "String").withBinaryStrings() + .withFunction((byte[] bytes) -> (long) bytes.length)); + assertEquals(Arrays.asList("3", "6"), query("SELECT j_byte_length(arrayJoin([unhex('FF00FF'), 'héllo']))")); + register(function("j_reverse_bytes", "String", "String").withBinaryStrings().withFunction((byte[] bytes) -> { + byte[] out = new byte[bytes.length]; + for (int i = 0; i < bytes.length; i++) { + out[i] = bytes[bytes.length - 1 - i]; + } + return out; + })); + assertEquals(Arrays.asList("00FF01"), query("SELECT hex(j_reverse_bytes(unhex('01FF00')))")); + + // A FixedString keeps its padding. + register(function("j_length", "UInt64", "FixedString(4)").withFunction((String s) -> (long) s.length())); + assertEquals(Arrays.asList("4"), query("SELECT j_length(toFixedString('ab', 4))")); + } + + @Test + @DisplayName("dates as LocalDate and timestamps as Instant, back into the declared zone") + void temporal() throws SQLException { + register(function("j_next_day", "Date32", "Date32").withFunction((LocalDate d) -> d.plusDays(1))); + assertEquals(Arrays.asList("1900-01-02"), query("SELECT j_next_day(toDate32('1900-01-01'))")); + register(function("j_day_of", "Date", "Date").withFunction((LocalDate d) -> d)); + assertEquals(Arrays.asList("2024-02-29"), query("SELECT j_day_of(toDate('2024-02-29'))")); + + AtomicReference seen = new AtomicReference<>(); + register(function("j_later", "DateTime('Asia/Shanghai')", "DateTime('Asia/Shanghai')") + .withFunction((Instant t) -> { + seen.set(t); + return t.plus(Duration.ofHours(1)); + })); + assertEquals(Arrays.asList("2024-01-02 12:04:05"), + query("SELECT toString(j_later(toDateTime('2024-01-02 11:04:05', 'Asia/Shanghai')))")); + assertEquals(Instant.parse("2024-01-02T03:04:05Z"), seen.get()); + + register(function("j_millis", "DateTime64(3, 'UTC')", "DateTime64(3, 'UTC')") + .withFunction((Instant t) -> t.plusMillis(1))); + assertEquals(Arrays.asList("2024-01-02 03:04:05.679"), + query("SELECT toString(j_millis(toDateTime64('2024-01-02 03:04:05.678', 3, 'UTC')))")); + } + + @Test + @DisplayName("Decimal, UUID, IPv4, IPv6, Enum and Int128 as their Java types") + void otherScalars() throws Exception { + register(function("j_double_decimal", "Decimal(18, 4)", "Decimal(18, 4)") + .withFunction((BigDecimal d) -> d.multiply(BigDecimal.valueOf(2)))); + assertEquals(Arrays.asList("-24.6912"), query("SELECT toString(j_double_decimal(toDecimal64('-12.3456', 4)))")); + + UUID uuid = UUID.fromString("123e4567-e89b-12d3-a456-426614174000"); + register(function("j_uuid", "UUID", "UUID").withFunction((UUID u) -> { + assertEquals(uuid, u); + return new UUID(u.getLeastSignificantBits(), u.getMostSignificantBits()); + })); + assertEquals(Arrays.asList("a4564266-1417-4000-123e-4567e89b12d3"), + query("SELECT toString(j_uuid(toUUID('" + uuid + "')))")); + + register(function("j_ip", "String", "IPv4", "IPv6") + .withFunction((InetAddress v4, InetAddress v6) -> v4.getHostAddress() + " " + v6.getHostAddress())); + assertEquals(Arrays.asList(InetAddress.getByName("192.168.1.1").getHostAddress() + " " + + InetAddress.getByName("2001:db8::1").getHostAddress()), + query("SELECT j_ip(toIPv4('192.168.1.1'), toIPv6('2001:db8::1'))")); + register(function("j_next_ip", "IPv4", "IPv4").withFunction((InetAddress a) -> { + byte[] bytes = a.getAddress(); + bytes[3]++; + try { + return InetAddress.getByAddress(bytes); + } catch (IOException e) { + throw new IllegalStateException(e); + } + })); + assertEquals(Arrays.asList("10.0.0.2"), query("SELECT toString(j_next_ip(toIPv4('10.0.0.1')))")); + + register(function("j_label", "Enum8('low' = 1, 'high' = 2)", "Enum8('low' = 1, 'high' = 2)") + .withFunction((String label) -> label.equals("low") ? "high" : "low")); + assertEquals(Arrays.asList("high"), + query("SELECT toString(j_label(CAST('low', 'Enum8(\\'low\\' = 1, \\'high\\' = 2)')))")); + + register(function("j_int128", "Int128", "Int128").withFunction((BigInteger x) -> x.negate())); + assertEquals(Arrays.asList("-170141183460469231731687303715884105727"), + query("SELECT toString(j_int128(toInt128('170141183460469231731687303715884105727')))")); + } + + @Test + @DisplayName("Array, Map and Tuple as List, Map and Object[], both ways") + void nested() throws SQLException { + register(function("j_sum", "Int64", "Array(Int64)").withFunction((List values) -> { + long sum = 0; + for (Long value : values) { + sum += value; + } + return sum; + })); + assertEquals(Arrays.asList("6"), query("SELECT j_sum([1, 2, 3])")); + register(function("j_split", "Array(String)", "String").withFunction((String s) -> Arrays.asList(s.split(",")))); + assertEquals(Arrays.asList("['a','b','c']"), query("SELECT toString(j_split('a,b,c'))")); + register(function("j_squares", "Array(Nullable(Int64))", "Int64").withFunction((Long n) -> { + Long[] out = new Long[(int) (long) n]; + for (int i = 0; i < out.length; i++) { + out[i] = i % 2 == 0 ? (long) i * i : null; + } + return out; + })); + assertEquals(Arrays.asList("[0,NULL,4]"), query("SELECT toString(j_squares(3))")); + + register(function("j_keys", "String", "Map(String, Int64)").withFunction((Map map) -> map.toString())); + assertEquals(Arrays.asList("{k=1, j=2}"), query("SELECT j_keys(map('k', 1, 'j', 2))")); + register(function("j_inverse", "Map(Int64, String)", "Map(String, Int64)").withFunction((Map map) -> { + Map out = new LinkedHashMap<>(); + map.forEach((key, value) -> out.put(value, key)); + return out; + })); + assertEquals(Arrays.asList("{1:'k',2:'j'}"), query("SELECT toString(j_inverse(map('k', 1, 'j', 2)))")); + + register(function("j_swap", "Tuple(String, Int64)", "Tuple(a Int64, b String)") + .withFunction((Object[] tuple) -> new Object[] {tuple[1], tuple[0]})); + assertEquals(Arrays.asList("('x',7)"), query("SELECT toString(j_swap((7, 'x')))")); + } + + @Test + @DisplayName("a null result is NULL for a Nullable type, and an error otherwise") + void nullableResults() throws SQLException { + register(function("j_maybe", "Nullable(String)", "Int64") + .withFunction((Long x) -> x % 2 == 0 ? null : "odd " + x)); + assertEquals(Arrays.asList(null, "odd 1", null), query("SELECT j_maybe(toInt64(number)) FROM numbers(3)")); + assertEquals(Arrays.asList("Nullable(String)"), query("SELECT toTypeName(j_maybe(1))")); + + register(function("j_never_null", "String", "Int64").withFunction((Long x) -> null)); + assertContains("Cannot convert NULL value to non-Nullable type", failure("SELECT j_never_null(1)")); + } + + @Test + @DisplayName("by default a row with a NULL argument yields NULL without a call") + void nullsSkippedByDefault() throws SQLException { + AtomicInteger calls = new AtomicInteger(); + AtomicInteger nulls = new AtomicInteger(); + register(function("j_counted", "Int64", "Int64").withRowFunction(args -> { + calls.incrementAndGet(); + if (args[0] == null) { + nulls.incrementAndGet(); + } + return (Long) args[0] + 1; + })); + assertEquals(Arrays.asList(null, "2", null, "4"), + query("SELECT j_counted(if(number % 2 = 0, NULL, toInt64(number))) FROM numbers(4)")); + assertEquals(2, calls.get()); + assertEquals(0, nulls.get()); + assertEquals(Arrays.asList("Nullable(Int64)"), query("SELECT toTypeName(j_counted(toNullable(toInt64(1))))")); + } + + @Test + @DisplayName("with special NULL handling the function sees NULLs, and the type stays as declared") + void specialNullHandling() throws SQLException { + register(function("j_is_null", "Bool", "String").withSpecialNullHandling() + .withFunction((String s) -> s == null)); + assertEquals(Arrays.asList("false", "true", "false"), + query("SELECT j_is_null(if(number = 1, NULL, 'a')) FROM numbers(3)")); + assertEquals(Arrays.asList("Bool"), query("SELECT toTypeName(j_is_null(toNullable('a')))")); + assertEquals(Arrays.asList("true"), query("SELECT j_is_null(NULL)")); + } + + @Test + @DisplayName("a deterministic function without arguments is evaluated once; a volatile one per row") + void volatility() throws SQLException { + AtomicInteger counter = new AtomicInteger(); + register(function("j_next", "Int64").withFunction(() -> (long) counter.incrementAndGet())); + register(function("j_next_volatile", "Int64").withVolatile().withFunction(() -> (long) counter.incrementAndGet())); + assertEquals(Arrays.asList("1"), query("SELECT count(DISTINCT j_next()) FROM numbers(5)")); + assertEquals(Arrays.asList("5"), query("SELECT count(DISTINCT j_next_volatile()) FROM numbers(5)")); + } + + @Test + @DisplayName("an exception fails the query with its message, and the connection carries on") + void exceptions() throws SQLException { + register(function("j_fail", "Int64", "Int64").withFunction((Long x) -> { + if (x == 0) { + throw new IllegalArgumentException("zero is not allowed"); + } + return x; + })); + SQLException e = failure("SELECT j_fail(toInt64(number)) FROM numbers(2)"); + assertContains("java.lang.IllegalArgumentException: zero is not allowed", e); + assertContains("UDF_EXECUTION_FAILED", e); + // Short-circuit evaluation keeps the rows a branch does not take away from the function. + assertEquals(Arrays.asList("-1", "1"), query("SELECT if(number > 0, j_fail(toInt64(number)), -1) FROM numbers(2)")); + + register(function("j_checked", "Int64", "Int64").withRowFunction(args -> { + throw new IOException("checked, from a row function"); + })); + assertContains("java.io.IOException: checked, from a row function", failure("SELECT j_checked(1)")); + register(function("j_npe", "Int64", "Int64").withRowFunction(args -> ((String) null).length())); + assertContains("java.lang.NullPointerException", failure("SELECT j_npe(1)")); + register(function("j_overflow", "Int64", "Int64").withRowFunction(args -> { + throw new StackOverflowError("deliberate"); + })); + assertContains("java.lang.StackOverflowError: deliberate", failure("SELECT j_overflow(1)")); + register(function("j_wrong_type", "Int64", "Int64").withFunction((Long x) -> "not a number")); + assertContains("returned a java.lang.String for a Int64 result", failure("SELECT j_wrong_type(1)")); + register(function("j_wrong_parameter", "Int64", "Int64").withFunction((Integer x) -> x)); + assertContains("ClassCastException", failure("SELECT j_wrong_parameter(1)")); + + assertEquals(Arrays.asList("1"), query("SELECT 1")); + } + + @Test + @DisplayName("an unknown type, a type without an Arrow form, and a taken name fail registration") + void registrationFailures() throws SQLException { + assertContains("NotAType", assertThrows(SQLException.class, + () -> register(function("j_bad_type", "Int64", "NotAType").withRowFunction(args -> 1L)))); + assertContains("has no Arrow form", assertThrows(SQLException.class, + () -> register(function("j_bad_return", "AggregateFunction(sum, UInt64)", "Int64").withRowFunction(args -> 1L)))); + assertContains("a built-in function with that name already exists", assertThrows(SQLException.class, + () -> register(function("plus", "Int64", "Int64").withFunction((Long x) -> x)))); + // Built-in names are matched as SQL matches them, case-insensitively where SQL does. + assertContains("a built-in function with that name already exists", assertThrows(SQLException.class, + () -> register(function("LOWER", "String", "String").withFunction((String s) -> s)))); + assertContains("an aggregate function with that name already exists", assertThrows(SQLException.class, + () -> register(function("sum", "Int64", "Int64").withFunction((Long x) -> x)))); + register(function("j_once", "Int64", "Int64").withFunction((Long x) -> x)); + assertContains("is already registered", assertThrows(SQLException.class, + () -> register(function("j_once", "Int64", "Int64").withFunction((Long x) -> x)))); + // A parameter type no Java value is read as is refused before chDB sees it. + assertThrows(SQLFeatureNotSupportedException.class, + () -> register(function("j_time", "String", "Time").withRowFunction(args -> "x"))); + assertEquals(1, ScalarFunctionCallback.liveCount(), "a refused registration leaves nothing registered"); + } + + @Test + @DisplayName("drop, drop again, and register the name anew") + void dropAndReRegister() throws SQLException { + RegisteredFunction first = register(function("j_versioned", "Int64", "Int64").withFunction((Long x) -> x + 1)); + assertEquals(Arrays.asList("2"), query("SELECT j_versioned(1)")); + ChdbFunctions.dropScalarFunction("j_versioned"); + assertEquals(0, ScalarFunctionCallback.liveCount(), "dropping destroys the function at once when no query uses it"); + assertContains("UNKNOWN_FUNCTION", failure("SELECT j_versioned(1)")); + assertContains("is not registered", assertThrows(SQLException.class, () -> ChdbFunctions.dropScalarFunction("j_versioned"))); + + RegisteredFunction second = register(function("j_versioned", "Int64", "Int64").withFunction((Long x) -> x + 2)); + assertEquals(Arrays.asList("3"), query("SELECT j_versioned(1)")); + // The first registration's handle no longer owns the name, so closing it drops nothing. + first.close(); + assertEquals(Arrays.asList("3"), query("SELECT j_versioned(1)")); + second.close(); + second.close(); + assertContains("UNKNOWN_FUNCTION", failure("SELECT j_versioned(1)")); + } + + @Test + @DisplayName("the brief's multi-threaded query gives the right sum") + void largeParallelQuery() throws SQLException { + register(function("j_plus_one", "Int64", "Int64").withFunction((Long x) -> x + 1)); + assertEquals(Arrays.asList("2000001000000"), + query("SELECT sum(j_plus_one(toInt64(number))) FROM numbers(2000000) SETTINGS max_threads = 8")); + assertEquals(Arrays.asList("500000500000"), query( + "SELECT sum(j_plus_one(toInt64(number))) FROM numbers_mt(1000000) SETTINGS max_threads = 8, max_block_size = 8192")); + } + + @Test + @DisplayName("queries from several Java threads run the function on several engine threads at once") + void concurrentQueries() throws Exception { + int threads = 4; + // Each query calls the function on exactly one row with number = 0, which waits for the + // other queries' calls: the barrier only trips if all four run at the same time. + CyclicBarrier together = new CyclicBarrier(threads); + register(function("j_meet", "Int64", "Int64").withFunction((Long x) -> { + if (x == 0) { + try { + together.await(30, TimeUnit.SECONDS); + } catch (Exception e) { + throw new IllegalStateException("the calls did not run concurrently", e); + } + } + return x * 2; + })); + ExecutorService pool = Executors.newFixedThreadPool(threads); + try { + List>> results = new ArrayList<>(); + for (int t = 0; t < threads; t++) { + results.add(pool.submit(() -> { + try (Connection own = openMemory()) { + return query(own, "SELECT sum(j_meet(toInt64(number))) FROM numbers(100000)"); + } + })); + } + for (Future> result : results) { + assertEquals(Arrays.asList("9999900000"), result.get(60, TimeUnit.SECONDS)); + } + } finally { + pool.shutdownNow(); + } + } + + @Test + @DisplayName("a function is the process's: every connection sees it, and it outlives the one that registered it") + void processWide() throws SQLException { + RegisteredFunction function; + try (Connection registering = openMemory()) { + function = ChdbFunctions.scalarFunction().withName("j_shared").withParameter("Int64").withReturnType("Int64") + .withFunction((Long x) -> x * 10).register(registering); + } + registered.add(function); + try (Connection later = openMemory()) { + assertEquals(Arrays.asList("70"), query(later, "SELECT j_shared(7)")); + } + // Through a connection that only wraps a chDB one, as a pool's proxy does. + Connection wrapper = (Connection) Proxy.newProxyInstance(getClass().getClassLoader(), + new Class[] {Connection.class}, (proxy, method, args) -> method.invoke(connection, args)); + registered.add(ChdbFunctions.scalarFunction().withName("j_through_wrapper").withReturnType("Int64") + .withFunction(() -> 1L).register(wrapper)); + assertEquals(Arrays.asList("1"), query("SELECT j_through_wrapper()")); + + // Dropping needs no connection at all, even when none is open and the engine has gone. + connection.close(); + function.close(); + connection = openMemory(); + assertContains("UNKNOWN_FUNCTION", failure("SELECT j_shared(7)")); + // What was not dropped survived the engine going and coming back. + assertEquals(Arrays.asList("1"), query("SELECT j_through_wrapper()")); + } + + @Test + @DisplayName("SQL from inside a function is refused, not left to deadlock") + void noChdbInsideAFunction() throws SQLException { + Connection other = openMemory(); + try { + register(function("j_same_connection", "Int64", "Int64").withRowFunction(args -> query(connection, "SELECT 1").size())); + register(function("j_other_connection", "Int64", "Int64").withRowFunction(args -> query(other, "SELECT 1").size())); + register(function("j_new_connection", "Int64", "Int64").withRowFunction(args -> { + openMemory().close(); + return 1L; + })); + register(function("j_drop_inside", "Int64", "Int64").withRowFunction(args -> { + ChdbFunctions.dropScalarFunction("j_same_connection"); + return 1L; + })); + for (String name : new String[] {"j_same_connection", "j_other_connection", "j_new_connection", "j_drop_inside"}) { + assertContains("from inside a scalar function", failure("SELECT " + name + "(1)")); + } + assertEquals(Arrays.asList("1"), query(other, "SELECT 1")); + } finally { + other.close(); + } + } + + @Test + @DisplayName("a function is released once dropped, and not before") + void releasedAfterDrop() throws SQLException { + assertEquals(0, ScalarFunctionCallback.liveCount()); + RegisteredFunction function = register(function("j_counted_release", "String", "String") + .withFunction((String s) -> new String(s.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8))); + assertEquals(1, ScalarFunctionCallback.liveCount()); + assertEquals(Arrays.asList("x"), query("SELECT j_counted_release('x')")); + assertEquals(1, ScalarFunctionCallback.liveCount(), "a query does not release it"); + function.close(); + assertEquals(0, ScalarFunctionCallback.liveCount()); + } +} diff --git a/chdb-jdbc/src/main/java/org/chdb/internal/ArrowColumn.java b/chdb-jdbc/src/main/java/org/chdb/internal/ArrowColumn.java new file mode 100644 index 0000000..3c4f75b --- /dev/null +++ b/chdb-jdbc/src/main/java/org/chdb/internal/ArrowColumn.java @@ -0,0 +1,74 @@ +package org.chdb.internal; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +/** + * One Arrow array with its buffers on the Java heap: what {@link ChdbNative#copyArrowArray} + * makes of a scalar function's arguments, and what {@link ChdbNative#exportArrowArray} turns into + * the function's result. + * + *

    Not public API. The buffers are the array's Arrow C Data buffers in the order the format lays + * them out -- the validity bitmap first, then offsets and values -- copied rather than viewed, so + * nothing here points into engine memory that chDB frees when the callback returns. A null entry + * is a buffer the array leaves out: a validity bitmap when nothing is null, or one of zero bytes. + * Multi-byte values are in the platform's byte order, which is little-endian on every platform the + * driver supports. + * + *

    The shim constructs these and reads their fields by name, so the constructor's signature and + * the field names are part of the JNI contract versioned by {@link ChdbNative#JNI_ABI_VERSION}. + */ +public final class ArrowColumn { + + final String format; + /** {@code ARROW:extension:name} from the field's metadata, such as {@code arrow.uuid}; null if none. */ + final String extension; + final boolean nullable; + final int length; + final int offset; + /** -1 when the producer did not count them. */ + final int nullCount; + final byte[][] buffers; + final ArrowColumn[] children; + + ArrowColumn( + String format, + String extension, + boolean nullable, + int length, + int offset, + int nullCount, + byte[][] buffers, + ArrowColumn[] children) { + this.format = format; + this.extension = extension; + this.nullable = nullable; + this.length = length; + this.offset = offset; + this.nullCount = nullCount; + this.buffers = buffers; + this.children = children; + } + + /** Rows in the array. For a scalar function's argument struct, rows in the batch. */ + public int length() { + return length; + } + + boolean isNull(int row) { + if (nullCount == 0 || buffers.length == 0 || buffers[0] == null) { + return false; + } + return !bit(buffers[0], offset + row); + } + + /** Buffer {@code index} for reading values, or null when the array leaves it out. */ + ByteBuffer buffer(int index) { + byte[] bytes = buffers[index]; + return bytes == null ? null : ByteBuffer.wrap(bytes).order(ByteOrder.nativeOrder()); + } + + static boolean bit(byte[] bitmap, int index) { + return (bitmap[index >>> 3] & (1 << (index & 7))) != 0; + } +} diff --git a/chdb-jdbc/src/main/java/org/chdb/internal/ArrowDecoder.java b/chdb-jdbc/src/main/java/org/chdb/internal/ArrowDecoder.java new file mode 100644 index 0000000..a70b60a --- /dev/null +++ b/chdb-jdbc/src/main/java/org/chdb/internal/ArrowDecoder.java @@ -0,0 +1,362 @@ +package org.chdb.internal; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * Reads a scalar function's arguments, as chDB passes them in Arrow, as the Java values a function + * called one row at a time receives. + * + *

    Not public API. The Arrow format decides how a value is read, and the declared ClickHouse type + * settles what it means where the format alone cannot: chDB sends {@code Int128} and {@code Enum8} + * as text like a {@code String}, {@code IPv4} as a {@code UInt32}, and {@code UUID}, {@code IPv6} + * and {@code FixedString(16)} as sixteen bytes of fixed-size binary. The values match what {@code + * ResultSet.getObject} returns for the same type, except that a date is a {@link LocalDate}, a + * timestamp an {@link Instant}, an {@code Array} a {@link List} and a {@code Tuple} an {@code + * Object[]}: the exact types rather than the {@code java.sql} ones JDBC prescribes. + * + *

    Every value is a copy, so a function may keep what it is given. + */ +public final class ArrowDecoder { + + /** One argument column, read one row at a time. */ + public interface Reader { + Object read(int row); + } + + private ArrowDecoder() { + } + + /** + * Fails for a declared argument type with no Java value here: {@code Time} and {@code Time64} + * arrive as Arrow times and {@code Variant} as a union, which a function called per row cannot + * be given faithfully. Checked when the function is registered rather than on every query. + * + * @throws IllegalArgumentException naming the type and what to do instead + */ + public static void checkReadable(ClickHouseType type) { + switch (type.kind()) { + case TIME: + case TIME64: + case VARIANT: + throw new IllegalArgumentException( + "a function called one row at a time cannot take a " + type.name() + " argument;" + + " declare it as String and pass toString(...), or use chdb-arrow's" + + " ArrowFunctions, which receives the Arrow arrays themselves"); + case ARRAY: + case MAP: + case TUPLE: + case NULLABLE: + case LOW_CARDINALITY: + for (ClickHouseType element : type.arguments()) { + checkReadable(element); + } + return; + default: + // Everything else arrives as a value this reads, JSON's typed paths included: + // JSON arrives as its text. + } + } + + /** + * Readers for the arguments of one batch: the children of {@code arguments}, chDB's struct + * array, in declaration order. + * + * @param types the declared argument types, as many as the struct has children + * @param binaryStrings whether the function was registered with binary strings, which makes a + * {@code String} or {@code FixedString} argument a {@code byte[]} + */ + public static Reader[] readers(ArrowColumn arguments, List types, boolean binaryStrings) { + if (!"+s".equals(arguments.format) || arguments.children.length != types.size()) { + throw new ScalarFunctionException("chDB passed a batch of Arrow format '" + arguments.format + "' with " + + arguments.children.length + " columns for " + types.size() + " declared arguments"); + } + Reader[] readers = new Reader[types.size()]; + for (int i = 0; i < readers.length; i++) { + readers[i] = field(arguments, i, types.get(i), binaryStrings); + } + return readers; + } + + /** A struct's field: the struct's own offset applies to its children too. */ + private static Reader field(ArrowColumn struct, int index, ClickHouseType declared, boolean binaryStrings) { + Reader child = reader(struct.children[index], declared, binaryStrings); + int offset = struct.offset; + return offset == 0 ? child : row -> child.read(offset + row); + } + + static Reader reader(ArrowColumn column, ClickHouseType declared, boolean binaryStrings) { + Reader values = values(column, declared == null ? null : declared.unwrapped(), binaryStrings); + if (column.nullCount == 0 || column.buffers.length == 0 || column.buffers[0] == null) { + return values; + } + return row -> column.isNull(row) ? null : values.read(row); + } + + private static Reader values(ArrowColumn column, ClickHouseType declared, boolean binaryStrings) { + String format = column.format; + ClickHouseType.Kind kind = declared == null ? ClickHouseType.Kind.UNKNOWN : declared.kind(); + int offset = column.offset; + switch (format) { + case "n": + return row -> null; + case "b": { + byte[] bits = column.buffers[1]; + return row -> ArrowColumn.bit(bits, offset + row); + } + case "c": { + ByteBuffer data = column.buffer(1); + return row -> data.get(offset + row); + } + case "C": { + ByteBuffer data = column.buffer(1); + return row -> (short) (data.get(offset + row) & 0xFF); + } + case "s": { + ByteBuffer data = column.buffer(1); + return row -> data.getShort((offset + row) * 2); + } + case "S": { + ByteBuffer data = column.buffer(1); + return row -> data.getShort((offset + row) * 2) & 0xFFFF; + } + case "i": { + ByteBuffer data = column.buffer(1); + return row -> data.getInt((offset + row) * 4); + } + case "I": { + ByteBuffer data = column.buffer(1); + if (kind == ClickHouseType.Kind.IPV4) { + return row -> ipv4(data.getInt((offset + row) * 4)); + } + return row -> data.getInt((offset + row) * 4) & 0xFFFFFFFFL; + } + case "l": { + ByteBuffer data = column.buffer(1); + return row -> data.getLong((offset + row) * 8); + } + case "L": { + ByteBuffer data = column.buffer(1); + return row -> unsigned(data.getLong((offset + row) * 8)); + } + case "f": { + ByteBuffer data = column.buffer(1); + return row -> data.getFloat((offset + row) * 4); + } + case "g": { + ByteBuffer data = column.buffer(1); + return row -> data.getDouble((offset + row) * 8); + } + case "u": + case "U": + case "z": + case "Z": + return variable(column, kind, binaryStrings); + case "tdD": { + ByteBuffer data = column.buffer(1); + return row -> LocalDate.ofEpochDay(data.getInt((offset + row) * 4)); + } + case "+l": + case "+L": + return list(column, declared, binaryStrings); + case "+s": + return tuple(column, declared, binaryStrings); + case "+m": + return map(column, declared, binaryStrings); + default: + break; + } + if (format.startsWith("ts") && format.length() >= 4 && format.charAt(3) == ':') { + return timestamp(column, format.charAt(2)); + } + if (format.startsWith("d:")) { + return decimal(column); + } + if (format.startsWith("w:")) { + return fixedBinary(column, kind, binaryStrings); + } + throw new ScalarFunctionException("cannot read an argument of Arrow format '" + format + "'" + + (declared == null ? "" : " (" + declared.name() + ")") + + " as a Java value; use chdb-arrow's ArrowFunctions, which receives the Arrow arrays"); + } + + /** utf8 and binary, as text, bytes or a number by what the argument was declared as. */ + private static Reader variable(ArrowColumn column, ClickHouseType.Kind kind, boolean binaryStrings) { + boolean large = column.format.equals("U") || column.format.equals("Z"); + boolean binary = column.format.equals("z") || column.format.equals("Z"); + ByteBuffer offsets = column.buffer(1); + byte[] data = column.buffers[2] == null ? new byte[0] : column.buffers[2]; + int offset = column.offset; + Reader bytes = row -> { + int start = large ? (int) offsets.getLong((offset + row) * 8) : offsets.getInt((offset + row) * 4); + int end = large ? (int) offsets.getLong((offset + row + 1) * 8) : offsets.getInt((offset + row + 1) * 4); + return Arrays.copyOfRange(data, start, end); + }; + switch (kind) { + // 128- and 256-bit integers arrive as their decimal text. + case INT128: + case INT256: + case UINT128: + case UINT256: + return row -> new BigInteger(new String((byte[]) bytes.read(row), StandardCharsets.US_ASCII)); + // An enum label is defined in SQL, and JSON text is UTF-8 even when strings arrive as binary. + case ENUM8: + case ENUM16: + case JSON: + case DYNAMIC: + return row -> new String((byte[]) bytes.read(row), StandardCharsets.UTF_8); + default: + if (binary || binaryStrings) { + return bytes; + } + return row -> new String((byte[]) bytes.read(row), StandardCharsets.UTF_8); + } + } + + /** UUID, IPv6 and FixedString(N) all arrive as N bytes of fixed-size binary. */ + private static Reader fixedBinary(ArrowColumn column, ClickHouseType.Kind kind, boolean binaryStrings) { + int width = Integer.parseInt(column.format.substring(2)); + byte[] data = column.buffers[1]; + int offset = column.offset; + Reader bytes = row -> Arrays.copyOfRange(data, (offset + row) * width, (offset + row + 1) * width); + if (width == 16 && (kind == ClickHouseType.Kind.UUID || "arrow.uuid".equals(column.extension))) { + // RFC 4122 byte order, which is big-endian whatever the platform's order is. + ByteBuffer big = ByteBuffer.wrap(data).order(ByteOrder.BIG_ENDIAN); + return row -> new UUID(big.getLong((offset + row) * 16), big.getLong((offset + row) * 16 + 8)); + } + if (width == 16 && kind == ClickHouseType.Kind.IPV6) { + return row -> address((byte[]) bytes.read(row)); + } + if (kind == ClickHouseType.Kind.FIXED_STRING && !binaryStrings) { + return row -> new String((byte[]) bytes.read(row), StandardCharsets.UTF_8); + } + return bytes; + } + + private static Reader timestamp(ArrowColumn column, char unit) { + ByteBuffer data = column.buffer(1); + int offset = column.offset; + switch (unit) { + case 's': + return row -> Instant.ofEpochSecond(data.getLong((offset + row) * 8)); + case 'm': + return row -> Instant.ofEpochMilli(data.getLong((offset + row) * 8)); + case 'u': + return row -> { + long micros = data.getLong((offset + row) * 8); + return Instant.ofEpochSecond(Math.floorDiv(micros, 1_000_000L), Math.floorMod(micros, 1_000_000L) * 1_000L); + }; + default: + return row -> { + long nanos = data.getLong((offset + row) * 8); + return Instant.ofEpochSecond(Math.floorDiv(nanos, 1_000_000_000L), Math.floorMod(nanos, 1_000_000_000L)); + }; + } + } + + /** "d:precision,scale[,bits]": a little-endian two's-complement integer of 128 or 256 bits. */ + private static Reader decimal(ArrowColumn column) { + String[] parts = column.format.substring(2).split(","); + int scale = Integer.parseInt(parts[1]); + int width = parts.length > 2 ? Integer.parseInt(parts[2]) / 8 : 16; + byte[] data = column.buffers[1]; + int offset = column.offset; + return row -> { + byte[] bigEndian = new byte[width]; + int start = (offset + row) * width; + for (int i = 0; i < width; i++) { + bigEndian[i] = data[start + width - 1 - i]; + } + return new BigDecimal(new BigInteger(bigEndian), scale); + }; + } + + private static Reader list(ArrowColumn column, ClickHouseType declared, boolean binaryStrings) { + boolean large = column.format.equals("+L"); + ByteBuffer offsets = column.buffer(1); + Reader elements = reader(column.children[0], element(declared, ClickHouseType.Kind.ARRAY, 0), binaryStrings); + int offset = column.offset; + return row -> { + int start = large ? (int) offsets.getLong((offset + row) * 8) : offsets.getInt((offset + row) * 4); + int end = large ? (int) offsets.getLong((offset + row + 1) * 8) : offsets.getInt((offset + row + 1) * 4); + List out = new ArrayList<>(end - start); + for (int i = start; i < end; i++) { + out.add(elements.read(i)); + } + return out; + }; + } + + private static Reader tuple(ArrowColumn column, ClickHouseType declared, boolean binaryStrings) { + boolean typed = declared != null && declared.kind() == ClickHouseType.Kind.TUPLE + && declared.arguments().size() == column.children.length; + Reader[] fields = new Reader[column.children.length]; + for (int i = 0; i < fields.length; i++) { + fields[i] = field(column, i, typed ? declared.arguments().get(i) : null, binaryStrings); + } + return row -> { + Object[] out = new Object[fields.length]; + for (int i = 0; i < fields.length; i++) { + out[i] = fields[i].read(row); + } + return out; + }; + } + + private static Reader map(ArrowColumn column, ClickHouseType declared, boolean binaryStrings) { + ByteBuffer offsets = column.buffer(1); + ArrowColumn entries = column.children[0]; + Reader keys = field(entries, 0, element(declared, ClickHouseType.Kind.MAP, 0), binaryStrings); + Reader values = field(entries, 1, element(declared, ClickHouseType.Kind.MAP, 1), binaryStrings); + int offset = column.offset; + return row -> { + int start = offsets.getInt((offset + row) * 4); + int end = offsets.getInt((offset + row + 1) * 4); + Map out = new LinkedHashMap<>(); + for (int i = start; i < end; i++) { + out.put(keys.read(i), values.read(i)); + } + return out; + }; + } + + /** The declared type of a nested element, when the declaration has that shape. */ + private static ClickHouseType element(ClickHouseType declared, ClickHouseType.Kind kind, int index) { + if (declared == null || declared.kind() != kind || declared.arguments().size() <= index) { + return null; + } + return declared.arguments().get(index); + } + + private static BigInteger unsigned(long value) { + BigInteger magnitude = BigInteger.valueOf(value & Long.MAX_VALUE); + return value < 0 ? magnitude.setBit(Long.SIZE - 1) : magnitude; + } + + /** IPv4 arrives as the address's 32-bit number, a.b.c.d being a << 24 | b << 16 | c << 8 | d. */ + private static InetAddress ipv4(int value) { + return address(new byte[] {(byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value}); + } + + private static InetAddress address(byte[] bytes) { + try { + return InetAddress.getByAddress(bytes); + } catch (UnknownHostException e) { + // Only thrown for a length other than 4 or 16, which the callers rule out. + throw new IllegalStateException(e); + } + } +} diff --git a/chdb-jdbc/src/main/java/org/chdb/internal/ArrowEncoder.java b/chdb-jdbc/src/main/java/org/chdb/internal/ArrowEncoder.java new file mode 100644 index 0000000..2c4b096 --- /dev/null +++ b/chdb-jdbc/src/main/java/org/chdb/internal/ArrowEncoder.java @@ -0,0 +1,532 @@ +package org.chdb.internal; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.net.InetAddress; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Function; + +/** + * Turns the values a scalar function returned, one per row, into the Arrow array chDB reads its + * result from. + * + *

    Not public API. The declared return type decides the Arrow type, and so which Java values are + * accepted. chDB converts the array to the declared type the way CAST does, refusing a value that + * does not fit, so each type is sent in the Arrow form that converts to it exactly: int64 for every + * integer type, falling back to the number's decimal text when a {@code BigInteger} needs more + * than 64 bits; float64 for every float; date32 for a date; a timestamp in the declared precision + * for a {@code DateTime}; and text for the types Java holds as an object with a canonical text + * form -- {@code Decimal}, {@code UUID}, {@code IPv4}, {@code IPv6}, {@code Enum} -- and for every + * type without a mapping of its own, which then takes a {@code String} for chDB to parse. + * + *

    A null is a NULL, which chDB accepts only where the declared type is {@code Nullable}. + */ +public abstract class ArrowEncoder { + + private static final ArrowColumn[] NO_CHILDREN = new ArrowColumn[0]; + + /** The declared type, as declared, for messages. */ + final String typeName; + + private ArrowEncoder(ClickHouseType type) { + this.typeName = type.name(); + } + + /** The encoder for a declared return type, or for an element of one. */ + public static ArrowEncoder forType(ClickHouseType declared) { + ClickHouseType type = declared.unwrapped(); + List arguments = type.arguments(); + switch (type.kind()) { + case BOOL: + return new Bools(type); + case INT8: + case INT16: + case INT32: + case INT64: + case INT128: + case INT256: + case UINT8: + case UINT16: + case UINT32: + case UINT64: + case UINT128: + case UINT256: + case INTERVAL: + return new Integers(type); + case FLOAT32: + case FLOAT64: + case BFLOAT16: + return new Floats(type); + case STRING: + case FIXED_STRING: + return new Strings(type); + case DATE: + case DATE32: + return new Dates(type); + case DATETIME: + return new Timestamps(type, 0); + case DATETIME64: + return new Timestamps(type, type.scale()); + case DECIMAL: + return new Text(type, ArrowEncoder::decimalText, "a BigDecimal, another Number or a String"); + case UUID: + return new Text(type, value -> value instanceof UUID ? value.toString() : charSequence(value), + "a UUID or a String"); + case IPV4: + case IPV6: + return new Text(type, value -> value instanceof InetAddress + ? ((InetAddress) value).getHostAddress() : charSequence(value), + "an InetAddress or a String"); + case ARRAY: + if (arguments.size() == 1) { + return new Lists(type, forType(arguments.get(0))); + } + break; + case MAP: + if (arguments.size() == 2) { + return new Maps(type, forType(arguments.get(0)), forType(arguments.get(1))); + } + break; + case TUPLE: { + List elements = new ArrayList<>(arguments.size()); + for (ClickHouseType element : arguments) { + elements.add(forType(element)); + } + return new Tuples(type, elements); + } + default: + break; + } + return new Text(type, ArrowEncoder::charSequence, "a String, which chDB parses as " + type.name()); + } + + /** One batch of results, values[i] being row i's. */ + public abstract ArrowColumn encode(Object[] values); + + ScalarFunctionException mismatch(Object value, String expected) { + return new ScalarFunctionException("the function returned a " + value.getClass().getName() + " for a " + + typeName + " result; return " + expected); + } + + // ------------------------------------------------------------------ encoders + + private static final class Bools extends ArrowEncoder { + Bools(ClickHouseType type) { + super(type); + } + + @Override + public ArrowColumn encode(Object[] values) { + byte[] bits = new byte[bitmapBytes(values.length)]; + for (int i = 0; i < values.length; i++) { + Object value = values[i]; + if (value == null) { + continue; + } + if (!(value instanceof Boolean)) { + throw mismatch(value, "a Boolean"); + } + if ((Boolean) value) { + setBit(bits, i); + } + } + return column("b", values, NO_CHILDREN, bits); + } + } + + private static final class Integers extends ArrowEncoder { + Integers(ClickHouseType type) { + super(type); + } + + @Override + public ArrowColumn encode(Object[] values) { + boolean fitsLong = true; + for (Object value : values) { + if (value == null || value instanceof Long || value instanceof Integer || value instanceof Short + || value instanceof Byte) { + continue; + } + if (!(value instanceof BigInteger)) { + throw mismatch(value, "an Integer, Long, Short, Byte or BigInteger"); + } + fitsLong &= ((BigInteger) value).bitLength() < Long.SIZE; + } + if (!fitsLong) { + // An Int128, a UInt64 above Long.MAX_VALUE: as decimal text, which chDB parses + // with the range check it applies to any other value. + return text("u", values, value -> value.toString().getBytes(StandardCharsets.US_ASCII)); + } + ByteBuffer data = allocate(values.length, Long.BYTES); + for (int i = 0; i < values.length; i++) { + if (values[i] != null) { + data.putLong(i * Long.BYTES, ((Number) values[i]).longValue()); + } + } + return column("l", values, NO_CHILDREN, data.array()); + } + } + + private static final class Floats extends ArrowEncoder { + Floats(ClickHouseType type) { + super(type); + } + + @Override + public ArrowColumn encode(Object[] values) { + ByteBuffer data = allocate(values.length, Double.BYTES); + for (int i = 0; i < values.length; i++) { + Object value = values[i]; + if (value == null) { + continue; + } + if (!(value instanceof Number)) { + throw mismatch(value, "a Number"); + } + data.putDouble(i * Double.BYTES, ((Number) value).doubleValue()); + } + return column("g", values, NO_CHILDREN, data.array()); + } + } + + private static final class Strings extends ArrowEncoder { + Strings(ClickHouseType type) { + super(type); + } + + @Override + public ArrowColumn encode(Object[] values) { + boolean binary = false; + for (Object value : values) { + if (value instanceof byte[]) { + binary = true; + } else if (value != null && !(value instanceof CharSequence)) { + throw mismatch(value, "a String or a byte[]"); + } + } + return text(binary ? "z" : "u", values, + value -> value instanceof byte[] ? (byte[]) value : value.toString().getBytes(StandardCharsets.UTF_8)); + } + } + + private static final class Dates extends ArrowEncoder { + Dates(ClickHouseType type) { + super(type); + } + + @Override + public ArrowColumn encode(Object[] values) { + ByteBuffer data = allocate(values.length, Integer.BYTES); + for (int i = 0; i < values.length; i++) { + Object value = values[i]; + if (value == null) { + continue; + } + if (!(value instanceof LocalDate)) { + throw mismatch(value, "a LocalDate"); + } + long day = ((LocalDate) value).toEpochDay(); + if (day != (int) day) { + throw new ScalarFunctionException("the function returned " + value + ", which no date type holds"); + } + data.putInt(i * Integer.BYTES, (int) day); + } + return column("tdD", values, NO_CHILDREN, data.array()); + } + } + + private static final class Timestamps extends ArrowEncoder { + private final char unit; + + Timestamps(ClickHouseType type, int scale) { + super(type); + // The declared precision, so that chDB has nothing to round: what does not fit in it + // is cut here, toward the past, as a cast to a coarser DateTime64 would. + this.unit = scale == 0 ? 's' : scale <= 3 ? 'm' : scale <= 6 ? 'u' : 'n'; + } + + @Override + public ArrowColumn encode(Object[] values) { + ByteBuffer data = allocate(values.length, Long.BYTES); + for (int i = 0; i < values.length; i++) { + Object value = values[i]; + if (value == null) { + continue; + } + Instant instant; + if (value instanceof Instant) { + instant = (Instant) value; + } else if (value instanceof OffsetDateTime) { + instant = ((OffsetDateTime) value).toInstant(); + } else if (value instanceof ZonedDateTime) { + instant = ((ZonedDateTime) value).toInstant(); + } else { + // Not LocalDateTime: it names no instant, so any zone chosen here would be a guess. + throw mismatch(value, "an Instant, OffsetDateTime or ZonedDateTime"); + } + try { + data.putLong(i * Long.BYTES, since(instant)); + } catch (ArithmeticException e) { + throw new ScalarFunctionException("the function returned " + instant + + ", which is out of range for " + typeName); + } + } + // UTC because an instant has no zone; chDB shows it in the declared type's. + return column("ts" + unit + ":UTC", values, NO_CHILDREN, data.array()); + } + + private long since(Instant instant) { + long seconds = instant.getEpochSecond(); + int nanos = instant.getNano(); + switch (unit) { + case 's': + return seconds; + case 'm': + return Math.addExact(Math.multiplyExact(seconds, 1_000L), nanos / 1_000_000); + case 'u': + return Math.addExact(Math.multiplyExact(seconds, 1_000_000L), nanos / 1_000); + default: + return Math.addExact(Math.multiplyExact(seconds, 1_000_000_000L), nanos); + } + } + } + + /** Values sent as their text, which chDB parses as the declared type. */ + private static final class Text extends ArrowEncoder { + private final Function textOf; + private final String expected; + + /** textOf returns null for a value of a class the type does not take. */ + Text(ClickHouseType type, Function textOf, String expected) { + super(type); + this.textOf = textOf; + this.expected = expected; + } + + @Override + public ArrowColumn encode(Object[] values) { + String[] texts = new String[values.length]; + for (int i = 0; i < values.length; i++) { + if (values[i] != null) { + texts[i] = textOf.apply(values[i]); + if (texts[i] == null) { + throw mismatch(values[i], expected); + } + } + } + return text("u", texts, text -> ((String) text).getBytes(StandardCharsets.UTF_8)); + } + } + + private static final class Lists extends ArrowEncoder { + private final ArrowEncoder elements; + + Lists(ClickHouseType type, ArrowEncoder elements) { + super(type); + this.elements = elements; + } + + @Override + public ArrowColumn encode(Object[] values) { + ByteBuffer offsets = allocate(values.length + 1, Integer.BYTES); + List flat = new ArrayList<>(); + for (int i = 0; i < values.length; i++) { + offsets.putInt(i * Integer.BYTES, flat.size()); + Object value = values[i]; + if (value == null) { + continue; + } + if (value instanceof Collection) { + flat.addAll((Collection) value); + } else if (value.getClass().isArray()) { + // Primitive arrays too: java.lang.reflect.Array boxes their elements. + int length = java.lang.reflect.Array.getLength(value); + for (int j = 0; j < length; j++) { + flat.add(java.lang.reflect.Array.get(value, j)); + } + } else { + throw mismatch(value, "a List or an array"); + } + } + offsets.putInt(values.length * Integer.BYTES, flat.size()); + return column("+l", values, new ArrowColumn[] {elements.encode(flat.toArray())}, offsets.array()); + } + } + + private static final class Maps extends ArrowEncoder { + private final ArrowEncoder keys; + private final ArrowEncoder items; + + Maps(ClickHouseType type, ArrowEncoder keys, ArrowEncoder items) { + super(type); + this.keys = keys; + this.items = items; + } + + @Override + public ArrowColumn encode(Object[] values) { + ByteBuffer offsets = allocate(values.length + 1, Integer.BYTES); + List keyValues = new ArrayList<>(); + List itemValues = new ArrayList<>(); + for (int i = 0; i < values.length; i++) { + offsets.putInt(i * Integer.BYTES, keyValues.size()); + Object value = values[i]; + if (value == null) { + continue; + } + if (!(value instanceof Map)) { + throw mismatch(value, "a Map"); + } + for (Map.Entry entry : ((Map) value).entrySet()) { + if (entry.getKey() == null) { + throw new ScalarFunctionException( + "the function returned a Map with a null key, which a " + typeName + " cannot hold"); + } + keyValues.add(entry.getKey()); + itemValues.add(entry.getValue()); + } + } + offsets.putInt(values.length * Integer.BYTES, keyValues.size()); + // Arrow requires a map's keys, and its entries, to be declared non-nullable. + ArrowColumn entries = new ArrowColumn("+s", null, false, keyValues.size(), 0, 0, new byte[][] {null}, + new ArrowColumn[] {keys.encode(keyValues.toArray()), items.encode(itemValues.toArray())}); + return column("+m", values, new ArrowColumn[] {entries}, offsets.array()); + } + } + + private static final class Tuples extends ArrowEncoder { + private final List elements; + + Tuples(ClickHouseType type, List elements) { + super(type); + this.elements = elements; + } + + @Override + public ArrowColumn encode(Object[] values) { + int width = elements.size(); + Object[][] columns = new Object[width][values.length]; + for (int i = 0; i < values.length; i++) { + Object value = values[i]; + if (value == null) { + continue; + } + Object[] items; + if (value instanceof Object[]) { + items = (Object[]) value; + } else if (value instanceof List) { + items = ((List) value).toArray(); + } else { + throw mismatch(value, "an Object[] or a List"); + } + if (items.length != width) { + throw new ScalarFunctionException("the function returned " + items.length + " elements for a " + + typeName + " result, which has " + width); + } + for (int j = 0; j < width; j++) { + columns[j][i] = items[j]; + } + } + ArrowColumn[] children = new ArrowColumn[width]; + for (int j = 0; j < width; j++) { + children[j] = elements.get(j).encode(columns[j]); + } + return column("+s", values, children); + } + } + + // ------------------------------------------------------------------ buffers + + /** + * A column of values: its validity bitmap, left out when nothing is null, then {@code buffers}. + */ + private static ArrowColumn column(String format, Object[] values, ArrowColumn[] children, byte[]... buffers) { + int nulls = 0; + for (Object value : values) { + if (value == null) { + nulls++; + } + } + byte[][] all = new byte[buffers.length + 1][]; + if (nulls > 0) { + all[0] = new byte[bitmapBytes(values.length)]; + for (int i = 0; i < values.length; i++) { + if (values[i] != null) { + setBit(all[0], i); + } + } + } + System.arraycopy(buffers, 0, all, 1, buffers.length); + return new ArrowColumn(format, null, nulls > 0, values.length, 0, nulls, all, children); + } + + /** utf8 or binary: int32 offsets, then every value's bytes end to end. */ + private static ArrowColumn text(String format, Object[] values, Function bytesOf) { + byte[][] each = new byte[values.length][]; + long total = 0; + for (int i = 0; i < values.length; i++) { + if (values[i] != null) { + each[i] = bytesOf.apply(values[i]); + total += each[i].length; + } + } + if (total > Integer.MAX_VALUE) { + throw new ScalarFunctionException( + "the function returned " + total + " bytes of text for one batch, more than an Arrow string column holds"); + } + ByteBuffer offsets = allocate(values.length + 1, Integer.BYTES); + byte[] data = new byte[(int) total]; + int at = 0; + for (int i = 0; i < values.length; i++) { + offsets.putInt(i * Integer.BYTES, at); + if (each[i] != null) { + System.arraycopy(each[i], 0, data, at, each[i].length); + at += each[i].length; + } + } + offsets.putInt(values.length * Integer.BYTES, at); + return column(format, values, NO_CHILDREN, offsets.array(), data); + } + + private static ByteBuffer allocate(int count, int width) { + return ByteBuffer.wrap(new byte[count * width]).order(ByteOrder.nativeOrder()); + } + + private static int bitmapBytes(int bits) { + return (bits + 7) / 8; + } + + private static void setBit(byte[] bitmap, int index) { + bitmap[index >>> 3] |= (byte) (1 << (index & 7)); + } + + private static String charSequence(Object value) { + return value instanceof CharSequence ? value.toString() : null; + } + + private static String decimalText(Object value) { + if (value instanceof BigDecimal) { + return ((BigDecimal) value).toPlainString(); + } + if (value instanceof Double || value instanceof Float) { + double number = ((Number) value).doubleValue(); + // NaN and the infinities go as they are, for chDB to refuse with its own message. + return Double.isFinite(number) ? BigDecimal.valueOf(number).toPlainString() : Double.toString(number); + } + if (value instanceof Number) { + return value.toString(); + } + return charSequence(value); + } +} diff --git a/chdb-jdbc/src/main/java/org/chdb/internal/ChdbNative.java b/chdb-jdbc/src/main/java/org/chdb/internal/ChdbNative.java index f274b16..5eaf7f2 100644 --- a/chdb-jdbc/src/main/java/org/chdb/internal/ChdbNative.java +++ b/chdb-jdbc/src/main/java/org/chdb/internal/ChdbNative.java @@ -28,7 +28,7 @@ public final class ChdbNative { * Must equal {@code chdb_jni::kJniAbiVersion} in the shim and {@code * chdb.jni.abi.version} in the poms. Verified at load time before any other call. */ - public static final int JNI_ABI_VERSION = 5; + public static final int JNI_ABI_VERSION = 6; /** Handle kinds, for {@link #openHandleCount(int)}. */ public static final int KIND_CONNECTION = 1; @@ -229,6 +229,57 @@ public static native long rowBinaryOpen( /** Releases the engine's stream handle. Idempotent. */ public static native void rowBinaryClose(long stream); + // ---------------------------------------------------------------- scalar functions + + /** + * Whether the loaded libchdb exports {@code chdb_create_scalar_function} and {@code + * chdb_drop_scalar_function}. + * + *

    Optional symbols, resolved by {@code dlsym} like the classifier: they landed in chdb-core + * v26.11.2-rc.3, which is the pinned baseline, and an older engine the loader is pointed at + * cannot register functions but runs everything else. + */ + public static native boolean scalarFunctionsAvailable(); + + /** + * {@code chdb_create_scalar_function}. On success chDB owns {@code callback}: it calls it on its + * own threads, and calls its {@code destroyed()} once the function is dropped and unused. Called + * through {@link ScalarFunctionCallback#register}, which keeps the count of live functions. + * + * @param argumentTypes ClickHouse type names, UTF-8, one per argument + * @param flags {@code ScalarFunctionCallback} flag bits + * @throws ChdbNativeException carrying chDB's error if the registration is refused + */ + public static native void createScalarFunction( + long connection, + byte[] name, + byte[][] argumentTypes, + byte[] returnType, + int flags, + ScalarFunctionCallback callback); + + /** + * {@code chdb_drop_scalar_function}, without a connection: a registration outlives every + * connection, and the call accepts none. chDB may destroy the function inside this call. + * + * @throws ChdbNativeException if no function has that name + */ + public static native void dropScalarFunction(byte[] name); + + /** + * Copies the Arrow array at these C Data addresses, children included, onto the Java heap. + * + *

    Only for a scalar function's arguments, inside its callback: the addresses are chDB's and + * valid only for the call, which is why the buffers are copied rather than viewed. + */ + public static native ArrowColumn copyArrowArray(long schemaAddress, long arrayAddress); + + /** + * Fills the zeroed C Data structs at these addresses with a copy of {@code column} in native + * memory, which chDB then owns and frees through their release callbacks. + */ + public static native void exportArrowArray(ArrowColumn column, long schemaAddress, long arrayAddress); + // ---------------------------------------------------------------- diagnostics /** diff --git a/chdb-jdbc/src/main/java/org/chdb/internal/ScalarFunctionCallback.java b/chdb-jdbc/src/main/java/org/chdb/internal/ScalarFunctionCallback.java new file mode 100644 index 0000000..3187189 --- /dev/null +++ b/chdb-jdbc/src/main/java/org/chdb/internal/ScalarFunctionCallback.java @@ -0,0 +1,143 @@ +package org.chdb.internal; + +import java.nio.charset.StandardCharsets; +import java.util.concurrent.atomic.AtomicLong; + +/** + * What the shim calls for one registered scalar function: {@link #invoke} once per batch of rows, + * and {@link #destroyed} once chDB has let go of the registration. + * + *

    Not public API. Subclasses turn the batch's Arrow C Data into the function's arguments and + * its result back into Arrow: one row at a time with {@link ArrowDecoder} and {@link ArrowEncoder} + * in chdb-jdbc, with Arrow Java in chdb-arrow. + * + *

    Threads

    + * chDB runs {@link #invoke} on its own threads, several at once, and the shim attaches each one to + * the JVM as a daemon the first time. So {@link #apply} must be safe to run concurrently, and so + * must the user's function behind it. While it runs, {@link #isRunningOnThisThread()} is true, + * which is what lets the driver refuse SQL from inside a function instead of deadlocking on it. + * + *

    Ownership

    + * A successful registration hands this object to chDB, which keeps it until the function is + * dropped and nothing uses it any more, then calls {@link #destroyed}. A failed one hands over + * nothing, and the registering code calls {@link #abandon} instead. + */ +public abstract class ScalarFunctionCallback { + + /** {@code chdb_scalar_function_flag} bits, as chdb.h defines them. */ + public static final int VOLATILE = 1; + public static final int SPECIAL_NULL_HANDLING = 1 << 1; + public static final int BINARY_STRINGS = 1 << 2; + + private static final ThreadLocal RUNNING = new ThreadLocal<>(); + + /** Registrations chDB holds: counted before chDB can see them, uncounted in {@link #destroyed}. */ + private static final AtomicLong LIVE = new AtomicLong(); + + protected ScalarFunctionCallback() { + } + + /** Whether this thread is running a scalar function, where chDB must not be called. */ + public static boolean isRunningOnThisThread() { + return RUNNING.get() != null; + } + + /** + * Functions registered and not yet destroyed by chDB. Diagnostic, like {@link + * ChdbNative#openHandleCount(int)}: after every function is dropped and no query is using one, + * it is back to zero. + */ + public static long liveCount() { + return LIVE.get(); + } + + /** + * {@code chdb_create_scalar_function} with this object as the function. On success chDB owns + * it; on failure nothing changed hands and the caller still has to {@link #abandon} it. + * + * @throws ChdbNativeException carrying chDB's error if the registration is refused + */ + public final void register(long connection, byte[] name, byte[][] argumentTypes, byte[] returnType, int flags) { + // Counted first: once chDB has it, a drop by name on another thread can destroy it + // before the call below even returns. + LIVE.incrementAndGet(); + try { + ChdbNative.createScalarFunction(connection, name, argumentTypes, returnType, flags, this); + } catch (RuntimeException | Error e) { + LIVE.decrementAndGet(); + throw e; + } + } + + /** + * Computes one batch: reads the arguments chDB passes at {@code argumentSchema} and {@code + * arguments} -- a struct array with one child per argument -- and fills the zeroed {@code + * resultSchema} and {@code result} with exactly as many values as it has rows. The addresses + * are valid only during the call. + */ + protected abstract void apply(long argumentSchema, long arguments, long resultSchema, long result) + throws Exception; + + /** + * Frees what the function holds, once chDB is done with it or after a failed registration. + * Runs on any thread, possibly inside another chDB call, so it must not call chDB. + */ + protected void release() { + } + + /** Releases a callback that never reached chDB. */ + public final void abandon() { + releaseQuietly(); + } + + /** + * Called by the shim, on an engine thread, once per batch. Returns null on success, or the + * failure as UTF-8 for chDB's error buffer, which makes it the query's error. Catches every + * Throwable: an exception left pending here would surface in whatever Java frame the engine + * thread reaches next, or in none. + */ + final byte[] invoke(long argumentSchema, long arguments, long resultSchema, long result) { + RUNNING.set(Boolean.TRUE); + try { + apply(argumentSchema, arguments, resultSchema, result); + return null; + } catch (Throwable failure) { + return describe(failure).getBytes(StandardCharsets.UTF_8); + } finally { + RUNNING.remove(); + } + } + + /** Called by the shim when chDB destroys the registration. Never throws. */ + final void destroyed() { + LIVE.decrementAndGet(); + releaseQuietly(); + } + + private void releaseQuietly() { + try { + release(); + } catch (Throwable ignored) { + // Nobody to report it to: this runs on whichever thread chDB destroyed the function + // on, after every query that could have shown the error has finished. + } + } + + /** + * The message a failed batch reports: the exception and its causes, each as its class and + * message, since a bare message can be empty (a NullPointerException) or say nothing without + * its type. A {@link ScalarFunctionException} is the driver's own report and is shown as is. + */ + static String describe(Throwable failure) { + StringBuilder text = new StringBuilder(); + Throwable current = failure; + // Bounded: a cause chain can be a cycle. + for (int depth = 0; current != null && depth < 8; depth++, current = current.getCause()) { + if (depth > 0) { + text.append("; caused by "); + } + text.append(current instanceof ScalarFunctionException ? current.getMessage() : current.toString()); + } + return text.toString(); + } +} diff --git a/chdb-jdbc/src/main/java/org/chdb/internal/ScalarFunctionException.java b/chdb-jdbc/src/main/java/org/chdb/internal/ScalarFunctionException.java new file mode 100644 index 0000000..73b2887 --- /dev/null +++ b/chdb-jdbc/src/main/java/org/chdb/internal/ScalarFunctionException.java @@ -0,0 +1,18 @@ +package org.chdb.internal; + +/** + * A scalar function's batch failing for a reason the driver states itself -- a result of the wrong + * Java type, or of the wrong length -- rather than one the user's code threw. + * + *

    Not public API, and never seen by a caller: it is thrown and caught inside {@link + * ScalarFunctionCallback#invoke}, which reports its message without the class name a user's + * exception is reported with. + */ +public final class ScalarFunctionException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public ScalarFunctionException(String message) { + super(message); + } +} diff --git a/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbConnection.java b/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbConnection.java index 0ae2ef6..d15ae02 100644 --- a/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbConnection.java +++ b/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbConnection.java @@ -19,6 +19,7 @@ import java.sql.Struct; import java.util.Collections; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; @@ -30,6 +31,7 @@ import org.chdb.internal.ChdbNative; import org.chdb.internal.ChdbNativeException; import org.chdb.internal.NativeLibraryLoader; +import org.chdb.internal.ScalarFunctionCallback; import org.chdb.internal.UnsupportedPlatformException; /** @@ -122,6 +124,9 @@ public final class ChdbConnection implements Connection { ChdbConnection(ChdbUrl url) throws SQLException { this.url = url; + if (ScalarFunctionCallback.isRunningOnThisThread()) { + throw ChdbExceptions.insideScalarFunction(); + } try { // Loads libchdb and the shim. The opt-out from chDB's signal handlers happens @@ -388,6 +393,44 @@ public long insertArrowStreamNative(String tableName, long streamAddress, int op } } + /** + * Registers {@code callback} as a scalar function named {@code name}. Bridge for {@link + * ChdbScalarFunctionBuilder} and the optional chdb-arrow artifact's builder, which build the + * callback; it runs under this connection's statement slot and execution gate like any other + * call into the engine. The registration itself is process-wide and outlives this connection. + * + *

    If this throws, the function was not registered and {@code callback} is still the + * caller's to {@link ScalarFunctionCallback#abandon abandon}. + * + * @param argumentTypes the parameters' ClickHouse type names, in order + * @param flags {@link ScalarFunctionCallback} flag bits + */ + public ChdbFunctions.RegisteredFunction registerScalarFunctionNative( + String name, List argumentTypes, String returnType, int flags, ScalarFunctionCallback callback) + throws SQLException { + Objects.requireNonNull(name, "name"); + Objects.requireNonNull(argumentTypes, "argumentTypes"); + Objects.requireNonNull(returnType, "returnType"); + Objects.requireNonNull(callback, "callback"); + ChdbFunctions.requireSupport(); + statementSlot.acquire("register scalar function " + name); + boolean entered = false; + try { + entered = executionStarted(); + if (!entered || isClosed()) { + throw ChdbExceptions.closed("Connection"); + } + return ChdbFunctions.create(handle, name, argumentTypes, returnType, flags, callback); + } catch (ChdbNativeException e) { + throw ChdbExceptions.wrap("Cannot register scalar function " + name, e); + } finally { + if (entered) { + executionFinished(); + } + statementSlot.release(); + } + } + /** * Announces that this thread is about to start a statement in the engine. * @@ -594,6 +637,11 @@ java.time.ZoneId sessionTimeZone() { @Override public void close() throws SQLException { + // Refused before anything is torn down: closing the connection whose query is running the + // function would wait for that query. + if (ScalarFunctionCallback.isRunningOnThisThread()) { + throw ChdbExceptions.insideScalarFunction(); + } synchronized (closeLock) { doClose(); } diff --git a/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbExceptions.java b/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbExceptions.java index 140f0bf..59f74ee 100644 --- a/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbExceptions.java +++ b/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbExceptions.java @@ -122,6 +122,23 @@ static SQLFeatureNotSupportedException notSupported(String what) { "0A000"); } + /** + * The exception for chDB used from inside a scalar function. + * + *

    chDB calls a scalar function in the middle of a query, on one of its own threads. A + * statement started there would wait for that query to finish -- for the connection's + * statement slot, or inside the engine -- while the query waits for the function, and chdb.h + * forbids the call for that reason. Refused here so that it fails the query rather than hangs it. + */ + static SQLException insideScalarFunction() { + return new SQLFeatureNotSupportedException( + "chDB cannot be used from inside a scalar function: the function runs in the middle of" + + " a query, and a statement, connection or registration started from it would wait" + + " for that query to finish. Work out what the function needs before the query, or" + + " pass it in as an argument.", + "0A000"); + } + /** The exception for a method called on a closed object. */ static SQLException closed(String what) { return new SQLNonTransientException(what + " is closed", "HY010"); diff --git a/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbFunctions.java b/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbFunctions.java new file mode 100644 index 0000000..8da5f52 --- /dev/null +++ b/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbFunctions.java @@ -0,0 +1,190 @@ +package org.chdb.jdbc; + +import java.sql.SQLException; +import java.sql.SQLFeatureNotSupportedException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import org.chdb.internal.ChdbNative; +import org.chdb.internal.ChdbNativeException; +import org.chdb.internal.NativeLibraryLoader; +import org.chdb.internal.ScalarFunctionCallback; +import org.chdb.internal.UnsupportedPlatformException; + +/** + * Scalar user-defined functions: Java code called from SQL. + * + *

    {@code
    + * try (Connection connection = DriverManager.getConnection("jdbc:chdb:")) {
    + *     ChdbFunctions.scalarFunction()
    + *             .withName("plus_one")
    + *             .withParameter("Int64")
    + *             .withReturnType("Int64")
    + *             .withFunction((Long x) -> x + 1)
    + *             .register(connection);
    + *     // SELECT plus_one(toInt64(number)) FROM numbers(3)  ->  1, 2, 3
    + * }
    + * }
    + * + *

    Parameters and the result are declared as ClickHouse type names, which is what the engine + * checks a call against; an argument of another type is accepted when it converts without loss, + * an {@code Int32} for an {@code Int64} parameter, and arrives converted. Each value reaches Java + * as the type {@code ResultSet.getObject} gives for it, with {@code java.time} types for dates and + * timestamps; {@code docs/scalar-functions.md} has the full mapping in both directions. + * + *

    Process-wide, unlike DuckDB

    + * A function is registered with the engine, not with the connection it was registered through. + * Every connection in the JVM can call it, including ones opened later, and it stays registered + * after all of them are closed, until it is dropped with {@link #dropScalarFunction} or by + * closing the {@link RegisteredFunction} the registration returned. DuckDB's functions belong to + * a connection's database instead. The name must be free: registering one that a built-in, + * aggregate or SQL function already has, or that another registration holds, fails. + * + *

    Threads

    + * chDB calls a function once per block of rows, from several of its own threads at once, so the + * function must be safe for concurrent use. It runs inside a query, so it must not use chDB: a + * statement, connection or registration started from inside it is refused with an + * SQLException rather than left to deadlock. + * + *

    Needs chdb-core v26.11.2-rc.3 or later; {@link #isScalarFunctionSupported()} says whether + * the loaded engine has it. + */ +public final class ChdbFunctions { + + /** + * The registrations made through this class, by name. Lets a {@link RegisteredFunction} drop + * only the registration it came from, never a later one that reused the name. + */ + private static final Map REGISTERED = new HashMap<>(); + + private ChdbFunctions() { + } + + /** Starts declaring a scalar function computed one row at a time. */ + public static ChdbScalarFunctionBuilder scalarFunction() { + return new ChdbScalarFunctionBuilder(); + } + + /** + * Whether the loaded libchdb can register scalar functions: chdb-core v26.11.2-rc.3 and later. + * + * @throws SQLException if the native runtime cannot be loaded at all + */ + public static boolean isScalarFunctionSupported() throws SQLException { + // Loaded first, as ChdbConnection does, so that a missing runtime is this SQLException + // rather than an ExceptionInInitializerError out of ChdbNative's static initializer. + try { + NativeLibraryLoader.ensureLoaded(); + } catch (UnsupportedPlatformException e) { + throw ChdbExceptions.wrap("Cannot load the chDB native runtime", e); + } catch (ChdbNativeException e) { + throw ChdbExceptions.wrap("Cannot load the chDB native runtime", e); + } + return ChdbNative.scalarFunctionsAvailable(); + } + + /** + * Unregisters the function of this name, whoever registered it. A query already using it + * finishes with it, and chDB releases it once nothing does. Needs no connection. + * + * @throws SQLException if no function of that name is registered, or this engine cannot + * register functions at all + */ + public static void dropScalarFunction(String name) throws SQLException { + Objects.requireNonNull(name, "name"); + refuseInsideAFunction(); + requireSupport(); + synchronized (REGISTERED) { + // Forgotten even if chDB refuses: the only refusal left is that the name is not + // registered, and then there is nothing a handle could drop either. + REGISTERED.remove(name); + drop(name); + } + } + + /** + * Registers {@code callback} under {@code name} through the connection with handle {@code + * connection}. The caller holds the connection's statement slot. + */ + static RegisteredFunction create( + long connection, + String name, + List argumentTypes, + String returnType, + int flags, + ScalarFunctionCallback callback) { + synchronized (REGISTERED) { + callback.register(connection, Utf8.encode(name), Utf8.encodeAll(argumentTypes), Utf8.encode(returnType), flags); + RegisteredFunction registered = new RegisteredFunction(name); + REGISTERED.put(name, registered); + return registered; + } + } + + /** Refuses before anything else when the engine lacks the ABI, with the release that has it. */ + static void requireSupport() throws SQLException { + if (isScalarFunctionSupported()) { + return; + } + throw new SQLFeatureNotSupportedException( + "This libchdb (engine " + ChdbNative.engineVersion() + ") lacks the scalar function ABI, chdb_create_scalar_function" + + " and chdb_drop_scalar_function: Java scalar functions need chdb-core v26.11.2-rc.3 or" + + " later.", + "0A000"); + } + + /** + * Checked before the registry is touched, so that a drop refused inside a function leaves the + * registration and its handle as they were. + */ + private static void refuseInsideAFunction() throws SQLException { + if (ScalarFunctionCallback.isRunningOnThisThread()) { + throw ChdbExceptions.insideScalarFunction(); + } + } + + private static void drop(String name) throws SQLException { + try { + ChdbNative.dropScalarFunction(Utf8.encode(name)); + } catch (ChdbNativeException e) { + throw ChdbExceptions.wrap("Cannot drop scalar function " + name, e); + } + } + + /** + * A function registered through {@link ChdbScalarFunctionBuilder#register} or chdb-arrow's + * {@code ArrowScalarFunctionBuilder}. Closing it drops the function. + */ + public static final class RegisteredFunction implements AutoCloseable { + private final String name; + + private RegisteredFunction(String name) { + this.name = name; + } + + /** The name SQL calls the function by. */ + public String name() { + return name; + } + + /** + * Drops the function, if it is still this registration under its name: after {@link + * #dropScalarFunction}, or after another registration took the name, there is nothing of + * this one left to drop and closing does nothing. Idempotent. + * + * @throws SQLException if chDB refuses the drop + */ + @Override + public void close() throws SQLException { + refuseInsideAFunction(); + synchronized (REGISTERED) { + if (REGISTERED.get(name) != this) { + return; + } + REGISTERED.remove(name); + drop(name); + } + } + } +} diff --git a/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbRowFunction.java b/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbRowFunction.java new file mode 100644 index 0000000..c453e32 --- /dev/null +++ b/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbRowFunction.java @@ -0,0 +1,26 @@ +package org.chdb.jdbc; + +/** + * A scalar function computed one row at a time, from any number of arguments. + * + *

    Registered with {@link ChdbScalarFunctionBuilder#withRowFunction}. For one or two arguments, + * {@link ChdbScalarFunctionBuilder#withFunction(java.util.function.Function)} and its {@code + * BiFunction} and {@code Supplier} overloads take an ordinary lambda instead. + * + *

    chDB calls it from several of its own threads at once, so it must be safe for concurrent + * use, and it runs inside a query, so it must not use chDB: the driver refuses any statement, + * connection or registration started from inside it. + */ +@FunctionalInterface +public interface ChdbRowFunction { + + /** + * Computes one row. + * + * @param arguments one value per declared parameter, in order, as the type mapping in {@link + * ChdbFunctions} gives them. The array is reused for the next row; copy it to keep it. + * @return the row's value, of a Java type the declared return type takes, or null for NULL + * @throws Exception to fail the query, with the exception as its error message + */ + Object apply(Object[] arguments) throws Exception; +} diff --git a/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbScalarFunctionBuilder.java b/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbScalarFunctionBuilder.java new file mode 100644 index 0000000..ea24474 --- /dev/null +++ b/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbScalarFunctionBuilder.java @@ -0,0 +1,207 @@ +package org.chdb.jdbc; + +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.SQLFeatureNotSupportedException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Supplier; +import org.chdb.internal.ArrowDecoder; +import org.chdb.internal.ClickHouseType; +import org.chdb.internal.ScalarFunctionCallback; + +/** + * Declares a scalar function computed one row at a time, and registers it. From {@link + * ChdbFunctions#scalarFunction()}. + * + *

    A name, a return type and a function are required; parameters are declared in order, and the + * function's arity has to match them. Types are ClickHouse type names, such as {@code "Int64"}, + * {@code "Nullable(String)"} or {@code "Array(Float64)"}. + * + *

    Unlike DuckDB, chDB keeps NULLs away from a function by default: a row with a NULL argument + * yields NULL without the function being called, and the result becomes {@code Nullable}. {@link + * #withSpecialNullHandling()} passes them instead. + */ +public final class ChdbScalarFunctionBuilder { + + private String name; + private final List parameters = new ArrayList<>(); + private String returnType; + private int flags; + private ChdbRowFunction function; + /** How many parameters the function takes, or -1 for any. */ + private int arity = -1; + private String functionKind; + + ChdbScalarFunctionBuilder() { + } + + /** The name SQL calls the function by. Case-sensitive. */ + public ChdbScalarFunctionBuilder withName(String name) { + Objects.requireNonNull(name, "name"); + if (name.trim().isEmpty()) { + throw new IllegalArgumentException("a scalar function name cannot be empty"); + } + this.name = name; + return this; + } + + /** Declares the next parameter, as a ClickHouse type name. */ + public ChdbScalarFunctionBuilder withParameter(String clickHouseType) { + parameters.add(typeName(clickHouseType)); + return this; + } + + /** Declares the next parameters, in order. */ + public ChdbScalarFunctionBuilder withParameters(String... clickHouseTypes) { + for (String type : clickHouseTypes) { + withParameter(type); + } + return this; + } + + /** + * The ClickHouse type of the result. What the function returns is converted to it the way CAST + * does, and a value that does not fit fails the query. + */ + public ChdbScalarFunctionBuilder withReturnType(String clickHouseType) { + this.returnType = typeName(clickHouseType); + return this; + } + + /** + * Marks the function as returning different results for the same arguments, like {@code + * rand()}. Otherwise chDB may evaluate a call with constant arguments, or none, once for all + * rows of a query. + */ + public ChdbScalarFunctionBuilder withVolatile() { + flags |= ScalarFunctionCallback.VOLATILE; + return this; + } + + /** + * Passes NULL arguments to the function, as Java {@code null}, and keeps the return type as + * declared. By default a row with a NULL argument yields NULL without a call, and the result + * becomes {@code Nullable}. With it, an argument that can be NULL needs a declared type that + * can hold one, which an {@code Array} cannot. + */ + public ChdbScalarFunctionBuilder withSpecialNullHandling() { + flags |= ScalarFunctionCallback.SPECIAL_NULL_HANDLING; + return this; + } + + /** + * Passes {@code String} and {@code FixedString} arguments as {@code byte[]} rather than as + * {@code String}, for data that is not valid UTF-8. Without it, a value that is not valid UTF-8 + * fails the query. + */ + public ChdbScalarFunctionBuilder withBinaryStrings() { + flags |= ScalarFunctionCallback.BINARY_STRINGS; + return this; + } + + /** The function of a scalar function without parameters, called once per row. */ + public ChdbScalarFunctionBuilder withFunction(Supplier function) { + Objects.requireNonNull(function, "function"); + return set(arguments -> function.get(), 0, "Supplier"); + } + + /** The function of a scalar function with one parameter. */ + public ChdbScalarFunctionBuilder withFunction(Function function) { + Objects.requireNonNull(function, "function"); + @SuppressWarnings("unchecked") + Function untyped = (Function) function; + return set(arguments -> untyped.apply(arguments[0]), 1, "Function"); + } + + /** The function of a scalar function with two parameters. */ + public ChdbScalarFunctionBuilder withFunction(BiFunction function) { + Objects.requireNonNull(function, "function"); + @SuppressWarnings("unchecked") + BiFunction untyped = (BiFunction) function; + return set(arguments -> untyped.apply(arguments[0], arguments[1]), 2, "BiFunction"); + } + + /** The function, for any number of parameters, which may throw checked exceptions. */ + public ChdbScalarFunctionBuilder withRowFunction(ChdbRowFunction function) { + return set(Objects.requireNonNull(function, "function"), -1, "ChdbRowFunction"); + } + + /** + * Registers the function through {@code connection}, which must be a chDB connection or wrap + * one. The registration is process-wide and outlives the connection; close what this returns, + * or call {@link ChdbFunctions#dropScalarFunction}, to drop it. + * + * @throws IllegalStateException if the name, the return type or the function is missing, or + * the function takes a different number of arguments than the parameters declared + * @throws SQLFeatureNotSupportedException if a parameter has a type no Java value is read as, + * or the loaded engine cannot register functions + * @throws SQLException if chDB refuses the registration: the name is taken, or a type is + * unknown or has no Arrow form + */ + public ChdbFunctions.RegisteredFunction register(Connection connection) throws SQLException { + Objects.requireNonNull(connection, "connection"); + if (name == null || returnType == null || function == null) { + throw new IllegalStateException("a scalar function needs withName, withReturnType and withFunction" + + " or withRowFunction before register"); + } + if (arity >= 0 && arity != parameters.size()) { + throw new IllegalStateException("a " + functionKind + " takes " + arity + " arguments, but " + name + " declares " + + parameters.size() + " parameters"); + } + List types = new ArrayList<>(parameters.size()); + for (String parameter : parameters) { + ClickHouseType type = parse(parameter); + try { + ArrowDecoder.checkReadable(type); + } catch (IllegalArgumentException e) { + throw new SQLFeatureNotSupportedException("Cannot register " + name + ": " + e.getMessage(), "0A000"); + } + types.add(type); + } + RowFunctionCallback callback = + new RowFunctionCallback(function, Collections.unmodifiableList(types), parse(returnType), flags); + return unwrap(connection).registerScalarFunctionNative(name, parameters, returnType, flags, callback); + } + + private ChdbScalarFunctionBuilder set(ChdbRowFunction function, int arity, String kind) { + this.function = function; + this.arity = arity; + this.functionKind = kind; + return this; + } + + private static String typeName(String clickHouseType) { + Objects.requireNonNull(clickHouseType, "clickHouseType"); + if (clickHouseType.trim().isEmpty()) { + throw new IllegalArgumentException("a ClickHouse type name cannot be empty"); + } + return clickHouseType; + } + + /** + * The type as the decoder and encoder see it. A name the parser rejects outright is kept as + * an unknown type: chDB is the authority on what a type name means, and refuses it at + * registration with its own message. + */ + private static ClickHouseType parse(String type) { + try { + return ClickHouseType.parse(type); + } catch (IllegalArgumentException e) { + return ClickHouseType.unknown(type); + } + } + + private static ChdbConnection unwrap(Connection connection) throws SQLException { + try { + return connection.unwrap(ChdbConnection.class); + } catch (SQLException e) { + throw new SQLException("Scalar functions are registered through a chDB connection, and " + + connection.getClass().getName() + " is not one and does not wrap one", "HY000", e); + } + } +} diff --git a/chdb-jdbc/src/main/java/org/chdb/jdbc/RowFunctionCallback.java b/chdb-jdbc/src/main/java/org/chdb/jdbc/RowFunctionCallback.java new file mode 100644 index 0000000..e4c533b --- /dev/null +++ b/chdb-jdbc/src/main/java/org/chdb/jdbc/RowFunctionCallback.java @@ -0,0 +1,47 @@ +package org.chdb.jdbc; + +import java.util.List; +import org.chdb.internal.ArrowColumn; +import org.chdb.internal.ArrowDecoder; +import org.chdb.internal.ArrowEncoder; +import org.chdb.internal.ChdbNative; +import org.chdb.internal.ClickHouseType; +import org.chdb.internal.ScalarFunctionCallback; + +/** + * Runs a {@link ChdbRowFunction} over each batch chDB passes: copies the batch's Arrow arguments + * onto the heap, calls the function once per row with Java values, and hands the results back to + * chDB as one Arrow array in native memory. + * + *

    Holds nothing native, so there is nothing to release when chDB destroys it. + */ +final class RowFunctionCallback extends ScalarFunctionCallback { + + private final ChdbRowFunction function; + private final List parameters; + private final ArrowEncoder result; + private final boolean binaryStrings; + + RowFunctionCallback( + ChdbRowFunction function, List parameters, ClickHouseType returnType, int flags) { + this.function = function; + this.parameters = parameters; + this.result = ArrowEncoder.forType(returnType); + this.binaryStrings = (flags & BINARY_STRINGS) != 0; + } + + @Override + protected void apply(long argumentSchema, long arguments, long resultSchema, long result) throws Exception { + ArrowColumn batch = ChdbNative.copyArrowArray(argumentSchema, arguments); + ArrowDecoder.Reader[] readers = ArrowDecoder.readers(batch, parameters, binaryStrings); + Object[] row = new Object[readers.length]; + Object[] results = new Object[batch.length()]; + for (int i = 0; i < results.length; i++) { + for (int a = 0; a < readers.length; a++) { + row[a] = readers[a].read(i); + } + results[i] = function.apply(row); + } + ChdbNative.exportArrowArray(this.result.encode(results), resultSchema, result); + } +} diff --git a/chdb-jdbc/src/main/java/org/chdb/jdbc/StatementSlot.java b/chdb-jdbc/src/main/java/org/chdb/jdbc/StatementSlot.java index 1e90729..2bf656a 100644 --- a/chdb-jdbc/src/main/java/org/chdb/jdbc/StatementSlot.java +++ b/chdb-jdbc/src/main/java/org/chdb/jdbc/StatementSlot.java @@ -3,6 +3,7 @@ import java.sql.SQLException; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicReference; +import org.chdb.internal.ScalarFunctionCallback; /** * Lets one statement at a time run on a chDB connection. @@ -30,6 +31,9 @@ * A thread that opens a second result set without closing the first would wait for itself * forever. That is a caller bug, and a deadlock is the least useful way to report one, so * re-entry from the holding thread raises an exception naming the statement still open. + * + *

    So does a statement started from inside a scalar function, from any thread: the query + * calling the function can hold this very slot, waiting for the function to return. */ final class StatementSlot { @@ -57,6 +61,11 @@ private static final class Holder { * @throws SQLException if this thread already holds the slot, or the wait is interrupted */ void acquire(String sql) throws SQLException { + // Before the wait, which is the deadlock: the query running the function may hold this + // very slot. + if (ScalarFunctionCallback.isRunningOnThisThread()) { + throw ChdbExceptions.insideScalarFunction(); + } Holder current = holder.get(); if (current != null && current.thread == Thread.currentThread()) { // Plain SQLException on purpose: JDBC 4 defines no subtype for SQLSTATE class 25, diff --git a/chdb-jdbc/src/test/java/org/chdb/internal/ArrowDecoderTest.java b/chdb-jdbc/src/test/java/org/chdb/internal/ArrowDecoderTest.java new file mode 100644 index 0000000..9e57c8a --- /dev/null +++ b/chdb-jdbc/src/test/java/org/chdb/internal/ArrowDecoderTest.java @@ -0,0 +1,288 @@ +package org.chdb.internal; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.net.InetAddress; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.LocalDate; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * The argument decoder against Arrow arrays laid out the way chDB sends them. + * + *

    The formats are the ones measured from v26.11.2-rc.3 by registering a function per type and + * logging its argument schema: {@code Int128} and {@code Enum8} as {@code u}, {@code IPv4} as + * {@code I}, {@code UUID} as {@code w:16} tagged {@code arrow.uuid}, {@code IPv6} as a bare + * {@code w:16}, {@code Date} and {@code Date32} as {@code tdD}, {@code DateTime} as {@code + * tss:} and {@code DateTime64(p)} in the unit its precision needs. The integration suite + * checks the same values arrive from real queries. + */ +class ArrowDecoderTest { + + private static final ArrowColumn[] NONE = new ArrowColumn[0]; + + private static ArrowColumn column(String format, int length, byte[] validity, byte[]... rest) { + return column(format, null, length, 0, validity, rest, NONE); + } + + private static ArrowColumn column( + String format, String extension, int length, int offset, byte[] validity, byte[][] rest, + ArrowColumn[] children) { + byte[][] buffers = new byte[rest.length + 1][]; + buffers[0] = validity; + System.arraycopy(rest, 0, buffers, 1, rest.length); + int nulls = 0; + if (validity != null) { + for (int i = 0; i < length; i++) { + if (!ArrowColumn.bit(validity, offset + i)) { + nulls++; + } + } + } + return new ArrowColumn(format, extension, nulls > 0, length, offset, nulls, buffers, children); + } + + private static ByteBuffer buffer(int bytes) { + return ByteBuffer.allocate(bytes).order(ByteOrder.nativeOrder()); + } + + private static byte[] longs(long... values) { + ByteBuffer out = buffer(values.length * 8); + for (long value : values) { + out.putLong(value); + } + return out.array(); + } + + private static byte[] ints(int... values) { + ByteBuffer out = buffer(values.length * 4); + for (int value : values) { + out.putInt(value); + } + return out.array(); + } + + private static byte[] bitmap(boolean... valid) { + byte[] bits = new byte[(valid.length + 7) / 8]; + for (int i = 0; i < valid.length; i++) { + if (valid[i]) { + bits[i >>> 3] |= (byte) (1 << (i & 7)); + } + } + return bits; + } + + /** offsets then data, for utf8 or binary. */ + private static byte[][] text(String... values) { + int[] offsets = new int[values.length + 1]; + StringBuilder data = new StringBuilder(); + for (int i = 0; i < values.length; i++) { + data.append(values[i] == null ? "" : values[i]); + offsets[i + 1] = data.toString().getBytes(StandardCharsets.UTF_8).length; + } + return new byte[][] {ints(offsets), data.toString().getBytes(StandardCharsets.UTF_8)}; + } + + private static ArrowColumn textColumn(String format, byte[] validity, String... values) { + return column(format, null, values.length, 0, validity, text(values), NONE); + } + + private static Object read(ArrowColumn column, String declared, int row) { + return ArrowDecoder.reader(column, ClickHouseType.parse(declared), false).read(row); + } + + @Test + @DisplayName("integers arrive as the Java type getObject gives for the ClickHouse type") + void integers() { + ArrowColumn int8 = column("c", 2, null, new byte[] {-1, 7}); + assertEquals((byte) -1, read(int8, "Int8", 0)); + ArrowColumn uint8 = column("C", 1, null, new byte[] {(byte) 0xff}); + assertEquals((short) 255, read(uint8, "UInt8", 0)); + ByteBuffer shorts = buffer(4).putShort((short) -2).putShort((short) 0xffff); + assertEquals((short) -2, read(column("s", 2, null, shorts.array()), "Int16", 0)); + assertEquals(65535, read(column("S", 2, null, shorts.array()), "UInt16", 1)); + assertEquals(-3, read(column("i", 1, null, ints(-3)), "Int32", 0)); + assertEquals(4294967295L, read(column("I", 1, null, ints(-1)), "UInt32", 0)); + assertEquals(Long.MIN_VALUE, read(column("l", 1, null, longs(Long.MIN_VALUE)), "Int64", 0)); + assertEquals(new BigInteger("18446744073709551615"), read(column("L", 1, null, longs(-1)), "UInt64", 0)); + assertEquals(BigInteger.valueOf(5), read(column("L", 1, null, longs(5)), "UInt64", 0)); + // Interval types arrive as int64 counts. + assertEquals(3L, read(column("l", 1, null, longs(3)), "IntervalDay", 0)); + } + + @Test + @DisplayName("128- and 256-bit integers arrive as text and are read as BigInteger") + void bigIntegers() { + String max = "170141183460469231731687303715884105727"; + assertEquals(new BigInteger(max), read(textColumn("u", null, max), "Int128", 0)); + assertEquals(new BigInteger("-5"), read(textColumn("u", null, "-5"), "Int256", 0)); + // Binary strings make the text binary, and it is still a number. + assertEquals(new BigInteger(max), read(textColumn("z", null, max), "UInt128", 0)); + } + + @Test + @DisplayName("floats, booleans and NULL") + void scalars() { + ByteBuffer floats = buffer(4).putFloat(1.5f); + assertEquals(1.5f, read(column("f", 1, null, floats.array()), "Float32", 0)); + ByteBuffer doubles = buffer(8).putDouble(Double.NaN); + assertTrue(Double.isNaN((Double) read(column("g", 1, null, doubles.array()), "Float64", 0))); + ArrowColumn bools = column("b", 3, null, bitmap(true, false, true)); + assertEquals(Boolean.TRUE, read(bools, "Bool", 0)); + assertEquals(Boolean.FALSE, read(bools, "Bool", 1)); + + ArrowColumn nullable = column("l", 3, bitmap(true, false, true), longs(1, 0, 3)); + assertEquals(1L, read(nullable, "Int64", 0)); + assertNull(read(nullable, "Int64", 1)); + assertNull(read(new ArrowColumn("n", null, true, 2, 0, 2, new byte[0][], NONE), "Nothing", 1)); + } + + @Test + @DisplayName("strings are text, enums are labels, and binary strings are bytes") + void strings() { + ArrowColumn utf8 = textColumn("u", null, "héllo", "", "😀"); + assertEquals("héllo", read(utf8, "String", 0)); + assertEquals("", read(utf8, "String", 1)); + assertEquals("😀", read(utf8, "String", 2)); + assertEquals("a", read(textColumn("u", null, "a"), "Enum8('a' = 1)", 0)); + + ArrowColumn binary = column("z", null, 1, 0, null, new byte[][] {ints(0, 2), new byte[] {(byte) 0xff, 0}}, NONE); + assertArrayEquals(new byte[] {(byte) 0xff, 0}, (byte[]) read(binary, "String", 0)); + // An enum label is text even when the strings arrive binary. + assertEquals("a", read(textColumn("z", null, "a"), "Enum8('a' = 1)", 0)); + // With binary strings asked for, a String argument is bytes whatever the Arrow type. + Object bytes = ArrowDecoder.reader(utf8, ClickHouseType.parse("String"), true).read(0); + assertArrayEquals("héllo".getBytes(StandardCharsets.UTF_8), (byte[]) bytes); + } + + @Test + @DisplayName("sixteen bytes of fixed-size binary are a UUID, an IPv6 address or a FixedString by declaration") + void fixedSizeBinary() throws Exception { + UUID uuid = UUID.fromString("123e4567-e89b-12d3-a456-426614174000"); + byte[] uuidBytes = ByteBuffer.allocate(16).putLong(uuid.getMostSignificantBits()) + .putLong(uuid.getLeastSignificantBits()).array(); + ArrowColumn tagged = column("w:16", "arrow.uuid", 1, 0, null, new byte[][] {uuidBytes}, NONE); + assertEquals(uuid, read(tagged, "UUID", 0)); + // The extension decides on its own too. + assertEquals(uuid, ArrowDecoder.reader(tagged, null, false).read(0)); + + byte[] loopback = InetAddress.getByName("::1").getAddress(); + ArrowColumn ipv6 = column("w:16", null, 1, 0, null, new byte[][] {loopback}, NONE); + assertEquals(InetAddress.getByName("::1"), read(ipv6, "IPv6", 0)); + + ArrowColumn fixed = column("w:3", null, 1, 0, null, new byte[][] {"ab\0".getBytes(StandardCharsets.UTF_8)}, NONE); + // The padding is part of the value, as it is to ClickHouse. + assertEquals("ab\0", read(fixed, "FixedString(3)", 0)); + assertArrayEquals("ab\0".getBytes(StandardCharsets.UTF_8), + (byte[]) ArrowDecoder.reader(fixed, ClickHouseType.parse("FixedString(3)"), true).read(0)); + } + + @Test + @DisplayName("IPv4 arrives as its 32-bit number") + void ipv4() throws Exception { + ArrowColumn address = column("I", 1, null, ints(0x01020304)); + assertEquals(InetAddress.getByName("1.2.3.4"), read(address, "IPv4", 0)); + } + + @Test + @DisplayName("dates, timestamps in every unit, and decimals") + void temporalAndDecimal() { + assertEquals(LocalDate.of(2024, 1, 2), read(column("tdD", 1, null, ints(19724)), "Date", 0)); + assertEquals(LocalDate.of(1900, 1, 1), read(column("tdD", 1, null, ints(-25567)), "Date32", 0)); + + assertEquals(Instant.parse("2024-01-02T03:04:05Z"), + read(column("tss:Asia/Shanghai", 1, null, longs(1704164645L)), "DateTime('Asia/Shanghai')", 0)); + assertEquals(Instant.parse("2024-01-02T03:04:05.678Z"), + read(column("tsm:UTC", 1, null, longs(1704164645678L)), "DateTime64(3, 'UTC')", 0)); + // Before the epoch a sub-second value floors toward the past. + assertEquals(Instant.parse("1969-12-31T23:59:59.999999Z"), + read(column("tsu:UTC", 1, null, longs(-1)), "DateTime64(6, 'UTC')", 0)); + assertEquals(Instant.parse("1969-12-31T23:59:59.999999999Z"), + read(column("tsn:UTC", 1, null, longs(-1)), "DateTime64(9, 'UTC')", 0)); + + byte[] decimal128 = buffer(16).putLong(-1234).putLong(-1).array(); + assertEquals(new BigDecimal("-12.34"), read(column("d:10,2", 1, null, decimal128), "Decimal(10, 2)", 0)); + byte[] decimal256 = new byte[32]; + decimal256[0] = 1; + assertEquals(new BigDecimal("1E-20"), read(column("d:76,20,256", 1, null, decimal256), "Decimal(76, 20)", 0)); + } + + @Test + @DisplayName("arrays are Lists, tuples Object[] and maps Maps, with element types from the declaration") + void nested() { + // Array(Nullable(Int128)): the element's declaration still makes its text a number. + ArrowColumn elements = textColumn("u", bitmap(true, false, true), "1", null, "2"); + ArrowColumn list = column("+l", null, 2, 0, null, new byte[][] {ints(0, 2, 3)}, new ArrowColumn[] {elements}); + assertEquals(Arrays.asList(BigInteger.ONE, null), read(list, "Array(Nullable(Int128))", 0)); + assertEquals(Collections.singletonList(BigInteger.valueOf(2)), read(list, "Array(Nullable(Int128))", 1)); + + ArrowColumn tuple = column("+s", null, 1, 0, null, new byte[0][], + new ArrowColumn[] {column("l", 1, null, longs(7)), textColumn("u", null, "z")}); + assertArrayEquals(new Object[] {7L, "z"}, (Object[]) read(tuple, "Tuple(a Int64, b String)", 0)); + + ArrowColumn entries = column("+s", null, 2, 0, null, new byte[0][], + new ArrowColumn[] {textColumn("u", null, "k", "j"), column("l", 2, null, longs(5, 6))}); + ArrowColumn map = column("+m", null, 1, 0, null, new byte[][] {ints(0, 2)}, new ArrowColumn[] {entries}); + Map expected = new LinkedHashMap<>(); + expected.put("k", 5L); + expected.put("j", 6L); + assertEquals(expected, read(map, "Map(String, Int64)", 0)); + } + + @Test + @DisplayName("array and struct offsets are honoured") + void offsets() { + // A slice starting at slot 1 of a nullable int64 array. + ArrowColumn sliced = column("l", null, 2, 1, bitmap(true, true, false), new byte[][] {longs(9, 10, 11)}, NONE); + assertEquals(10L, read(sliced, "Int64", 0)); + assertNull(read(sliced, "Int64", 1)); + // A struct's offset applies to its children. + ArrowColumn struct = column("+s", null, 1, 1, null, new byte[0][], new ArrowColumn[] {column("l", 2, null, longs(1, 2))}); + ArrowDecoder.Reader[] readers = + ArrowDecoder.readers(struct, Collections.singletonList(ClickHouseType.parse("Int64")), false); + assertEquals(2L, readers[0].read(0)); + } + + @Test + @DisplayName("a batch must be a struct with one child per declared argument") + void batchShape() { + ArrowColumn batch = column("+s", null, 1, 0, null, new byte[0][], new ArrowColumn[] {column("l", 1, null, longs(1))}); + List two = Arrays.asList(ClickHouseType.parse("Int64"), ClickHouseType.parse("Int64")); + assertThrows(ScalarFunctionException.class, () -> ArrowDecoder.readers(batch, two, false)); + ArrowColumn noArguments = column("+s", null, 3, 0, null, new byte[0][], NONE); + assertEquals(0, ArrowDecoder.readers(noArguments, Collections.emptyList(), false).length); + } + + @Test + @DisplayName("an Arrow type with no Java value fails with a message pointing at chdb-arrow") + void unsupported() { + ArrowColumn union = column("+ud:0,1", 1, null, new byte[1], ints(0)); + ScalarFunctionException e = assertThrows(ScalarFunctionException.class, () -> read(union, "Variant(Int64, String)", 0)); + assertTrue(e.getMessage().contains("chdb-arrow"), e.getMessage()); + + for (String type : new String[] {"Time", "Time64(3)", "Variant(Int64, String)", "Array(Nullable(Time))", + "Map(String, Time)", "Tuple(a Time)"}) { + IllegalArgumentException refused = + assertThrows(IllegalArgumentException.class, () -> ArrowDecoder.checkReadable(ClickHouseType.parse(type))); + assertTrue(refused.getMessage().contains("ArrowFunctions"), refused.getMessage()); + } + ArrowDecoder.checkReadable(ClickHouseType.parse("Map(String, Array(Nullable(Decimal(10, 2))))")); + ArrowDecoder.checkReadable(ClickHouseType.parse("JSON(a Time)")); + } +} diff --git a/chdb-jdbc/src/test/java/org/chdb/internal/ArrowEncoderTest.java b/chdb-jdbc/src/test/java/org/chdb/internal/ArrowEncoderTest.java new file mode 100644 index 0000000..e9c7a87 --- /dev/null +++ b/chdb-jdbc/src/test/java/org/chdb/internal/ArrowEncoderTest.java @@ -0,0 +1,229 @@ +package org.chdb.internal; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.net.InetAddress; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * The result encoder: which Arrow type each declared return type is sent as, the buffers it + * builds, and the Java values it refuses. That chDB reads these back as the declared type is the + * integration suite's to show; the conversions it relies on were measured on v26.11.2-rc.3. + */ +class ArrowEncoderTest { + + private static ArrowColumn encode(String type, Object... values) { + return ArrowEncoder.forType(ClickHouseType.parse(type)).encode(values); + } + + private static ByteBuffer buffer(ArrowColumn column, int index) { + return ByteBuffer.wrap(column.buffers[index]).order(ByteOrder.nativeOrder()); + } + + /** The values of a utf8 or binary column, as text. */ + private static List texts(ArrowColumn column) { + ByteBuffer offsets = buffer(column, 1); + String[] out = new String[column.length]; + for (int i = 0; i < column.length; i++) { + int start = offsets.getInt(i * 4); + int end = offsets.getInt((i + 1) * 4); + out[i] = column.isNull(i) ? null : new String(column.buffers[2], start, end - start, StandardCharsets.UTF_8); + } + return Arrays.asList(out); + } + + @Test + @DisplayName("every integer type is sent as int64, from any integral Java type") + void integers() { + for (String type : new String[] {"Int8", "Int64", "UInt8", "UInt64", "Int128", "Nullable(UInt32)", "IntervalDay"}) { + ArrowColumn column = encode(type, (byte) 1, (short) 2, 3, 4L, BigInteger.valueOf(-5), null); + assertEquals("l", column.format, type); + assertEquals(6, column.length); + assertEquals(1, column.nullCount); + assertTrue(column.nullable); + ByteBuffer data = buffer(column, 1); + assertEquals(4L, data.getLong(3 * 8)); + assertEquals(-5L, data.getLong(4 * 8)); + assertTrue(column.isNull(5)); + assertFalse(column.isNull(0)); + } + } + + @Test + @DisplayName("a BigInteger beyond 64 bits sends the whole batch as decimal text, which chDB parses") + void wideIntegers() { + BigInteger big = new BigInteger("18446744073709551615"); + ArrowColumn column = encode("UInt64", 1L, big, null); + assertEquals("u", column.format); + assertEquals(Arrays.asList("1", "18446744073709551615", null), texts(column)); + } + + @Test + @DisplayName("an integer type refuses what is not an integer, naming the type and what it takes") + void integerMismatch() { + ScalarFunctionException e = assertThrows(ScalarFunctionException.class, () -> encode("Int64", 1L, "2")); + assertTrue(e.getMessage().contains("java.lang.String for a Int64 result"), e.getMessage()); + assertTrue(e.getMessage().contains("Long"), e.getMessage()); + assertThrows(ScalarFunctionException.class, () -> encode("Int32", 1.5)); + } + + @Test + @DisplayName("floats take any Number, booleans only Boolean") + void floatsAndBooleans() { + ArrowColumn floats = encode("Float32", 1, 2.5f, 3.25); + assertEquals("g", floats.format); + assertEquals(2.5, buffer(floats, 1).getDouble(8)); + assertThrows(ScalarFunctionException.class, () -> encode("Float64", "1")); + + ArrowColumn bools = encode("Bool", true, false, null, true); + assertEquals("b", bools.format); + assertTrue(ArrowColumn.bit(bools.buffers[1], 0)); + assertFalse(ArrowColumn.bit(bools.buffers[1], 1)); + assertTrue(ArrowColumn.bit(bools.buffers[1], 3)); + assertTrue(bools.isNull(2)); + assertThrows(ScalarFunctionException.class, () -> encode("Bool", 1)); + } + + @Test + @DisplayName("strings are utf8, unless a byte[] is among them, which makes the batch binary") + void strings() { + ArrowColumn text = encode("String", "héllo", "", null); + assertEquals("u", text.format); + assertEquals(Arrays.asList("héllo", "", null), texts(text)); + // A CharSequence is text too. + assertEquals("u", encode("FixedString(3)", new StringBuilder("ab")).format); + + ArrowColumn binary = encode("String", "a", new byte[] {(byte) 0xff}); + assertEquals("z", binary.format); + assertArrayEquals(new byte[] {'a', (byte) 0xff}, binary.buffers[2]); + assertNull(binary.buffers[0], "no nulls, no validity bitmap"); + assertThrows(ScalarFunctionException.class, () -> encode("String", 1)); + } + + @Test + @DisplayName("Decimal, UUID, IPv4 and IPv6 go as text, from their Java types or a String") + void text() throws Exception { + ArrowColumn decimals = encode("Decimal(10, 2)", new BigDecimal("1E+3"), 12, 0.1, "7.5"); + assertEquals("u", decimals.format); + // Plain notation: ClickHouse does not parse an exponent. + assertEquals(Arrays.asList("1000", "12", "0.1", "7.5"), texts(decimals)); + + UUID uuid = UUID.fromString("123e4567-e89b-12d3-a456-426614174000"); + assertEquals(Arrays.asList(uuid.toString(), "00000000-0000-0000-0000-000000000000"), + texts(encode("UUID", uuid, "00000000-0000-0000-0000-000000000000"))); + assertEquals(Collections.singletonList("1.2.3.4"), texts(encode("IPv4", InetAddress.getByName("1.2.3.4")))); + assertThrows(ScalarFunctionException.class, () -> encode("UUID", 5L)); + assertThrows(ScalarFunctionException.class, () -> encode("Enum8('a' = 1)", 1)); + } + + @Test + @DisplayName("a type without a mapping of its own takes a String for chDB to parse") + void otherTypes() { + assertEquals(Collections.singletonList("{\"a\":1}"), texts(encode("JSON", "{\"a\":1}"))); + assertEquals("u", encode("Time", "01:02:03").format); + ScalarFunctionException e = assertThrows(ScalarFunctionException.class, () -> encode("Variant(Int64, String)", 1L)); + assertTrue(e.getMessage().contains("chDB parses as Variant(Int64, String)"), e.getMessage()); + } + + @Test + @DisplayName("dates are date32 days; DateTime and DateTime64 are timestamps in the declared precision") + void temporal() { + ArrowColumn dates = encode("Date32", LocalDate.of(1900, 1, 1)); + assertEquals("tdD", dates.format); + assertEquals(-25567, buffer(dates, 1).getInt(0)); + assertThrows(ScalarFunctionException.class, () -> encode("Date", "2024-01-02")); + + Instant instant = Instant.parse("2024-01-02T03:04:05.678912345Z"); + ArrowColumn seconds = encode("DateTime('Asia/Shanghai')", instant); + assertEquals("tss:UTC", seconds.format); + assertEquals(1704164645L, buffer(seconds, 1).getLong(0)); + assertEquals("tsm:UTC", encode("DateTime64(3)", instant).format); + assertEquals(1704164645678L, buffer(encode("DateTime64(3)", instant), 1).getLong(0)); + assertEquals(1704164645678912L, buffer(encode("DateTime64(6)", instant), 1).getLong(0)); + assertEquals(1704164645678912345L, buffer(encode("DateTime64(9, 'UTC')", instant), 1).getLong(0)); + // Before the epoch the cut goes toward the past, as a coarser DateTime64 would. + assertEquals(-1L, buffer(encode("DateTime64(3)", Instant.parse("1969-12-31T23:59:59.9995Z")), 1).getLong(0)); + + // Any Java type that names an instant; never one that does not. + ZonedDateTime zoned = instant.atZone(ZoneId.of("Asia/Shanghai")); + OffsetDateTime offset = instant.atOffset(ZoneOffset.ofHours(-5)); + assertEquals(1704164645L, buffer(encode("DateTime", zoned), 1).getLong(0)); + assertEquals(1704164645L, buffer(encode("DateTime", offset), 1).getLong(0)); + ScalarFunctionException e = assertThrows(ScalarFunctionException.class, + () -> encode("DateTime", LocalDateTime.of(2024, 1, 2, 3, 4))); + assertTrue(e.getMessage().contains("Instant"), e.getMessage()); + assertThrows(ScalarFunctionException.class, () -> encode("DateTime64(9)", Instant.parse("2300-01-01T00:00:00Z"))); + } + + @Test + @DisplayName("arrays from Lists and arrays, primitive ones included") + void arrays() { + ArrowColumn column = encode("Array(Int64)", Arrays.asList(1L, 2L), new long[] {3}, null, new Integer[0]); + assertEquals("+l", column.format); + ByteBuffer offsets = buffer(column, 1); + assertArrayEquals(new int[] {0, 2, 3, 3, 3}, + new int[] {offsets.getInt(0), offsets.getInt(4), offsets.getInt(8), offsets.getInt(12), offsets.getInt(16)}); + assertTrue(column.isNull(2)); + ArrowColumn elements = column.children[0]; + assertEquals("l", elements.format); + assertEquals(3, elements.length); + assertEquals(3L, buffer(elements, 1).getLong(16)); + + // Elements are checked against the element type. + assertThrows(ScalarFunctionException.class, () -> encode("Array(Int64)", Collections.singletonList("x"))); + assertThrows(ScalarFunctionException.class, () -> encode("Array(Int64)", 5L)); + } + + @Test + @DisplayName("maps have non-nullable keys and refuse a null one; tuples need every element") + void mapsAndTuples() { + Map map = new LinkedHashMap<>(); + map.put("k", 5L); + map.put("j", null); + ArrowColumn column = encode("Map(String, Nullable(Int64))", map); + assertEquals("+m", column.format); + ArrowColumn entries = column.children[0]; + assertEquals("+s", entries.format); + assertFalse(entries.nullable); + assertFalse(entries.children[0].nullable, "Arrow requires map keys to be declared non-nullable"); + assertEquals(Arrays.asList("k", "j"), texts(entries.children[0])); + assertTrue(entries.children[1].isNull(1)); + + Map nullKey = new LinkedHashMap<>(); + nullKey.put(null, 1L); + assertThrows(ScalarFunctionException.class, () -> encode("Map(String, Int64)", nullKey)); + + ArrowColumn tuples = encode("Tuple(a Int64, b String)", new Object[] {1L, "x"}, Arrays.asList(2L, "y"), null); + assertEquals("+s", tuples.format); + assertEquals(1, tuples.buffers.length, "a struct has only its validity bitmap"); + assertTrue(tuples.isNull(2)); + assertEquals(Arrays.asList("x", "y", null), texts(tuples.children[1])); + ScalarFunctionException e = assertThrows(ScalarFunctionException.class, + () -> encode("Tuple(a Int64, b String)", (Object) new Object[] {1L})); + assertTrue(e.getMessage().contains("1 elements"), e.getMessage()); + } +} diff --git a/chdb-jdbc/src/test/java/org/chdb/internal/ScalarFunctionCallbackTest.java b/chdb-jdbc/src/test/java/org/chdb/internal/ScalarFunctionCallbackTest.java new file mode 100644 index 0000000..11f77a6 --- /dev/null +++ b/chdb-jdbc/src/test/java/org/chdb/internal/ScalarFunctionCallbackTest.java @@ -0,0 +1,116 @@ +package org.chdb.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What the shim relies on from the Java half of a callback: that {@link + * ScalarFunctionCallback#invoke} never throws, reports a failure as its message, and marks the + * thread while the function runs. Exercised without a shim, since invoke is plain Java. + */ +class ScalarFunctionCallbackTest { + + /** A callback whose batch does whatever the test says. */ + private static final class TestCallback extends ScalarFunctionCallback { + private final ThrowingRunnable batch; + final AtomicInteger releases = new AtomicInteger(); + + TestCallback(ThrowingRunnable batch) { + this.batch = batch; + } + + @Override + protected void apply(long argumentSchema, long arguments, long resultSchema, long result) throws Exception { + batch.run(); + } + + @Override + protected void release() { + releases.incrementAndGet(); + throw new IllegalStateException("release fails, and must not escape"); + } + } + + @FunctionalInterface + private interface ThrowingRunnable { + void run() throws Exception; + } + + private static String failure(ScalarFunctionCallback callback) { + byte[] message = callback.invoke(1, 2, 3, 4); + return message == null ? null : new String(message, StandardCharsets.UTF_8); + } + + @Test + @DisplayName("a batch that succeeds reports nothing, and the thread is marked only while it runs") + void success() { + AtomicBoolean inside = new AtomicBoolean(); + TestCallback callback = new TestCallback(() -> inside.set(ScalarFunctionCallback.isRunningOnThisThread())); + assertFalse(ScalarFunctionCallback.isRunningOnThisThread()); + assertNull(failure(callback)); + assertTrue(inside.get()); + assertFalse(ScalarFunctionCallback.isRunningOnThisThread()); + } + + @Test + @DisplayName("an exception becomes its class and message, with its causes") + void exceptions() { + assertEquals("java.lang.IllegalArgumentException: zero is not allowed", + failure(new TestCallback(() -> { + throw new IllegalArgumentException("zero is not allowed"); + }))); + // Without its class a NullPointerException would report nothing at all. + assertEquals("java.lang.NullPointerException", failure(new TestCallback(() -> { + throw new NullPointerException(); + }))); + assertEquals("java.lang.RuntimeException: outer; caused by java.io.IOException: inner", + failure(new TestCallback(() -> { + throw new RuntimeException("outer", new java.io.IOException("inner")); + }))); + // The driver's own reports are already sentences. + assertEquals("the function returned 2 values for a batch of 1 rows", failure(new TestCallback(() -> { + throw new ScalarFunctionException("the function returned 2 values for a batch of 1 rows"); + }))); + assertFalse(ScalarFunctionCallback.isRunningOnThisThread()); + } + + @Test + @DisplayName("an Error is reported too, rather than escaping into the engine thread") + void errors() { + String message = failure(new TestCallback(() -> { + throw new StackOverflowError("deep"); + })); + assertEquals("java.lang.StackOverflowError: deep", message); + } + + @Test + @DisplayName("a cause chain that loops is cut off") + void causeCycle() { + RuntimeException first = new RuntimeException("first"); + RuntimeException second = new RuntimeException("second", first); + first.initCause(second); + String message = failure(new TestCallback(() -> { + throw first; + })); + assertTrue(message.startsWith("java.lang.RuntimeException: first; caused by java.lang.RuntimeException: second"), + message); + } + + @Test + @DisplayName("abandoning a callback releases it once and swallows what release throws") + void release() { + // destroyed() takes the same path, and also uncounts a live registration, which only a + // real one has; the integration suite checks that the count returns to zero. + TestCallback abandoned = new TestCallback(() -> { }); + abandoned.abandon(); + assertEquals(1, abandoned.releases.get()); + } +} diff --git a/chdb-jdbc/src/test/java/org/chdb/jdbc/ChdbScalarFunctionBuilderTest.java b/chdb-jdbc/src/test/java/org/chdb/jdbc/ChdbScalarFunctionBuilderTest.java new file mode 100644 index 0000000..15c3250 --- /dev/null +++ b/chdb-jdbc/src/test/java/org/chdb/jdbc/ChdbScalarFunctionBuilderTest.java @@ -0,0 +1,83 @@ +package org.chdb.jdbc; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.lang.reflect.Proxy; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.SQLFeatureNotSupportedException; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What the builder refuses before it reaches a connection, and so before any engine is loaded: + * a declaration missing a part, a function whose arity contradicts the parameters, a parameter + * type no Java value is read as, and a connection that is not chDB's. + */ +class ChdbScalarFunctionBuilderTest { + + /** A Connection that is not a chDB one, failing anything but unwrap. */ + private static final Connection FOREIGN = (Connection) Proxy.newProxyInstance( + ChdbScalarFunctionBuilderTest.class.getClassLoader(), + new Class[] {Connection.class}, + (proxy, method, args) -> { + if (method.getName().equals("unwrap")) { + throw new SQLException("not a wrapper"); + } + throw new AssertionError("unexpected call to " + method.getName()); + }); + + private static ChdbScalarFunctionBuilder complete() { + return ChdbFunctions.scalarFunction().withName("f").withParameter("Int64").withReturnType("Int64") + .withFunction((Long x) -> x); + } + + @Test + @DisplayName("a name, a return type and a function are required") + void incomplete() { + assertThrows(IllegalStateException.class, + () -> ChdbFunctions.scalarFunction().withParameter("Int64").withReturnType("Int64") + .withFunction((Long x) -> x).register(FOREIGN)); + assertThrows(IllegalStateException.class, + () -> ChdbFunctions.scalarFunction().withName("f").withFunction(() -> 1).register(FOREIGN)); + assertThrows(IllegalStateException.class, + () -> ChdbFunctions.scalarFunction().withName("f").withReturnType("Int64").register(FOREIGN)); + assertThrows(IllegalArgumentException.class, () -> ChdbFunctions.scalarFunction().withName(" ")); + assertThrows(IllegalArgumentException.class, () -> ChdbFunctions.scalarFunction().withParameter("")); + assertThrows(NullPointerException.class, () -> ChdbFunctions.scalarFunction().withReturnType(null)); + } + + @Test + @DisplayName("a Supplier, Function or BiFunction must match the number of parameters") + void arity() { + IllegalStateException e = assertThrows(IllegalStateException.class, + () -> ChdbFunctions.scalarFunction().withName("f").withParameters("Int64", "Int64") + .withReturnType("Int64").withFunction((Long x) -> x).register(FOREIGN)); + assertTrue(e.getMessage().contains("Function takes 1 arguments"), e.getMessage()); + assertThrows(IllegalStateException.class, + () -> ChdbFunctions.scalarFunction().withName("f").withParameter("Int64").withReturnType("Int64") + .withFunction(() -> 1L).register(FOREIGN)); + assertThrows(IllegalStateException.class, + () -> ChdbFunctions.scalarFunction().withName("f").withReturnType("Int64") + .withFunction((Long x, Long y) -> x + y).register(FOREIGN)); + } + + @Test + @DisplayName("a parameter type with no Java value is refused at registration, not at the first query") + void unreadableParameter() { + SQLFeatureNotSupportedException e = assertThrows(SQLFeatureNotSupportedException.class, + () -> ChdbFunctions.scalarFunction().withName("f").withParameter("Time").withReturnType("String") + .withRowFunction(args -> "x").register(FOREIGN)); + assertTrue(e.getMessage().contains("Time"), e.getMessage()); + assertEquals("0A000", e.getSQLState()); + } + + @Test + @DisplayName("registration needs a chDB connection, or one that wraps it") + void foreignConnection() { + SQLException e = assertThrows(SQLException.class, () -> complete().register(FOREIGN)); + assertTrue(e.getMessage().contains("chDB connection"), e.getMessage()); + } +} diff --git a/chdb-jni/CMakeLists.txt b/chdb-jni/CMakeLists.txt index 5ff3280..af1d98a 100644 --- a/chdb-jni/CMakeLists.txt +++ b/chdb-jni/CMakeLists.txt @@ -125,6 +125,7 @@ endif() add_library(chdb_java_jni SHARED src/chdb_jni.cpp + src/chdb_jni_functions.cpp src/chdb_jni_signals.cpp src/chdb_optional_api.cpp) @@ -170,12 +171,17 @@ target_compile_options(chdb_java_jni PRIVATE # shim cannot accidentally interpose on a libchdb symbol. -fvisibility=hidden) +# pthread keys and thread names, for the engine threads scalar functions attach to the JVM, and +# the harness's own threads. +find_package(Threads REQUIRED) + if(CHDB_JNI_BUILD_TESTS) # Links only the translation units that need neither JNI nor the engine: the Arrow layout - # parser, the signal guard, and the header-only handle registry. Not linking libchdb is the - # entire point -- its allocator is what makes a preloaded ASan crash. + # and copies scalar functions use, the signal guard, and the header-only handle registry. Not + # linking libchdb is the entire point -- its allocator is what makes a preloaded ASan crash. add_executable(chdb_jni_test test/chdb_jni_test.cpp + src/chdb_jni_functions.cpp src/chdb_jni_signals.cpp) target_include_directories(chdb_jni_test PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src") target_compile_options(chdb_jni_test PRIVATE -Wall -Wextra -Wpedantic -g) @@ -187,7 +193,6 @@ if(CHDB_JNI_BUILD_TESTS) target_compile_options(chdb_jni_test PRIVATE -fno-sanitize-recover=undefined) endif() endif() - find_package(Threads REQUIRED) target_link_libraries(chdb_jni_test PRIVATE Threads::Threads) endif() @@ -224,7 +229,11 @@ set_target_properties(chdb_java_jni PROPERTIES # dlsym. glibc 2.34 merged libdl into libc, so a build on Ubuntu 22.04 links without it by # accident; on glibc 2.28 -- the floor this package targets -- the link fails with an undefined # reference. Found by building in a manylinux_2_28 container, which is why that build exists. -target_link_libraries(chdb_java_jni PRIVATE "${CHDB_LIBRARY}" ${CMAKE_DL_LIBS}) +# +# Threads::Threads is the same story for libpthread, which chdb_jni.cpp needs for the pthread +# key that detaches an attached engine thread as it exits: merged into libc in 2.34, separate on +# the 2.28 floor. +target_link_libraries(chdb_java_jni PRIVATE "${CHDB_LIBRARY}" ${CMAKE_DL_LIBS} Threads::Threads) if(APPLE) # libchdb's install_name is @rpath/libchdb.so, so the shim needs an LC_RPATH of diff --git a/chdb-jni/src/arrow_c_abi.h b/chdb-jni/src/arrow_c_abi.h new file mode 100644 index 0000000..056be90 --- /dev/null +++ b/chdb-jni/src/arrow_c_abi.h @@ -0,0 +1,61 @@ +// Arrow C Data Interface struct definitions. +// +// Transcribed from the Apache Arrow specification (arrow/c/abi.h, Apache-2.0): the two structs +// of the C Data Interface and its flags, which are the whole ABI a scalar function's callback +// speaks -- chdb.h passes them as the opaque chdb_arrow_schema and chdb_arrow_array handles. +// Vendored on purpose, as the shim's first Arrow path did: it keeps the shim free of any Arrow +// C++ or Arrow Java dependency (work plan section 3.2). +// +// Do not extend this file with helpers. It is a transcription of a frozen ABI. + +#pragma once + +#include + +extern "C" { + +#ifndef ARROW_C_DATA_INTERFACE +#define ARROW_C_DATA_INTERFACE + +#define ARROW_FLAG_DICTIONARY_ORDERED 1 +#define ARROW_FLAG_NULLABLE 2 +#define ARROW_FLAG_MAP_KEYS_SORTED 4 + +struct ArrowSchema +{ + // Array type description + const char * format; + const char * name; + const char * metadata; + int64_t flags; + int64_t n_children; + struct ArrowSchema ** children; + struct ArrowSchema * dictionary; + + // Release callback + void (*release)(struct ArrowSchema *); + // Opaque producer-specific data + void * private_data; +}; + +struct ArrowArray +{ + // Array data description + int64_t length; + int64_t null_count; + int64_t offset; + int64_t n_buffers; + int64_t n_children; + const void ** buffers; + struct ArrowArray ** children; + struct ArrowArray * dictionary; + + // Release callback + void (*release)(struct ArrowArray *); + // Opaque producer-specific data + void * private_data; +}; + +#endif // ARROW_C_DATA_INTERFACE + +} // extern "C" diff --git a/chdb-jni/src/chdb_jni.cpp b/chdb-jni/src/chdb_jni.cpp index 4f32d39..d245389 100644 --- a/chdb-jni/src/chdb_jni.cpp +++ b/chdb-jni/src/chdb_jni.cpp @@ -6,18 +6,23 @@ // nothing unwinds across the JNI boundary // - keep the host JVM's signal dispositions intact (chdb_jni_signals.h) // - hand Java the bytes of one result chunk, copied out before the engine's buffer goes +// - run Java scalar functions on the engine's threads, and keep Java exceptions out of them // // It deliberately holds no query logic. Deciding what a statement is, mapping types and // enforcing JDBC semantics all happen in Java, where they are testable without a build. #include +#include +#include #include #include #include #include #include +#include "arrow_c_abi.h" +#include "chdb_jni_functions.h" #include "chdb_jni_handles.h" #include "chdb_jni_signals.h" #include "chdb_optional_api.h" @@ -66,6 +71,25 @@ void throwOutOfMemory(JNIEnv * env, const char * what) env->DeleteLocalRef(clazz); } +// ---------------------------------------------------------------------- inside a scalar function + +// Whether this thread is running a scalar function's Java code. chdb.h forbids calling into chDB +// from the callback, and the call would deadlock rather than fail: chDB can run the callback on the +// very thread that issued the query, which holds that connection's mutex for as long as the query +// runs, and on any other thread the call would wait for a query that is waiting for the callback. +// So every entry point that reaches the engine refuses first. +thread_local bool t_inside_scalar_function = false; + +bool refuseInsideScalarFunction(JNIEnv * env) +{ + if (!t_inside_scalar_function) + return false; + throwNative(env, "chDB cannot be called from inside a scalar function: the function runs in the middle of" + " a query, and the call would wait for that query to finish. Work out what the function" + " needs before the query, or pass it in as an argument."); + return true; +} + // ---------------------------------------------------------------------- handles struct ConnHandle : HandleBase @@ -341,6 +365,8 @@ Java_org_chdb_internal_ChdbNative_connect(JNIEnv * env, jclass, jobjectArray arg { try { + if (refuseInsideScalarFunction(env)) + return 0; std::vector args; if (!toBytesVector(env, argv, args)) return 0; @@ -424,6 +450,8 @@ Java_org_chdb_internal_ChdbNative_closeConnection(JNIEnv * env, jclass, jlong id { try { + if (refuseInsideScalarFunction(env)) + return; // Idempotent by construction: remove() returns null for an id that is already gone, // so a second close does nothing rather than double-freeing. auto base = HandleRegistry::instance().remove(id, kKindConnection); @@ -452,6 +480,8 @@ Java_org_chdb_internal_ChdbNative_queryArrowMaterialized( { try { + if (refuseInsideScalarFunction(env)) + return; if (stream_address == 0) { throwNative(env, "Arrow stream address is null"); @@ -510,6 +540,8 @@ Java_org_chdb_internal_ChdbNative_registerArrowStream( { try { + if (refuseInsideScalarFunction(env)) + return; if (stream_address == 0) { throwNative(env, "Arrow stream address is null"); @@ -556,6 +588,8 @@ Java_org_chdb_internal_ChdbNative_unregisterArrowStream( { try { + if (refuseInsideScalarFunction(env)) + return; auto connection = requireConnection(env, connection_id); if (!connection) return; @@ -622,6 +656,8 @@ static jlong arrowStreamOpenImpl(JNIEnv * env, jlong connection_id, { try { + if (refuseInsideScalarFunction(env)) + return 0; auto connection = requireConnection(env, connection_id); if (!connection) return 0; @@ -709,6 +745,8 @@ Java_org_chdb_internal_ChdbNative_arrowStreamFetch( { try { + if (refuseInsideScalarFunction(env)) + return; if (out_address == 0) { throwNative(env, "Arrow output stream address is null"); @@ -753,6 +791,8 @@ Java_org_chdb_internal_ChdbNative_arrowStreamCancel( { try { + if (refuseInsideScalarFunction(env)) + return; auto stream = requireArrowStream(env, stream_id); if (!stream) return; @@ -780,6 +820,8 @@ Java_org_chdb_internal_ChdbNative_arrowStreamClose(JNIEnv * env, jclass, jlong s { try { + if (refuseInsideScalarFunction(env)) + return; auto base = HandleRegistry::instance().remove(stream_id, kKindArrowStream); if (!base) return; @@ -798,6 +840,8 @@ static jlong insertArrowStreamImpl(JNIEnv * env, jlong connection_id, { try { + if (refuseInsideScalarFunction(env)) + return 0; if (option_flags != 0 && option_flags != 1) { throwNative(env, "Unknown Arrow insert options"); @@ -920,6 +964,8 @@ Java_org_chdb_internal_ChdbNative_query( { try { + if (refuseInsideScalarFunction(env)) + return 0; auto connection = requireConnection(env, connection_id); if (!connection) return 0; @@ -1096,6 +1142,8 @@ Java_org_chdb_internal_ChdbNative_classifyQuery(JNIEnv * env, jclass, jlong conn { try { + if (refuseInsideScalarFunction(env)) + return nullptr; // Optional symbol: present from v26.7.2-rc.2, so on the pinned v26.11.2-rc.3 baseline, // absent on anything older. Null tells the Java side to use its own statement-shape // heuristic rather than failing the query. @@ -1218,6 +1266,8 @@ Java_org_chdb_internal_ChdbNative_rowBinaryOpen( { try { + if (refuseInsideScalarFunction(env)) + return 0; auto connection = requireConnection(env, connection_id); if (!connection) return 0; @@ -1293,6 +1343,8 @@ Java_org_chdb_internal_ChdbNative_rowBinaryFetch( { try { + if (refuseInsideScalarFunction(env)) + return nullptr; auto handle = requireRowBinary(env, id); if (!handle) return nullptr; @@ -1359,6 +1411,8 @@ Java_org_chdb_internal_ChdbNative_rowBinaryCancel( { try { + if (refuseInsideScalarFunction(env)) + return; auto handle = requireRowBinary(env, id); if (!handle) return; @@ -1386,6 +1440,8 @@ Java_org_chdb_internal_ChdbNative_rowBinaryClose(JNIEnv * env, jclass, jlong id) { try { + if (refuseInsideScalarFunction(env)) + return; auto base = HandleRegistry::instance().remove(id, kKindRowBinary); if (!base) return; @@ -1399,6 +1455,675 @@ Java_org_chdb_internal_ChdbNative_rowBinaryClose(JNIEnv * env, jclass, jlong id) } } +// ====================================================================== scalar functions +// +// chDB calls a registered function's callback once per block of rows, on its own threads and +// several at once. The callback attaches its thread to the JVM and calls +// ScalarFunctionCallback.invoke with the addresses of the batch's Arrow C Data structs. Java reads +// them through copyArrowArray -- chdb-jdbc's row-at-a-time functions -- or imports them with Arrow +// Java, for chdb-arrow's, and fills the result the same two ways. invoke catches every Throwable +// and returns its message, so nothing Java throws reaches chDB's frames; the message goes into +// chDB's error buffer and becomes the query's error. + +namespace +{ + +// The Java side of one registration, owned by chDB from a successful +// chdb_create_scalar_function until it calls destroyScalarFunction. +struct ScalarFunctionState +{ + JavaVM * vm = nullptr; + // Global reference to the org.chdb.internal.ScalarFunctionCallback. + jobject callback = nullptr; + // byte[] invoke(long, long, long, long) and void destroyed(), looked up once, on the Java + // thread that registered the function: an engine thread has no Java frame, so FindClass there + // would search the system class loader, which need not be the one that loaded the driver. + jmethodID invoke = nullptr; + jmethodID destroyed = nullptr; +}; + +// Marks this thread as running a scalar function for the length of an upcall. +class InsideScalarFunction +{ +public: + InsideScalarFunction() : outer_(t_inside_scalar_function) { t_inside_scalar_function = true; } + ~InsideScalarFunction() { t_inside_scalar_function = outer_; } + + InsideScalarFunction(const InsideScalarFunction &) = delete; + InsideScalarFunction & operator=(const InsideScalarFunction &) = delete; + +private: + const bool outer_; +}; + +// Sets aside an exception pending on this thread for the length of an upcall, and throws it again +// afterwards. One can be pending when chDB calls back on a thread that is itself inside a JNI call: +// a destroy run by the cleanup of a statement the shim has already queued an error for. Calling +// into Java with one pending is undefined. +class PendingException +{ +public: + explicit PendingException(JNIEnv * env) : env_(env), pending_(env->ExceptionOccurred()) + { + if (pending_ != nullptr) + env_->ExceptionClear(); + } + + ~PendingException() + { + if (pending_ == nullptr) + return; + env_->Throw(pending_); + env_->DeleteLocalRef(pending_); + } + + PendingException(const PendingException &) = delete; + PendingException & operator=(const PendingException &) = delete; + +private: + JNIEnv * const env_; + const jthrowable pending_; +}; + +} // namespace + +extern "C" { + +// Detaches a thread the shim attached, as the thread exits. An engine thread runs many batches, +// so it is attached once and stays attached rather than paying for an attach and a detach every +// time; detaching at exit is what stops the JVM keeping a java.lang.Thread for every engine thread +// that has come and gone. +static void detachAtThreadExit(void * vm) +{ + static_cast(vm)->DetachCurrentThread(); +} + +} // extern "C" + +namespace +{ + +pthread_key_t attachedThreads() +{ + static const pthread_key_t key = [] + { + pthread_key_t created; + pthread_key_create(&created, detachAtThreadExit); + return created; + }(); + return key; +} + +// The calling thread's JNIEnv, attaching it to the JVM first if it is an engine thread the JVM has +// not seen. As a daemon, so that an engine thread never keeps the JVM from exiting. Null if the JVM +// refuses. +JNIEnv * attachCurrentThread(JavaVM * vm) +{ + JNIEnv * env = nullptr; + const jint status = vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_8); + if (status == JNI_OK) + return env; + if (status != JNI_EDETACHED) + return nullptr; + // Named after the engine thread, so that a thread dump says which of chDB's pools it is from. + char name[64] = {0}; + if (pthread_getname_np(pthread_self(), name, sizeof(name)) != 0 || name[0] == '\0') + std::strcpy(name, "chdb-engine"); + JavaVMAttachArgs args{JNI_VERSION_1_8, name, nullptr}; + if (vm->AttachCurrentThreadAsDaemon(reinterpret_cast(&env), &args) != JNI_OK) + return nullptr; + pthread_setspecific(attachedThreads(), vm); + return env; +} + +jlong addressOf(const void * pointer) +{ + return static_cast(reinterpret_cast(pointer)); +} + +} // namespace + +extern "C" { + +// chdb_scalar_function_callback. Lets nothing escape: a C++ exception or a Java one would unwind +// through chDB's frames, so both end up in the error buffer instead. +static int callScalarFunction( + void * user_data, + void * argument_schema, + void * arguments, + void * result_schema, + void * result, + char * error, + size_t error_size) +{ + const auto * state = static_cast(user_data); + try + { + JNIEnv * env = attachCurrentThread(state->vm); + if (env == nullptr) + { + writeErrorMessage("the JVM refused to attach this engine thread, so the Java scalar function cannot run on it", + error, error_size); + return 1; + } + PendingException pending(env); + // An attached engine thread never returns to Java, so its local references would pile up + // across batches without a frame of their own. + if (env->PushLocalFrame(4) != 0) + { + env->ExceptionClear(); + writeErrorMessage("out of memory calling the Java scalar function", error, error_size); + return 1; + } + jobject message = nullptr; + { + InsideScalarFunction inside; + message = env->CallObjectMethod( + state->callback, state->invoke, addressOf(argument_schema), addressOf(arguments), + addressOf(result_schema), addressOf(result)); + } + int status = 0; + if (env->ExceptionCheck()) + { + // invoke catches every Throwable, so this is one thrown while it was turning a failure + // into a message -- an OutOfMemoryError, say. There is no message left to report. + env->ExceptionClear(); + writeErrorMessage("the Java scalar function failed, and so did reporting why", error, error_size); + status = 1; + } + else if (message != nullptr) + { + auto bytes = static_cast(message); + std::string text(static_cast(env->GetArrayLength(bytes)), '\0'); + if (!text.empty()) + env->GetByteArrayRegion(bytes, 0, static_cast(text.size()), reinterpret_cast(&text[0])); + writeErrorMessage(text, error, error_size); + status = 1; + } + env->PopLocalFrame(nullptr); + return status; + } + catch (const std::exception & e) + { + writeErrorMessage(std::string("the Java scalar function could not be called: ") + e.what(), error, error_size); + return 1; + } + catch (...) + { + writeErrorMessage("the Java scalar function could not be called", error, error_size); + return 1; + } +} + +// destroy of chdb_scalar_function_options. chDB calls it once, after the function is dropped and +// nothing uses it, on whichever thread let go of it last -- possibly inside another chDB call, +// which is why ScalarFunctionCallback.destroyed must not call chDB either. +static void destroyScalarFunction(void * user_data) +{ + auto * state = static_cast(user_data); + if (JNIEnv * env = attachCurrentThread(state->vm)) + { + PendingException pending(env); + env->CallVoidMethod(state->callback, state->destroyed); + // destroyed() catches whatever releasing the function's resources throws, so there is + // nothing here to report, and nobody to report it to. + env->ExceptionClear(); + env->DeleteGlobalRef(state->callback); + } + // Without a JNIEnv the global reference cannot be deleted. It stays: a leak of one object, + // where anything else would be a crash. + delete state; +} + +} // extern "C" + +namespace +{ + +// org.chdb.internal.ArrowColumn: the class, its constructor and its fields. +struct ArrowColumnClass +{ + jclass column = nullptr; // global reference + jclass byte_array = nullptr; // global reference to byte[] + jmethodID constructor = nullptr; + jfieldID format = nullptr; + jfieldID nullable = nullptr; + jfieldID length = nullptr; + jfieldID offset = nullptr; + jfieldID null_count = nullptr; + jfieldID buffers = nullptr; + jfieldID children = nullptr; +}; + +// Looked up once and kept for the life of the process, like the handle registry: callbacks can +// still be running on engine threads while the JVM exits. Null, with the JNI error pending, when a +// lookup fails -- which means the shim and the driver JAR come from different releases. +const ArrowColumnClass * arrowColumnClass(JNIEnv * env) +{ + static std::atomic cached{nullptr}; + // A leaf: held only around the lookups below, never with another of the shim's locks. + static std::mutex mutex; + + if (const ArrowColumnClass * known = cached.load(std::memory_order_acquire)) + return known; + std::lock_guard lock(mutex); + if (const ArrowColumnClass * known = cached.load(std::memory_order_relaxed)) + return known; + + jclass column = env->FindClass("org/chdb/internal/ArrowColumn"); + if (column == nullptr) + return nullptr; + jclass byte_array = env->FindClass("[B"); + if (byte_array == nullptr) + return nullptr; + auto found = std::make_unique(); + found->constructor = env->GetMethodID( + column, "", "(Ljava/lang/String;Ljava/lang/String;ZIII[[B[Lorg/chdb/internal/ArrowColumn;)V"); + found->format = env->GetFieldID(column, "format", "Ljava/lang/String;"); + found->nullable = env->GetFieldID(column, "nullable", "Z"); + found->length = env->GetFieldID(column, "length", "I"); + found->offset = env->GetFieldID(column, "offset", "I"); + found->null_count = env->GetFieldID(column, "nullCount", "I"); + found->buffers = env->GetFieldID(column, "buffers", "[[B"); + found->children = env->GetFieldID(column, "children", "[Lorg/chdb/internal/ArrowColumn;"); + if (env->ExceptionCheck()) + return nullptr; + found->column = static_cast(env->NewGlobalRef(column)); + found->byte_array = static_cast(env->NewGlobalRef(byte_array)); + env->DeleteLocalRef(column); + env->DeleteLocalRef(byte_array); + if (found->column == nullptr || found->byte_array == nullptr) + { + throwOutOfMemory(env, "out of memory looking up org.chdb.internal.ArrowColumn"); + return nullptr; + } + const ArrowColumnClass * published = found.release(); + cached.store(published, std::memory_order_release); + return published; +} + +// How deep copies follow children. An argument type is a few levels deep; this only keeps a +// pathological one from exhausting an engine thread's stack. +constexpr int kMaxArrowDepth = 32; + +// Copies one array and its children onto the Java heap as an ArrowColumn. Null with an exception +// pending on failure. +jobject copyArrowColumn( + JNIEnv * env, const ArrowColumnClass & classes, const ArrowSchema & schema, const ArrowArray & array, int depth) +{ + std::vector extents; + std::string error; + if (depth > kMaxArrowDepth) + error = "the Arrow array is nested deeper than " + std::to_string(kMaxArrowDepth) + " levels"; + else if (!arrowBufferExtents(schema, array, extents, error)) + { + } + else if (schema.n_children != array.n_children + || (schema.n_children > 0 && (schema.children == nullptr || array.children == nullptr))) + error = "the Arrow schema and array disagree about their children"; + else if (array.length > INT32_MAX || array.offset > INT32_MAX - array.length) + error = "an Arrow array of " + std::to_string(array.length) + " rows is too large to copy into Java"; + if (!error.empty()) + { + throwNative(env, error); + return nullptr; + } + + jobjectArray buffers = env->NewObjectArray(static_cast(extents.size()), classes.byte_array, nullptr); + if (buffers == nullptr) + return nullptr; + for (size_t i = 0; i < extents.size(); ++i) + { + if (extents[i].data == nullptr) + continue; // absent: no nulls, or zero bytes + if (extents[i].size > static_cast(INT32_MAX)) + { + throwNative(env, "an Arrow buffer of " + std::to_string(extents[i].size) + " bytes is too large to copy into Java"); + return nullptr; + } + const auto size = static_cast(extents[i].size); + jbyteArray bytes = env->NewByteArray(size); + if (bytes == nullptr) + return nullptr; + env->SetByteArrayRegion(bytes, 0, size, static_cast(extents[i].data)); + env->SetObjectArrayElement(buffers, static_cast(i), bytes); + env->DeleteLocalRef(bytes); + } + + jobjectArray children = env->NewObjectArray(static_cast(schema.n_children), classes.column, nullptr); + if (children == nullptr) + return nullptr; + for (int64_t i = 0; i < schema.n_children; ++i) + { + jobject child = copyArrowColumn(env, classes, *schema.children[i], *array.children[i], depth + 1); + if (child == nullptr) + return nullptr; + env->SetObjectArrayElement(children, static_cast(i), child); + env->DeleteLocalRef(child); + } + + jstring format = env->NewStringUTF(schema.format); + if (format == nullptr) + return nullptr; + const std::string extension_name = arrowExtensionName(schema.metadata); + jstring extension = nullptr; + if (!extension_name.empty()) + { + extension = env->NewStringUTF(extension_name.c_str()); + if (extension == nullptr) + return nullptr; + } + jobject column = env->NewObject( + classes.column, classes.constructor, format, extension, + static_cast((schema.flags & ARROW_FLAG_NULLABLE) != 0), static_cast(array.length), + static_cast(array.offset), static_cast(array.null_count), buffers, children); + env->DeleteLocalRef(format); + if (extension != nullptr) + env->DeleteLocalRef(extension); + env->DeleteLocalRef(buffers); + env->DeleteLocalRef(children); + return column; +} + +// Reads an ArrowColumn the Java side built into an ArrowOwnedArray, copying its buffers. False +// with an exception pending on failure. +bool readArrowColumn(JNIEnv * env, const ArrowColumnClass & classes, jobject column, ArrowOwnedArray & out, int depth) +{ + if (column == nullptr || depth > kMaxArrowDepth) + { + throwNative(env, column == nullptr ? "an Arrow result column is null" : "an Arrow result is nested too deep"); + return false; + } + auto format = static_cast(env->GetObjectField(column, classes.format)); + if (format == nullptr) + { + throwNative(env, "an Arrow result column has no format"); + return false; + } + const char * chars = env->GetStringUTFChars(format, nullptr); + if (chars == nullptr) + return false; + out.format = chars; + env->ReleaseStringUTFChars(format, chars); + env->DeleteLocalRef(format); + out.nullable = env->GetBooleanField(column, classes.nullable) == JNI_TRUE; + out.length = env->GetIntField(column, classes.length); + out.offset = env->GetIntField(column, classes.offset); + out.null_count = env->GetIntField(column, classes.null_count); + + auto buffers = static_cast(env->GetObjectField(column, classes.buffers)); + const jsize buffer_count = buffers == nullptr ? 0 : env->GetArrayLength(buffers); + out.buffers.resize(static_cast(buffer_count)); + for (jsize i = 0; i < buffer_count; ++i) + { + auto bytes = static_cast(env->GetObjectArrayElement(buffers, i)); + if (bytes == nullptr) + continue; // absent + const jsize size = env->GetArrayLength(bytes); + ArrowOwnedArray::Buffer & buffer = out.buffers[static_cast(i)]; + buffer.present = true; + buffer.bytes.resize(static_cast(size)); + if (size > 0) + env->GetByteArrayRegion(bytes, 0, size, reinterpret_cast(buffer.bytes.data())); + env->DeleteLocalRef(bytes); + } + if (buffers != nullptr) + env->DeleteLocalRef(buffers); + + auto children = static_cast(env->GetObjectField(column, classes.children)); + const jsize child_count = children == nullptr ? 0 : env->GetArrayLength(children); + out.children.resize(static_cast(child_count)); + for (jsize i = 0; i < child_count; ++i) + { + jobject child = env->GetObjectArrayElement(children, i); + const bool read = readArrowColumn(env, classes, child, out.children[static_cast(i)], depth + 1); + if (child != nullptr) + env->DeleteLocalRef(child); + if (!read) + return false; + } + if (children != nullptr) + env->DeleteLocalRef(children); + return !env->ExceptionCheck(); +} + +bool hasNul(const std::string & text) +{ + return text.find('\0') != std::string::npos; +} + +} // namespace + +extern "C" JNIEXPORT jboolean JNICALL +Java_org_chdb_internal_ChdbNative_scalarFunctionsAvailable(JNIEnv *, jclass) +{ + const OptionalApi & api = optionalApi(); + return api.create_scalar_function != nullptr && api.drop_scalar_function != nullptr ? JNI_TRUE : JNI_FALSE; +} + +extern "C" JNIEXPORT void JNICALL +Java_org_chdb_internal_ChdbNative_createScalarFunction( + JNIEnv * env, + jclass, + jlong connection_id, + jbyteArray name_bytes, + jobjectArray argument_type_bytes, + jbyteArray return_type_bytes, + jint flags, + jobject callback) +{ + try + { + if (refuseInsideScalarFunction(env)) + return; + // Optional symbol, from v26.11.2-rc.3. The Java side checks scalarFunctionsAvailable() + // first and says which release has it; this is the backstop. + const auto create = optionalApi().create_scalar_function; + if (create == nullptr) + { + throwNative(env, "this libchdb does not export chdb_create_scalar_function, which chdb-core v26.11.2-rc.3 added"); + return; + } + const uint32_t known = kScalarFunctionVolatile | kScalarFunctionSpecialNullHandling | kScalarFunctionBinaryStrings; + if (callback == nullptr || (static_cast(flags) & ~known) != 0) + { + throwNative(env, callback == nullptr ? "the scalar function callback is null" : "invalid scalar function flags"); + return; + } + auto connection = requireConnection(env, connection_id); + if (!connection) + return; + + std::string name; + std::string return_type; + std::vector argument_types; + if (!toBytes(env, name_bytes, name) || !toBytes(env, return_type_bytes, return_type) + || !toBytesVector(env, argument_type_bytes, argument_types)) + return; + bool valid = !name.empty() && !hasNul(name) && !return_type.empty() && !hasNul(return_type); + for (const auto & type : argument_types) + valid = valid && !type.empty() && !hasNul(type); + if (!valid) + { + throwNative(env, "a scalar function name or type is empty or contains a NUL byte"); + return; + } + + auto state = std::make_unique(); + if (env->GetJavaVM(&state->vm) != JNI_OK) + { + throwNative(env, "cannot reach the JVM to register a scalar function"); + return; + } + jclass base = env->FindClass("org/chdb/internal/ScalarFunctionCallback"); + if (base == nullptr) + return; + state->invoke = env->GetMethodID(base, "invoke", "(JJJJ)[B"); + state->destroyed = env->GetMethodID(base, "destroyed", "()V"); + env->DeleteLocalRef(base); + // Looked up here, on a Java thread, for the reason ScalarFunctionState gives: the + // callbacks that use it run where FindClass may not see the driver. + if (state->invoke == nullptr || state->destroyed == nullptr || arrowColumnClass(env) == nullptr) + return; + + std::vector type_pointers; + type_pointers.reserve(argument_types.size()); + for (const auto & type : argument_types) + type_pointers.push_back(type.c_str()); + ScalarFunctionOptionsV1 options{}; + options.struct_size = sizeof(options); + options.argument_types = type_pointers.empty() ? nullptr : type_pointers.data(); + options.argument_count = type_pointers.size(); + options.return_type = return_type.c_str(); + options.flags = static_cast(flags); + options.callback = callScalarFunction; + options.user_data = state.get(); + options.destroy = destroyScalarFunction; + + state->callback = env->NewGlobalRef(callback); + if (state->callback == nullptr) + { + throwOutOfMemory(env, "out of memory registering a scalar function"); + return; + } + chdb_result * raw = nullptr; + bool closed = false; + { + std::lock_guard lock(connection->mutex); + closed = connection->conn == nullptr; + if (!closed) + raw = create(*connection->conn, name.c_str(), &options); + } + std::unique_ptr result(raw, &chdb_destroy_query_result); + const std::string error + = closed ? std::string("the connection was closed before the function could be registered") : resultError(result.get()); + if (!error.empty()) + { + // A failed registration transfers nothing: the state is still the shim's to free. + env->DeleteGlobalRef(state->callback); + throwNative(env, error); + return; + } + // chDB owns it now, and hands it back through destroyScalarFunction. + state.release(); + } + catch (const std::bad_alloc &) + { + throwOutOfMemory(env, "out of memory registering a scalar function"); + } + catch (const std::exception & e) + { + throwNative(env, std::string("scalar function registration failed: ") + e.what()); + } +} + +extern "C" JNIEXPORT void JNICALL +Java_org_chdb_internal_ChdbNative_dropScalarFunction(JNIEnv * env, jclass, jbyteArray name_bytes) +{ + try + { + if (refuseInsideScalarFunction(env)) + return; + const auto drop = optionalApi().drop_scalar_function; + if (drop == nullptr) + { + throwNative(env, "this libchdb does not export chdb_drop_scalar_function, which chdb-core v26.11.2-rc.3 added"); + return; + } + std::string name; + if (!toBytes(env, name_bytes, name)) + return; + if (name.empty() || hasNul(name)) + { + throwNative(env, "a scalar function name is empty or contains a NUL byte"); + return; + } + // No connection: registrations outlive every connection, and chdb.h lets this one be NULL. + // chDB may destroy the function inside this call, which upcalls Java on this thread. + std::unique_ptr result( + drop(nullptr, name.c_str()), &chdb_destroy_query_result); + const std::string error = resultError(result.get()); + if (!error.empty()) + throwNative(env, error); + } + catch (const std::exception & e) + { + throwNative(env, std::string("dropping the scalar function failed: ") + e.what()); + } +} + +extern "C" JNIEXPORT jobject JNICALL +Java_org_chdb_internal_ChdbNative_copyArrowArray(JNIEnv * env, jclass, jlong schema_address, jlong array_address) +{ + try + { + if (schema_address == 0 || array_address == 0) + { + throwNative(env, "Arrow schema or array address is null"); + return nullptr; + } + const ArrowColumnClass * classes = arrowColumnClass(env); + if (classes == nullptr) + return nullptr; + const auto * schema = reinterpret_cast(static_cast(schema_address)); + const auto * array = reinterpret_cast(static_cast(array_address)); + if (schema->release == nullptr || array->release == nullptr) + { + throwNative(env, "the Arrow array was already released"); + return nullptr; + } + return copyArrowColumn(env, *classes, *schema, *array, 0); + } + catch (const std::bad_alloc &) + { + throwOutOfMemory(env, "out of memory copying an Arrow array"); + return nullptr; + } + catch (const std::exception & e) + { + throwNative(env, std::string("copying the Arrow array failed: ") + e.what()); + return nullptr; + } +} + +extern "C" JNIEXPORT void JNICALL +Java_org_chdb_internal_ChdbNative_exportArrowArray( + JNIEnv * env, jclass, jobject column, jlong schema_address, jlong array_address) +{ + try + { + if (schema_address == 0 || array_address == 0) + { + throwNative(env, "Arrow schema or array address is null"); + return; + } + const ArrowColumnClass * classes = arrowColumnClass(env); + if (classes == nullptr) + return; + auto * schema = reinterpret_cast(static_cast(schema_address)); + auto * array = reinterpret_cast(static_cast(array_address)); + if (schema->release != nullptr || array->release != nullptr) + { + throwNative(env, "the Arrow result was already filled"); + return; + } + ArrowOwnedArray owned; + if (!readArrowColumn(env, *classes, column, owned, 0)) + return; + std::string error; + if (!exportArrowArray(std::move(owned), schema, array, error)) + throwNative(env, error); + } + catch (const std::bad_alloc &) + { + throwOutOfMemory(env, "out of memory exporting an Arrow array"); + } + catch (const std::exception & e) + { + throwNative(env, std::string("exporting the Arrow array failed: ") + e.what()); + } +} + // ====================================================================== diagnostics extern "C" JNIEXPORT jlong JNICALL @@ -1412,6 +2137,8 @@ Java_org_chdb_internal_ChdbNative_shutdown(JNIEnv * env, jclass) { try { + if (refuseInsideScalarFunction(env)) + return 1; // Optional symbol, like the classifier. 2 means "this engine has no chdb_shutdown", // which is not a failure: skipping it is as safe as it always was for a process // that simply exits. diff --git a/chdb-jni/src/chdb_jni_functions.cpp b/chdb-jni/src/chdb_jni_functions.cpp new file mode 100644 index 0000000..e66821d --- /dev/null +++ b/chdb-jni/src/chdb_jni_functions.cpp @@ -0,0 +1,455 @@ +#include "chdb_jni_functions.h" + +#include +#include +#include +#include + +namespace chdb_jni +{ + +namespace +{ + +// Reads the whole of text as a decimal number. Strict on purpose: a format such as "w:a" must be +// refused rather than read as a width of 0, or as whatever atoi makes of it, because the width +// decides how many bytes are copied out of the producer's buffer. +bool parseDigits(const std::string & text, size_t & value) +{ + if (text.empty() || text.size() > 9) + return false; + value = 0; + for (const char c : text) + { + if (c < '0' || c > '9') + return false; + value = value * 10 + static_cast(c - '0'); + } + return true; +} + +// A width or a precision: a decimal number above zero, or 0 when text is not one. +size_t parsePositive(const std::string & text) +{ + size_t value = 0; + return parseDigits(text, value) ? value : 0; +} + +bool isTimeUnit(char c) +{ + return c == 's' || c == 'm' || c == 'u' || c == 'n'; +} + +// Bytes per slot of a fixed-width format, or 0 if format is not one. +size_t fixedWidth(const std::string & format) +{ + if (format.size() == 1) + { + switch (format[0]) + { + case 'c': // int8 + case 'C': // uint8 + return 1; + case 's': // int16 + case 'S': // uint16 + case 'e': // float16 + return 2; + case 'i': // int32 + case 'I': // uint32 + case 'f': // float32 + return 4; + case 'l': // int64 + case 'L': // uint64 + case 'g': // float64 + return 8; + default: + return 0; + } + } + // Dates, times and intervals: date32 and time32 are four bytes, date64 and time64 eight, + // interval[days, ms] two int32s, interval[month, day, ns] two int32s and an int64. + if (format == "tdD" || format == "tts" || format == "ttm" || format == "tiM") + return 4; + if (format == "tdm" || format == "ttu" || format == "ttn" || format == "tiD") + return 8; + if (format == "tin") + return 16; + // timestamp "ts:" and duration "tD", both int64. + if (format.size() >= 4 && format.compare(0, 2, "ts") == 0 && isTimeUnit(format[2]) && format[3] == ':') + return 8; + if (format.size() == 3 && format.compare(0, 2, "tD") == 0 && isTimeUnit(format[2])) + return 8; + // decimal "d:precision,scale[,bitwidth]", 128 bits unless the width is named. + if (format.compare(0, 2, "d:") == 0) + { + const size_t first = format.find(',', 2); + if (first == std::string::npos || parsePositive(format.substr(2, first - 2)) == 0) + return 0; + const size_t second = format.find(',', first + 1); + const std::string scale = format.substr(first + 1, second == std::string::npos ? std::string::npos : second - first - 1); + // A negative scale is legal Arrow, so only its digits are checked. + size_t digits = 0; + if (!parseDigits(!scale.empty() && scale[0] == '-' ? scale.substr(1) : scale, digits)) + return 0; + if (second == std::string::npos) + return 16; + const size_t bits = parsePositive(format.substr(second + 1)); + return bits == 32 || bits == 64 || bits == 128 || bits == 256 ? bits / 8 : 0; + } + // fixed-size binary "w:". + if (format.compare(0, 2, "w:") == 0) + return parsePositive(format.substr(2)); + return 0; +} + +size_t bitmapBytes(uint64_t slots) +{ + return static_cast((slots + 7) / 8); +} + +// The value of an offsets buffer at index, which the caller has checked is inside it. +template +int64_t offsetAt(const void * offsets, uint64_t index) +{ + Offset value; + std::memcpy(&value, static_cast(offsets) + index * sizeof(Offset), sizeof(Offset)); + return static_cast(value); +} + +bool isList(const std::string & format) +{ + return format == "+l" || format == "+L" || format.compare(0, 3, "+w:") == 0; +} + +// How many children C Data gives an array of this format: -1 for any number, which only a struct +// has. +int childCount(const std::string & format) +{ + if (format == "+s") + return -1; + return isList(format) || format == "+m" ? 1 : 0; +} + +// ArrowSchema::private_data of an exported array. +struct ExportedSchema +{ + std::string format; + std::string name; + std::vector children; + std::vector child_pointers; + + ExportedSchema() = default; + ExportedSchema(const ExportedSchema &) = delete; + ExportedSchema & operator=(const ExportedSchema &) = delete; + + ~ExportedSchema() + { + // A child the consumer moved out has release == nullptr; the rest are still ours. + for (ArrowSchema & child : children) + if (child.release != nullptr) + child.release(&child); + } +}; + +// ArrowArray::private_data of an exported array. +struct ExportedArray +{ + std::vector buffers; + std::vector buffer_pointers; + std::vector children; + std::vector child_pointers; + + ExportedArray() = default; + ExportedArray(const ExportedArray &) = delete; + ExportedArray & operator=(const ExportedArray &) = delete; + + ~ExportedArray() + { + for (ArrowArray & child : children) + if (child.release != nullptr) + child.release(&child); + } +}; + +extern "C" { + +static void releaseExportedSchema(ArrowSchema * schema) +{ + delete static_cast(schema->private_data); + schema->release = nullptr; +} + +static void releaseExportedArray(ArrowArray * array) +{ + delete static_cast(array->private_data); + array->release = nullptr; +} + +} // extern "C" + +bool validate(const ArrowOwnedArray & array, std::string & error) +{ + const int buffers = arrowBufferCount(array.format); + if (buffers < 0) + { + error = "cannot export Arrow format '" + array.format + "'"; + return false; + } + if (array.buffers.size() != static_cast(buffers)) + { + error = "Arrow format '" + array.format + "' has " + std::to_string(buffers) + " buffers, not " + + std::to_string(array.buffers.size()); + return false; + } + const int children = childCount(array.format); + if (children >= 0 && array.children.size() != static_cast(children)) + { + error = "Arrow format '" + array.format + "' has " + std::to_string(children) + " children, not " + + std::to_string(array.children.size()); + return false; + } + if (array.format == "+m" && (array.children[0].format != "+s" || array.children[0].children.size() != 2)) + { + error = "an Arrow map's child must be a struct of a key and a value"; + return false; + } + if (array.length < 0 || array.offset < 0 || array.null_count < 0 || array.null_count > array.length) + { + error = "Arrow array with length " + std::to_string(array.length) + ", offset " + std::to_string(array.offset) + + " and null count " + std::to_string(array.null_count); + return false; + } + for (const ArrowOwnedArray & child : array.children) + if (!validate(child, error)) + return false; + return true; +} + +// Builds schema and out for an array validate() accepted. Assigns to the two structs only once +// everything they will point at exists, so an allocation failure part way leaves them as they +// were and frees whatever was built -- including children already filled, which their parent's +// private data releases as it is destroyed. +void fill(ArrowOwnedArray & array, const std::string & name, bool map_entries, ArrowSchema * schema, ArrowArray * out) +{ + auto schema_data = std::make_unique(); + auto array_data = std::make_unique(); + schema_data->format = array.format; + schema_data->name = name; + + const size_t children = array.children.size(); + schema_data->children.assign(children, ArrowSchema{}); + array_data->children.assign(children, ArrowArray{}); + for (size_t i = 0; i < children; ++i) + { + std::string child_name; + if (isList(array.format)) + child_name = "item"; + else if (array.format == "+m") + child_name = "entries"; + else if (map_entries) + child_name = i == 0 ? "key" : "value"; + else + child_name = std::to_string(i + 1); + fill(array.children[i], child_name, array.format == "+m", &schema_data->children[i], &array_data->children[i]); + } + for (ArrowSchema & child : schema_data->children) + schema_data->child_pointers.push_back(&child); + for (ArrowArray & child : array_data->children) + array_data->child_pointers.push_back(&child); + + array_data->buffers = std::move(array.buffers); + for (const ArrowOwnedArray::Buffer & buffer : array_data->buffers) + array_data->buffer_pointers.push_back(buffer.present ? buffer.bytes.data() : nullptr); + + // Nothing below allocates. + schema->format = schema_data->format.c_str(); + schema->name = schema_data->name.c_str(); + schema->metadata = nullptr; + schema->flags = array.nullable ? ARROW_FLAG_NULLABLE : 0; + schema->n_children = static_cast(children); + schema->children = children == 0 ? nullptr : schema_data->child_pointers.data(); + schema->dictionary = nullptr; + schema->release = releaseExportedSchema; + schema->private_data = schema_data.release(); + + out->length = array.length; + out->null_count = array.null_count; + out->offset = array.offset; + out->n_buffers = static_cast(array_data->buffer_pointers.size()); + out->n_children = static_cast(children); + out->buffers = array_data->buffer_pointers.empty() ? nullptr : array_data->buffer_pointers.data(); + out->children = children == 0 ? nullptr : array_data->child_pointers.data(); + out->dictionary = nullptr; + out->release = releaseExportedArray; + out->private_data = array_data.release(); +} + +} // namespace + +bool arrowBufferExtents( + const ArrowSchema & schema, const ArrowArray & array, std::vector & extents, std::string & error) +{ + extents.clear(); + if (schema.format == nullptr) + { + error = "the Arrow schema has no format"; + return false; + } + const std::string format = schema.format; + if (schema.dictionary != nullptr || array.dictionary != nullptr) + { + error = "dictionary-encoded Arrow arrays are not supported"; + return false; + } + // A length or offset past this would overflow the arithmetic below; no batch comes near it. + constexpr int64_t kMaxSlots = int64_t{1} << 40; + if (array.length < 0 || array.offset < 0 || array.length > kMaxSlots || array.offset > kMaxSlots) + { + error = "Arrow array with length " + std::to_string(array.length) + " and offset " + std::to_string(array.offset); + return false; + } + const int expected = arrowBufferCount(format); + if (expected < 0) + { + error = "Arrow format '" + format + "' is not supported"; + return false; + } + if (array.n_buffers != expected || (expected > 0 && array.buffers == nullptr)) + { + error = "Arrow format '" + format + "' needs " + std::to_string(expected) + " buffers, the array has " + + std::to_string(array.n_buffers); + return false; + } + + const uint64_t slots = static_cast(array.offset) + static_cast(array.length); + auto bitmap = [&](int index) { extents.push_back({array.buffers[index], array.buffers[index] ? bitmapBytes(slots) : 0}); }; + auto bytes = [&](int index, size_t size) { extents.push_back({array.buffers[index], array.buffers[index] ? size : 0}); }; + // Variable-length values: offsets of type Offset, then the data the last of them points past. + auto variable = [&](size_t offset_bytes, bool with_data) -> bool + { + bitmap(0); + const void * offsets = array.buffers[1]; + if (offsets == nullptr) + { + if (slots != 0) + { + error = "Arrow array of format '" + format + "' has no offsets buffer"; + return false; + } + bytes(1, 0); + if (with_data) + bytes(2, 0); + return true; + } + bytes(1, (slots + 1) * offset_bytes); + if (with_data) + { + const int64_t end = offset_bytes == 4 ? offsetAt(offsets, slots) : offsetAt(offsets, slots); + if (end < 0) + { + error = "Arrow array of format '" + format + "' ends at offset " + std::to_string(end); + return false; + } + bytes(2, static_cast(end)); + } + return true; + }; + + if (format == "n") + return true; + if (format == "b") + { + bitmap(0); + bitmap(1); + return true; + } + if (const size_t width = fixedWidth(format)) + { + bitmap(0); + bytes(1, slots * width); + return true; + } + if (format == "u" || format == "z") + return variable(4, true); + if (format == "U" || format == "Z") + return variable(8, true); + if (format == "+l" || format == "+m") + return variable(4, false); + if (format == "+L") + return variable(8, false); + // fixed-size list and struct: a validity bitmap only. + bitmap(0); + return true; +} + +std::string arrowExtensionName(const char * metadata) +{ + if (metadata == nullptr) + return std::string(); + // int32 count, then for each entry: int32 key length, the key, int32 value length, the value. + auto readInt = [](const char *& at) + { + int32_t value; + std::memcpy(&value, at, sizeof(value)); + at += sizeof(value); + return value; + }; + static const std::string kExtensionName = "ARROW:extension:name"; + const char * at = metadata; + const int32_t count = readInt(at); + for (int32_t i = 0; i < count; ++i) + { + const int32_t key_length = readInt(at); + if (key_length < 0) + return std::string(); + const char * key = at; + at += key_length; + const int32_t value_length = readInt(at); + if (value_length < 0) + return std::string(); + const char * value = at; + at += value_length; + if (kExtensionName.compare(0, std::string::npos, key, static_cast(key_length)) == 0) + return std::string(value, static_cast(value_length)); + } + return std::string(); +} + +int arrowBufferCount(const std::string & format) +{ + if (format == "n") + return 0; + if (format == "b" || fixedWidth(format) != 0) + return 2; + if (format == "u" || format == "z" || format == "U" || format == "Z") + return 3; + if (format == "+l" || format == "+L" || format == "+m") + return 2; + if (format == "+s" || (format.compare(0, 3, "+w:") == 0 && parsePositive(format.substr(3)) != 0)) + return 1; + return -1; +} + +bool exportArrowArray(ArrowOwnedArray && array, ArrowSchema * schema, ArrowArray * out, std::string & error) +{ + if (!validate(array, error)) + return false; + fill(array, std::string(), false, schema, out); + return true; +} + +void writeErrorMessage(const std::string & message, char * buffer, size_t size) +{ + if (buffer == nullptr || size == 0) + return; + size_t length = message.size() < size - 1 ? message.size() : size - 1; + // Cutting before a continuation byte (10xxxxxx) would split a character: step back to the + // byte that starts it, so what chDB reports is still valid UTF-8. + if (length < message.size()) + while (length > 0 && (static_cast(message[length]) & 0xC0) == 0x80) + --length; + std::memcpy(buffer, message.data(), length); + buffer[length] = '\0'; +} + +} // namespace chdb_jni diff --git a/chdb-jni/src/chdb_jni_functions.h b/chdb-jni/src/chdb_jni_functions.h new file mode 100644 index 0000000..c4a28e3 --- /dev/null +++ b/chdb-jni/src/chdb_jni_functions.h @@ -0,0 +1,79 @@ +// The half of scalar function support that needs neither a JVM nor the engine: reading the +// layout of an argument array, building result arrays, and filling the callback's error buffer. +// +// The Arrow C Data Interface carries no buffer lengths -- a consumer is expected to know the +// layout of the type it reads. The shim copies argument buffers into Java arrays, so it has to +// know them: copying past the end of the producer's allocation is a crash in the engine's memory, +// not an exception. And a result has to stay valid after the callback returns, until chDB calls +// its release, so it is built here in memory the garbage collector cannot move or free. +// +// Kept apart from chdb_jni.cpp so that chdb_jni_test can run it under ASan, which cannot be +// preloaded into a JVM holding the released engine (see test/chdb_jni_test.cpp). + +#pragma once + +#include +#include +#include +#include + +#include "arrow_c_abi.h" + +namespace chdb_jni +{ + +// One buffer of an array: its address, and how many bytes of it the array's slots cover. data is +// null for a buffer the producer left out, which C Data allows for a validity bitmap when there +// are no nulls and for any buffer of zero bytes. +struct ArrowBufferExtent +{ + const void * data = nullptr; + size_t size = 0; +}; + +// The extent of every buffer of array -- not of its children -- in the order C Data lays them out +// for schema's format. False, with the reason in error, for a layout this does not read: a +// dictionary, a union, a view, run-end encoding, or a format it does not recognise. +bool arrowBufferExtents( + const ArrowSchema & schema, const ArrowArray & array, std::vector & extents, std::string & error); + +// The value of ARROW:extension:name in a C Data metadata blob, or empty if there is none. +std::string arrowExtensionName(const char * metadata); + +// An array the shim builds and hands over, before it is exported. +struct ArrowOwnedArray +{ + struct Buffer + { + // An absent buffer is exported as a null pointer. + bool present = false; + std::vector bytes; + }; + + std::string format; + bool nullable = false; + int64_t length = 0; + int64_t null_count = 0; + int64_t offset = 0; + std::vector buffers; + std::vector children; +}; + +// How many buffers C Data gives an array of this format, or -1 for a format the shim does not +// export. +int arrowBufferCount(const std::string & format); + +// Moves array into the zeroed schema and out structs. Each gets a release callback that frees +// what it holds, so the receiver owns all of it afterwards. Children are named the way Arrow names +// them: "item" in a list, "entries" in a map, "key" and "value" in its entries, and a struct's +// fields by position from "1". +// +// False, with the reason in error and both structs left zeroed, for an array the format cannot +// describe: an unknown format, the wrong number of buffers or children, or a negative count. +bool exportArrowArray(ArrowOwnedArray && array, ArrowSchema * schema, ArrowArray * out, std::string & error); + +// Copies message into buffer, NUL-terminated, cut at a UTF-8 character boundary when it is longer +// than size - 1 bytes. Writes nothing when size is 0. +void writeErrorMessage(const std::string & message, char * buffer, size_t size); + +} // namespace chdb_jni diff --git a/chdb-jni/src/chdb_jni_handles.h b/chdb-jni/src/chdb_jni_handles.h index 43bf5d6..b58db6e 100644 --- a/chdb-jni/src/chdb_jni_handles.h +++ b/chdb-jni/src/chdb_jni_handles.h @@ -24,7 +24,7 @@ namespace chdb_jni // Bumped only on an incompatible change to the Java <-> shim contract. Must match // ChdbNative.JNI_ABI_VERSION on the Java side and chdb.jni.abi.version in the poms. -constexpr int32_t kJniAbiVersion = 5; +constexpr int32_t kJniAbiVersion = 6; enum HandleKind : int32_t { @@ -42,6 +42,8 @@ enum HandleKind : int32_t // // chdb_jni_signals.cpp signalMutex() (leaf, held only around chdb_connect and // chdb_set_signal_handlers_enabled) +// chdb_jni.cpp arrowColumnClass() mutex (leaf, held only around the one-time JNI +// lookups of org.chdb.internal.ArrowColumn) // // Why the stream comes first: a stream is driven by exactly one caller thread, which holds // its handle mutex for the length of a fetch, and that fetch needs the connection to stay diff --git a/chdb-jni/src/chdb_optional_api.cpp b/chdb-jni/src/chdb_optional_api.cpp index b46595e..bac1824 100644 --- a/chdb-jni/src/chdb_optional_api.cpp +++ b/chdb-jni/src/chdb_optional_api.cpp @@ -22,6 +22,9 @@ OptionalApi resolveAll() OptionalApi api; api.classify_query_n = resolve("chdb_classify_query_n"); api.shutdown = resolve("chdb_shutdown"); + api.create_scalar_function + = resolve("chdb_create_scalar_function"); + api.drop_scalar_function = resolve("chdb_drop_scalar_function"); return api; } diff --git a/chdb-jni/src/chdb_optional_api.h b/chdb-jni/src/chdb_optional_api.h index e65e7f3..41465a9 100644 --- a/chdb-jni/src/chdb_optional_api.h +++ b/chdb-jni/src/chdb_optional_api.h @@ -16,6 +16,14 @@ // to degrade rather than fail the load. The required half is everything chdb_jni.cpp calls // directly, which the linker checks at build time and the loader re-checks at startup. // +// The scalar function ABI is optional for the same reason, and newer than both: +// +// chdb_create_scalar_function since v26.11.2-rc.3 registers a host function for SQL +// chdb_drop_scalar_function since v26.11.2-rc.3 unregisters it +// +// Without them everything else keeps working and registering a function fails with a message +// naming the release that has them. +// // Resolution uses RTLD_DEFAULT rather than a dlopen handle. By the time any of this runs // the Java loader has already System.load()-ed libchdb into the process, so its symbols // are in the global namespace and there is no second handle to keep in sync. @@ -55,6 +63,38 @@ enum QueryClass : uint32_t kQueryUnknown = 4, }; +// Mirrors chdb_scalar_function_options, for the reason QueryAnalysisV1 mirrors its struct: it is +// versioned by its first field, so an engine newer than this definition reads only the fields it +// has room for. The Arrow handles in the callback are passed as plain pointers to the C Data +// structs in arrow_c_abi.h. +struct ScalarFunctionOptionsV1 +{ + size_t struct_size; + const char * const * argument_types; + size_t argument_count; + const char * return_type; + uint32_t flags; + int (*callback)( + void * user_data, + void * argument_schema, + void * arguments, + void * result_schema, + void * result, + char * error, + size_t error_size); + void * user_data; + void (*destroy)(void * user_data); +}; + +// chdb_scalar_function_flag values, as of v26.11.2-rc.3. Kept in sync with the flag constants in +// ScalarFunctionCallback on the Java side. +enum ScalarFunctionFlag : uint32_t +{ + kScalarFunctionVolatile = 1u << 0, + kScalarFunctionSpecialNullHandling = 1u << 1, + kScalarFunctionBinaryStrings = 1u << 2, +}; + struct OptionalApi { chdb_state (*classify_query_n)( @@ -67,6 +107,12 @@ struct OptionalApi = nullptr; chdb_state (*shutdown)() = nullptr; + + chdb_result * (*create_scalar_function)( + chdb_connection conn, const char * name, const ScalarFunctionOptionsV1 * options) + = nullptr; + + chdb_result * (*drop_scalar_function)(chdb_connection conn, const char * name) = nullptr; }; // Resolved once, on first use. Safe to call from any thread. diff --git a/chdb-jni/test/chdb_jni_test.cpp b/chdb-jni/test/chdb_jni_test.cpp index cc44a79..5cff403 100644 --- a/chdb-jni/test/chdb_jni_test.cpp +++ b/chdb-jni/test/chdb_jni_test.cpp @@ -12,6 +12,8 @@ // - The handle registry, which is the mechanism that turns a use-after-close into an // exception instead of a dereference. // - The signal guard's snapshot and restore. +// - The scalar function data path: how many bytes of each argument buffer are copied, and +// result arrays that chDB frees through their release callbacks. // // UBSan covers the whole JDBC suite separately, in a real JVM against the real engine, because // it does not intercept allocation and so coexists with both. @@ -27,6 +29,7 @@ #include #include +#include "chdb_jni_functions.h" #include "chdb_jni_handles.h" #include "chdb_jni_signals.h" @@ -284,6 +287,304 @@ void testSignalGuard() sigaction(SIGUSR2, &original, nullptr); } + +// ---------------------------------------------------------------- scalar function data + +// An argument array as a producer lays it out, for arrowBufferExtents to measure. Nothing here +// is released: the extents only read the structs. +struct TestArray +{ + ArrowSchema schema{}; + ArrowArray array{}; + std::vector buffers; + + TestArray(const char * format, int64_t length, int64_t offset, std::vector with) + : buffers(std::move(with)) + { + schema.format = format; + array.length = length; + array.offset = offset; + array.n_buffers = static_cast(buffers.size()); + array.buffers = buffers.empty() ? nullptr : buffers.data(); + } +}; + +std::vector extentsOf(const TestArray & test, std::string & error) +{ + std::vector extents; + error.clear(); + if (!arrowBufferExtents(test.schema, test.array, extents, error)) + extents.clear(); + return extents; +} + +void testArrowBufferExtents() +{ + std::string error; + const uint8_t bits[4] = {0xff, 0xff, 0xff, 0xff}; + const int64_t longs[8] = {0}; + + // Fixed width: offset plus length slots of the value's size, the bitmap rounded up to bytes. + { + TestArray test("l", 5, 2, {bits, longs}); + auto extents = extentsOf(test, error); + checkEqual(static_cast(extents.size()), 2, "int64 has two buffers"); + if (extents.size() == 2) + { + checkEqual(static_cast(extents[0].size), 1, "bitmap of 7 slots is one byte"); + checkEqual(static_cast(extents[1].size), 7 * 8, "7 slots of 8 bytes"); + } + } + // An absent validity bitmap is reported as absent, not sized. + { + TestArray test("i", 3, 0, {nullptr, longs}); + auto extents = extentsOf(test, error); + check(extents.size() == 2 && extents[0].data == nullptr && extents[0].size == 0, "absent bitmap"); + } + // The widths the format grammar spells out rather than names. + const std::pair widths[] = { + {"tdD", 4}, {"tsn:UTC", 8}, {"tss:", 8}, {"d:18,4", 16}, {"d:76,20,256", 32}, {"d:9,-2", 16}, {"w:16", 16}, {"w:3", 3}}; + for (const auto & width : widths) + { + TestArray test(width.first, 1, 0, {nullptr, longs}); + auto extents = extentsOf(test, error); + check(extents.size() == 2 && extents[1].size == static_cast(width.second), + std::string("width of ") + width.first); + } + // Variable width: the data extent is where the last slot's offset ends. + { + const int32_t offsets[] = {0, 3, 3, 10}; + const char data[] = "abcdefghij"; + TestArray test("u", 2, 1, {nullptr, offsets, data}); + auto extents = extentsOf(test, error); + check(extents.size() == 3, "utf8 has three buffers"); + if (extents.size() == 3) + { + checkEqual(static_cast(extents[1].size), 4 * 4, "offsets for offset + length + 1 slots"); + checkEqual(static_cast(extents[2].size), 10, "data up to the last offset"); + } + } + { + const int64_t offsets[] = {0, 2}; + TestArray test("Z", 1, 0, {nullptr, offsets, "xy"}); + auto extents = extentsOf(test, error); + check(extents.size() == 3 && extents[1].size == 16 && extents[2].size == 2, "large binary"); + } + // A list measures its offsets, not its child, which has a length of its own. + { + const int32_t offsets[] = {0, 2, 5}; + TestArray test("+l", 2, 0, {nullptr, offsets}); + auto extents = extentsOf(test, error); + check(extents.size() == 2 && extents[1].size == 12, "list offsets"); + } + { + TestArray test("+s", 9, 0, {bits}); + auto extents = extentsOf(test, error); + check(extents.size() == 1 && extents[0].size == 2, "struct bitmap of 9 slots is two bytes"); + } + { + TestArray test("b", 9, 0, {nullptr, bits}); + auto extents = extentsOf(test, error); + check(extents.size() == 2 && extents[1].size == 2, "bool values are a bitmap too"); + } + // Zero rows of strings may come with no offsets at all. + { + TestArray test("u", 0, 0, {nullptr, nullptr, nullptr}); + auto extents = extentsOf(test, error); + check(extents.size() == 3 && extents[2].size == 0, "an empty string array without offsets"); + } + + // What is refused, rather than measured wrongly. + const char * refused[] = {"+ud:0,1", "vu", "+r", "w:a", "w:", "d:a,2", "d:10,2,100", "?"}; + for (const char * format : refused) + { + TestArray test(format, 1, 0, {nullptr, longs}); + check(extentsOf(test, error).empty() && !error.empty(), std::string("refuses ") + format); + } + { + TestArray test("l", 1, 0, {nullptr, longs, longs}); + check(extentsOf(test, error).empty() && !error.empty(), "refuses a buffer count the format does not have"); + } + { + TestArray test("u", 2, 0, {nullptr, nullptr, nullptr}); + check(extentsOf(test, error).empty() && !error.empty(), "refuses rows of strings without offsets"); + } + { + ArrowSchema dictionary{}; + TestArray test("i", 1, 0, {nullptr, longs}); + test.schema.dictionary = &dictionary; + check(extentsOf(test, error).empty() && !error.empty(), "refuses a dictionary"); + } + { + TestArray test("l", -1, 0, {nullptr, longs}); + check(extentsOf(test, error).empty() && !error.empty(), "refuses a negative length"); + } +} + +void testArrowExtensionName() +{ + // int32 count, then key and value, each an int32 length and its bytes. + std::string metadata; + auto put = [&metadata](const std::string & text) + { + const int32_t length = static_cast(text.size()); + metadata.append(reinterpret_cast(&length), sizeof(length)); + metadata += text; + }; + const int32_t count = 2; + metadata.append(reinterpret_cast(&count), sizeof(count)); + put("PARQUET:logical_type"); + put("UUID"); + put("ARROW:extension:name"); + put("arrow.uuid"); + check(arrowExtensionName(metadata.data()) == "arrow.uuid", "reads the extension name"); + check(arrowExtensionName(nullptr).empty(), "no metadata, no extension"); +} + +ArrowOwnedArray ownedInt64(std::vector values) +{ + ArrowOwnedArray array; + array.format = "l"; + array.length = static_cast(values.size()); + array.buffers.resize(2); + array.buffers[1].present = true; + array.buffers[1].bytes.resize(values.size() * sizeof(int64_t)); + std::memcpy(array.buffers[1].bytes.data(), values.data(), array.buffers[1].bytes.size()); + return array; +} + +void testExportArrowArray() +{ + std::string error; + + // A flat array: the receiver reads it, then releases it, which frees everything (ASan and + // LSan are the assertion for the latter). + { + ArrowSchema schema{}; + ArrowArray array{}; + check(exportArrowArray(ownedInt64({7, -8, 9}), &schema, &array, error), "exports int64"); + check(std::strcmp(schema.format, "l") == 0 && array.length == 3 && array.n_buffers == 2, "int64 shape"); + check(array.buffers[0] == nullptr, "no validity bitmap was given, none is exported"); + int64_t second = 0; + std::memcpy(&second, static_cast(array.buffers[1]) + sizeof(int64_t), sizeof(second)); + checkEqual(second, -8, "the values are the ones given"); + schema.release(&schema); + array.release(&array); + check(schema.release == nullptr && array.release == nullptr, "release marks the structs released"); + } + + // A map: children named the way Arrow names them, and a child the receiver moved out is + // left to the receiver when the parent is released. + { + ArrowOwnedArray entries; + entries.format = "+s"; + entries.length = 2; + entries.buffers.resize(1); + ArrowOwnedArray keys = ownedInt64({1, 2}); + ArrowOwnedArray values = ownedInt64({10, 20}); + values.nullable = true; + entries.children.push_back(std::move(keys)); + entries.children.push_back(std::move(values)); + ArrowOwnedArray map; + map.format = "+m"; + map.length = 1; + map.buffers.resize(2); + map.buffers[1].present = true; + map.buffers[1].bytes.resize(2 * sizeof(int32_t)); + const int32_t offsets[] = {0, 2}; + std::memcpy(map.buffers[1].bytes.data(), offsets, sizeof(offsets)); + map.children.push_back(std::move(entries)); + + ArrowSchema schema{}; + ArrowArray array{}; + check(exportArrowArray(std::move(map), &schema, &array, error), "exports a map"); + check(schema.n_children == 1 && std::strcmp(schema.children[0]->name, "entries") == 0, "entries is named"); + check(std::strcmp(schema.children[0]->children[0]->name, "key") == 0 + && std::strcmp(schema.children[0]->children[1]->name, "value") == 0, + "key and value are named"); + check((schema.children[0]->children[0]->flags & ARROW_FLAG_NULLABLE) == 0 + && (schema.children[0]->children[1]->flags & ARROW_FLAG_NULLABLE) != 0, + "nullability is what was given"); + + // Move the entries out, as C Data allows, and release them separately. + ArrowArray moved = *array.children[0]; + array.children[0]->release = nullptr; + array.release(&array); + check(moved.release != nullptr, "the moved child is still alive"); + moved.release(&moved); + schema.release(&schema); + } + + // Structs are named by position. + { + ArrowOwnedArray tuple; + tuple.format = "+s"; + tuple.length = 1; + tuple.buffers.resize(1); + tuple.children.push_back(ownedInt64({1})); + tuple.children.push_back(ownedInt64({2})); + ArrowSchema schema{}; + ArrowArray array{}; + check(exportArrowArray(std::move(tuple), &schema, &array, error), "exports a struct"); + check(std::strcmp(schema.children[0]->name, "1") == 0 && std::strcmp(schema.children[1]->name, "2") == 0, + "struct fields are named by position"); + schema.release(&schema); + array.release(&array); + } + + // What cannot be described is refused, and leaves the structs as they were. + auto refused = [&error](ArrowOwnedArray owned, const char * what) + { + ArrowSchema schema{}; + ArrowArray array{}; + const bool exported = exportArrowArray(std::move(owned), &schema, &array, error); + check(!exported && !error.empty() && schema.release == nullptr && array.release == nullptr, + std::string("refuses ") + what); + }; + { + ArrowOwnedArray wrong = ownedInt64({1}); + wrong.buffers.resize(3); + refused(std::move(wrong), "a buffer count the format does not have"); + } + { + ArrowOwnedArray wrong = ownedInt64({1}); + wrong.format = "+ud:0"; + refused(std::move(wrong), "a format it does not export"); + } + { + ArrowOwnedArray wrong = ownedInt64({1}); + wrong.null_count = 2; + refused(std::move(wrong), "more nulls than rows"); + } + { + ArrowOwnedArray wrong; + wrong.format = "+l"; + wrong.length = 0; + wrong.buffers.resize(2); + refused(std::move(wrong), "a list without its child"); + } +} + +void testWriteErrorMessage() +{ + char buffer[8]; + writeErrorMessage("short", buffer, sizeof(buffer)); + check(std::strcmp(buffer, "short") == 0, "a message that fits is copied whole"); + + writeErrorMessage("much too long", buffer, sizeof(buffer)); + check(std::strcmp(buffer, "much to") == 0, "a long one is cut to size - 1 bytes"); + + // "aaaaaé" is 7 bytes, the last two one character: cut at 7 bytes it would end in half of it. + std::memset(buffer, 'x', sizeof(buffer)); + writeErrorMessage("aaaaaa\xc3\xa9!", buffer, sizeof(buffer)); + check(std::strcmp(buffer, "aaaaaa") == 0, "the cut does not split a UTF-8 character"); + + char one[1] = {'x'}; + writeErrorMessage("anything", one, sizeof(one)); + check(one[0] == '\0', "a one-byte buffer gets the terminator"); + writeErrorMessage("anything", nullptr, 0); +} + } // namespace int main() @@ -293,6 +594,10 @@ int main() testHandleRegistry(); testHandleRegistryConcurrency(); testSignalGuard(); + testArrowBufferExtents(); + testArrowExtensionName(); + testExportArrowArray(); + testWriteErrorMessage(); std::printf("\n%d checks, %d failures\n", checks, failures); return failures == 0 ? 0 : 1; diff --git a/docs/scalar-functions.md b/docs/scalar-functions.md new file mode 100644 index 0000000..30e996a --- /dev/null +++ b/docs/scalar-functions.md @@ -0,0 +1,292 @@ +# Scalar functions written in Java + +A scalar user-defined function is Java code that SQL calls like a built-in: one value in per +argument, one value out, for every row. Register it once and any query in the JVM can call it. + +```java +try (Connection connection = DriverManager.getConnection("jdbc:chdb::memory:")) { + ChdbFunctions.scalarFunction() + .withName("plus_one") + .withParameter("Int64") + .withReturnType("Int64") + .withFunction((Long x) -> x + 1) + .register(connection); + + try (Statement statement = connection.createStatement(); + ResultSet rs = statement.executeQuery( + "SELECT plus_one(toInt64(number)) FROM numbers(3)")) { + while (rs.next()) { + System.out.println(rs.getLong(1)); // 1, 2, 3 + } + } + ChdbFunctions.dropScalarFunction("plus_one"); +} +``` + +`ChdbFunctions` and its builder are in `chdb-jdbc` (`org.chdb.jdbc`); the API follows +duckdb-java's `DuckDBFunctions.scalarFunction()`. Functions computed a batch at a time with Arrow +vectors are in the optional `chdb-arrow` module, as [`ArrowFunctions`](#a-batch-at-a-time-with-arrow). + +**Needs chdb-core v26.11.2-rc.3 or later**, the first release with the scalar function C ABI +(`chdb_create_scalar_function` and `chdb_drop_scalar_function`). The driver resolves those two +entry points when the engine loads rather than linking them, so it still loads and runs against +an older `libchdb`, and only registering or dropping a function fails there, with an +`SQLFeatureNotSupportedException` that names the release you need. +`ChdbFunctions.isScalarFunctionSupported()` asks without trying. + +## Declaring a function + +| Builder method | What it declares | +|---|---| +| `withName(String)` | the name SQL calls it by, case-sensitive; required | +| `withParameter(String)`, `withParameters(String...)` | each parameter's ClickHouse type, in order | +| `withReturnType(String)` | the result's ClickHouse type; required | +| `withFunction(Supplier)` | the function, for no parameters | +| `withFunction(Function)` | the function, for one parameter | +| `withFunction(BiFunction)` | the function, for two parameters | +| `withRowFunction(ChdbRowFunction)` | the function, for any number of parameters, as `Object apply(Object[] arguments) throws Exception` | +| `withVolatile()` | see [Volatile functions](#volatile-functions) | +| `withSpecialNullHandling()` | see [NULL arguments](#null-arguments) | +| `withBinaryStrings()` | see [Binary strings](#binary-strings) | +| `register(Connection)` | registers it, through any chDB `Connection` or one that wraps it, such as a pool's proxy | + +Types are ClickHouse type names, exactly as you would write them in SQL: `"Int64"`, +`"Nullable(String)"`, `"Array(Float64)"`, `"DateTime64(3, 'UTC')"`. That is what the engine checks +a call against. An argument of another type is accepted when it converts to the declared one +without loss -- an `Int32` column for an `Int64` parameter -- and reaches the function converted; +one that does not, such as a `UInt64` for an `Int64`, fails the query, so cast it in SQL +(`toInt64(...)`). Note that `numbers(n)` produces `UInt64`. `Nullable(...)` and +`LowCardinality(...)` on a parameter mean the same as the type inside them. + +`register` refuses a name that is already taken -- by a built-in function (in any case, for the +built-ins SQL matches case-insensitively), an aggregate function, a SQL or executable UDF, or +another registration -- and a type name the engine does not know or cannot pass through Arrow, +with an `SQLException` carrying the engine's message. + +## The type mapping + +Each argument reaches Java as the type `ResultSet.getObject` gives for that ClickHouse type, with +the exact `java.time` types in place of the `java.sql` ones JDBC prescribes, and `List` and +`Object[]` for arrays and tuples. Every value is a copy, so a function may keep what it is given. + +What a function returns is sent to chDB in the Arrow form that converts to the declared type +exactly, and chDB converts it the way `CAST` does: a value that does not fit -- 300 for a +`UInt8` -- fails the query with an error naming the function, and a value of a Java type the +declared type does not take -- a `Double` for an integer type -- fails it with a message saying +what it does take. + +| ClickHouse | Argument | Results accepted | +|---|---|---| +| `Bool` | `Boolean` | `Boolean` | +| `Int8`, `Int16`, `Int32`, `Int64` | `Byte`, `Short`, `Integer`, `Long` | `Byte`, `Short`, `Integer`, `Long`, `BigInteger` | +| `UInt8`, `UInt16`, `UInt32` | `Short`, `Integer`, `Long` | as for `Int64` | +| `UInt64`, `Int128`, `UInt128`, `Int256`, `UInt256` | `BigInteger` | as for `Int64` | +| `Float32`, `BFloat16`, `Float64` | `Float`, `Float`, `Double` | any `Number` | +| `Decimal(P, S)` | `BigDecimal` | any `Number`, or a `String` | +| `String`, `FixedString(N)` | `String`, or `byte[]` with binary strings | `String` (any `CharSequence`) or `byte[]` | +| `Enum8`, `Enum16` | `String`, the label | `String`, the label | +| `Date`, `Date32` | `LocalDate` | `LocalDate` | +| `DateTime`, `DateTime64(p)` | `Instant` | `Instant`, `OffsetDateTime`, `ZonedDateTime` | +| `UUID` | `UUID` | `UUID` or a `String` | +| `IPv4`, `IPv6` | `InetAddress` | `InetAddress` or a `String` | +| `Interval*` | `Long` | as for `Int64` | +| `Array(T)` | `List`, of T's argument type | a `Collection` or an array, primitive arrays included | +| `Tuple(...)` | `Object[]` | `Object[]` or a `List`, one element per field | +| `Map(K, V)` | `Map` (insertion-ordered) | `Map`, with no null key | +| `JSON`, `Dynamic` | `String`, the JSON text | `String` | +| `Nullable(T)` | T's type, or `null` | T's types, or `null` | +| any other type | -- | a `String`, which chDB parses as the type | + +Some details the table cannot hold: + +- A `FixedString` keeps its zero padding: `toFixedString('ab', 4)` arrives as `"ab\0\0"`. +- A timestamp is an instant, so it arrives as an `Instant` whatever the column's zone, and a + result is shown in the declared type's zone. A `LocalDateTime` result is refused: it names no + instant, and any zone the driver chose for it would be a guess. A result is cut to the + declared precision toward the past, as a cast to a coarser `DateTime64` is. +- An integer result is sent as a 64-bit integer, or as its decimal text when a `BigInteger` + needs more bits; either way chDB's range check is the one that applies. +- A `Decimal`, `UUID`, `IPv4` or `IPv6` result is sent as its text, which is why a `String` + works there too. A `Decimal` result with more fractional digits than the type has is cut, as + `CAST` cuts it. +- `Time`, `Time64` and `Variant` parameters have no Java value here and are refused when the + function is registered: declare a `String` parameter and pass `toString(...)`, or use the + Arrow API, which receives the Arrow arrays as they are. +- A `null` result is a NULL. chDB accepts one only where the declared return type is + `Nullable(...)`; otherwise the query fails with *Cannot convert NULL value to non-Nullable + type*. + +The `Function` and `BiFunction` overloads cast each argument to the lambda's parameter type, so a +lambda declared with the wrong type fails the query with a `ClassCastException`: `(Integer x) ->` +for an `Int64` parameter is the usual one. + +## NULL arguments + +By default chDB keeps NULLs away from the function: a row with a NULL in any argument yields +NULL without the function being called, and the result type becomes `Nullable` whenever an +argument can be NULL. A batch of nothing but NULLs is not evaluated at all. + +`withSpecialNullHandling()` passes them instead, as Java `null`, and keeps the return type +exactly as declared, so the function decides what a NULL means: + +```java +ChdbFunctions.scalarFunction() + .withName("is_missing") + .withParameter("String") + .withReturnType("Bool") + .withSpecialNullHandling() + .withFunction((String s) -> s == null || s.isEmpty()) + .register(connection); +``` + +With it, an argument that can be NULL needs a declared type that can hold one: an `Array` +parameter, which cannot be `Nullable`, then refuses a NULL argument at query time. + +This is the opposite default from duckdb-java, whose Java functions see NULLs unless +`withNullInNullOut()` is called. + +## Volatile functions + +Without `withVolatile()` a function is taken to return the same result for the same arguments +within a query, so chDB may evaluate a call with constant arguments -- or with none -- once and +use the value for every row. `withVolatile()` marks a function like `rand()`, which is called for +every row: + +```java +AtomicLong counter = new AtomicLong(); +ChdbFunctions.scalarFunction() + .withName("next_id") + .withReturnType("Int64") + .withVolatile() + .withFunction(counter::incrementAndGet) + .register(connection); +// SELECT next_id() FROM numbers(3) -> 1, 2, 3; without withVolatile() the call is folded: 1, 1, 1 +``` + +chDB never reuses a result across queries, since a function can be dropped and registered +again under its name. + +## Binary strings + +A `String` argument arrives as a Java `String`, so text that is not valid UTF-8 fails the query. +`withBinaryStrings()` passes `String` and `FixedString` arguments as `byte[]` instead, nested ones +included, for binary data: + +```java +ChdbFunctions.scalarFunction() + .withName("byte_length") + .withParameter("String") + .withReturnType("UInt64") + .withBinaryStrings() + .withFunction((byte[] bytes) -> (long) bytes.length) + .register(connection); +// SELECT byte_length(unhex('FF00FF')) -> 3 +``` + +A result can be a `byte[]` for a `String` or `FixedString` return type with or without it. A +`Map(String, ...)` argument then has `byte[]` keys, which a Java `Map` compares by identity: +iterate over its entries rather than looking a key up. + +## Errors + +An exception from the function fails the query, and the query's `SQLException` carries the +exception's class and message, then its causes': + +``` +Code: 754. DB::Exception: Scalar function 'no_zero' failed on a batch of 2 rows: +java.lang.IllegalArgumentException: zero is not allowed: while executing ... (UDF_EXECUTION_FAILED) +``` + +`withRowFunction` may throw checked exceptions; the `java.util.function` overloads cannot. An +`Error` -- a `StackOverflowError`, say -- is reported the same way. Nothing a function throws +reaches the engine's own threads, and the connection carries on. chDB evaluates a function only +for the rows it needs, so with the default short-circuit evaluation `if(x > 0, f(x), 0)` does +not call `f` for a row where `x <= 0`. + +## Threads + +chDB calls a function once per block of rows -- the row-at-a-time API then loops over the block +in Java -- on its own threads, and from several at once when several queries, or parallel parts +of one, use it. Each engine thread is attached to the JVM the first time it runs Java, as a +daemon so it never holds the JVM open, named after its engine thread (`QueryPipelineEx`, +`QueryPullPipeEx`, ...) in a thread dump, and detached when the engine thread exits. So: + +- **The function must be thread-safe.** Shared state needs synchronization or atomics. +- **It must not use chDB.** It runs in the middle of a query, and a statement, a new connection, + a registration or a drop started from inside it would wait for that query to finish -- on the + same connection for its statement slot, on any other inside the engine. The driver refuses all + of them with an `SQLFeatureNotSupportedException` saying so, which fails the query rather than + hanging it. Work out what the function needs before the query, or pass it in as an argument. + Handing the work to another thread and waiting for it is the one way round the check, and + deadlocks. +- Do not rely on which thread runs it. It is usually not the thread that issued the query, but + can be. + +## One registry for the whole JVM + +A function is registered with the engine, not with the connection it was registered through. +Every connection in the JVM can call it, including connections opened later, and it stays +registered after all of them close -- even across the engine shutting down and starting again -- +until it is dropped. That is the main difference from duckdb-java, where a function belongs to +the database of the connection that registered it. Registering the same name twice therefore +fails, wherever the first registration came from. + +Two ways to drop one, neither needing an open connection: + +- `ChdbFunctions.dropScalarFunction(name)` drops the function of that name, whoever registered + it, and fails if there is none. +- `register(...)` returns a `ChdbFunctions.RegisteredFunction`, which is `AutoCloseable`. Closing + it drops the function if it is still this registration under its name, and does nothing if + the name was dropped, or dropped and registered again, in the meantime; closing twice is fine. + +A query already using a function when it is dropped finishes with it. chDB releases the Java +object -- the global reference the driver holds for it, and anything a chdb-arrow function +allocated -- once nothing uses it any more, usually inside the drop call and otherwise on the +engine thread that finishes the last query using it. The engine does not release registered +functions at JVM exit, which costs nothing: the process is ending. + +## A batch at a time, with Arrow + +With the optional `chdb-arrow` module, `ArrowFunctions.scalarFunction()` declares the same thing +with an `ArrowScalarFunction` in place of a function of Java values: it receives the batch's +arguments as a `VectorSchemaRoot`, one vector per parameter in order, and returns one +`FieldVector` with as many values as the batch has rows. + +```java +ArrowFunctions.scalarFunction() + .withName("weighted") + .withParameters("Float64", "Float64") + .withReturnType("Float64") + .withFunction((arguments, allocator) -> { + Float8Vector values = (Float8Vector) arguments.getVector(0); + Float8Vector weights = (Float8Vector) arguments.getVector(1); + Float8Vector out = new Float8Vector("weighted", allocator); + out.allocateNew(arguments.getRowCount()); + for (int i = 0; i < arguments.getRowCount(); i++) { + out.set(i, values.get(i) * weights.get(i)); + } + out.setValueCount(arguments.getRowCount()); + return out; + }) + .register(connection); +``` + +Use it for types the table above leaves out, for nested results built column by column, or to +avoid a Java call and a boxed value per row. The arguments are imported through Arrow's C Data +Interface without a copy, and the result exported the same way. The vectors chDB sends are the +Arrow types its `chdb_query_arrow` produces, except that a `DateTime` is a +`TimeStampSecTZVector`, and an `Enum` or a 128- or 256-bit integer is text; with binary strings +a `String` is a `VarBinaryVector`. The result may be any Arrow type chDB converts to the +declared one, including one of the argument vectors. + +`allocator` belongs to the registration, which closes it once chDB has released the function, so +the function need not manage one. The argument root is closed when the call returns: transfer +anything you keep. Volatility, NULL handling, binary strings, errors, threads and the registry +are as above, and the `RegisteredFunction` it returns, or `ChdbFunctions.dropScalarFunction`, +drops it. + +## What is not supported + +- Aggregate and table functions: the engine's C ABI registers scalar functions only. +- Overloading a name by argument types, and variadic functions: a name has one signature. +- A Java function registered for an older engine: v26.11.2-rc.3 is the first with the ABI. diff --git a/docs/unsupported.md b/docs/unsupported.md index 9dc39d0..e98c339 100644 --- a/docs/unsupported.md +++ b/docs/unsupported.md @@ -102,7 +102,8 @@ A high-throughput streaming insert path is on the post-V1 list; the engine's C A `prepareCall()` and every `CallableStatement` method throw. ClickHouse has no stored procedures. -**Instead:** a `CREATE FUNCTION` UDF called from `SELECT`, or a parameterized view. +**Instead:** a `CREATE FUNCTION` UDF called from `SELECT`, a function written in Java and +registered with `ChdbFunctions` ([scalar functions](scalar-functions.md)), or a parameterized view. ## Generated keys diff --git a/docs/upstream-findings.md b/docs/upstream-findings.md index 7dea3b1..408e6ed 100644 --- a/docs/upstream-findings.md +++ b/docs/upstream-findings.md @@ -48,6 +48,8 @@ pinned for the scalar function ABI (chdb-core #352): - **§2's table gained a sixth column**: at the tag the in-tree constant reads `26.11.1`, one release behind the tarball again. +- **§6 gained two symbols**: `chdb_create_scalar_function` and `chdb_drop_scalar_function` are + optional the same way, for Java scalar functions. The rest still hold on the new engine, and the tests named against each are what demonstrates that — they run in `mvn verify` against whichever engine is pinned. @@ -400,6 +402,15 @@ degrade rather than fail the load: - no `chdb_shutdown`: `ChdbNative.shutdown()` returns 2, and the engine threads are reaped by process exit as they always were. +The scalar function ABI, `chdb_create_scalar_function` and `chdb_drop_scalar_function`, arrived +in v26.11.2-rc.3 -- v26.11.1 exports 62 `chdb_*` symbols, v26.11.2-rc.3 the same 62 and these +two, on all four platforms -- and is resolved the same way, for the same reason: + +- no scalar function ABI: `ChdbFunctions.isScalarFunctionSupported()` is false, and registering + a function throws an `SQLFeatureNotSupportedException` naming the release that has it. The + loader still loads the engine, and everything else runs. Measured by pointing the loader at + the v26.11.1 release library with `-Dchdb.skipEngineVersionCheck=true`. + `chdb_shutdown()` turned out to be narrower than issue #8 assumed — see §9. --- diff --git a/docs/v1-progress.md b/docs/v1-progress.md index 62cc87d..1a54a1e 100644 --- a/docs/v1-progress.md +++ b/docs/v1-progress.md @@ -59,7 +59,7 @@ consumer check completed after upload. | ✅ | Direct JNI is the mainline, ADBC the experiment | no Arrow Java dependency anywhere | | ✅ | Engine release, dynamic-library checksum and symbol set pinned | `scripts/engine.properties`, SHA-256 per platform from the GitHub release digests | | 🟡 | Consistency check across `chdb_version()`, tag and header version | The v26.11.2-rc.3 release tarball header is now vendored byte-for-byte and reports `26.11.2-rc.3`, identical in all four platform tarballs; the Linux x86_64 runtime agrees. The other platforms need CI confirmation. The `26.5.1-rc.3` constant blamed on upstream turned out to be ours: the vendored header had been copied from chdb-core's source tree instead of its release tarball — [findings §2](upstream-findings.md). Still enforced against `engine.properties` rather than the header | -| ✅ | C API split into required and optional symbols | 18 required, linker- and load-checked; `chdb_classify_query_n` and `chdb_shutdown` optional via `dlsym`, and present on the current baseline | +| ✅ | C API split into required and optional symbols | 18 required, linker- and load-checked; `chdb_classify_query_n`, `chdb_shutdown`, `chdb_create_scalar_function` and `chdb_drop_scalar_function` optional via `dlsym`, and present on the current baseline | | ⬜ | C ABI version and compatibility promise confirmed with Core | needs upstream agreement | | ✅ | Signal-handler requirement raised upstream | reproduced, measured and written up in [findings §1](upstream-findings.md), filed as chdb-core #221, and fixed by chdb-core #224 in engine v26.7.3 — the shim's guard now reports no handler to repair, and `run-signal-window-test.sh measure` reports zero | diff --git a/pom.xml b/pom.xml index 1775fcd..9df42e9 100644 --- a/pom.xml +++ b/pom.xml @@ -68,7 +68,7 @@ 26.11.2-rc.3 1 - 5 + 6 1 19.0.0 From 7952e01affc03d5f1d4a7f673209fc9201bb82e3 Mon Sep 17 00:00:00 2001 From: wudidapaopao Date: Wed, 2 Dec 2026 02:57:26 +0000 Subject: [PATCH 3/4] Name the Arrow batch method as duckdb-java does 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) --- chdb-arrow/README.md | 2 +- .../java/org/chdb/arrow/ArrowFunctions.java | 2 +- .../org/chdb/arrow/ArrowScalarFunction.java | 2 +- .../arrow/ArrowScalarFunctionBuilder.java | 6 ++-- .../org/chdb/arrow/ArrowFunctionsTest.java | 32 +++++++++---------- docs/scalar-functions.md | 2 +- 6 files changed, 23 insertions(+), 23 deletions(-) diff --git a/chdb-arrow/README.md b/chdb-arrow/README.md index dfc6c4b..c3a74be 100644 --- a/chdb-arrow/README.md +++ b/chdb-arrow/README.md @@ -187,7 +187,7 @@ try (Connection connection = DriverManager.getConnection("jdbc:chdb::memory:")) .withName("add") .withParameters("Int64", "Int64") .withReturnType("Int64") - .withFunction((arguments, allocator) -> { + .withVectorizedFunction((arguments, allocator) -> { BigIntVector left = (BigIntVector) arguments.getVector(0); BigIntVector right = (BigIntVector) arguments.getVector(1); BigIntVector sum = new BigIntVector("sum", allocator); diff --git a/chdb-arrow/src/main/java/org/chdb/arrow/ArrowFunctions.java b/chdb-arrow/src/main/java/org/chdb/arrow/ArrowFunctions.java index 54fd7cb..62fecc3 100644 --- a/chdb-arrow/src/main/java/org/chdb/arrow/ArrowFunctions.java +++ b/chdb-arrow/src/main/java/org/chdb/arrow/ArrowFunctions.java @@ -8,7 +8,7 @@ * .withName("weighted") * .withParameters("Float64", "Float64") * .withReturnType("Float64") - * .withFunction((arguments, allocator) -> { + * .withVectorizedFunction((arguments, allocator) -> { * Float8Vector values = (Float8Vector) arguments.getVector(0); * Float8Vector weights = (Float8Vector) arguments.getVector(1); * Float8Vector out = new Float8Vector("weighted", allocator); diff --git a/chdb-arrow/src/main/java/org/chdb/arrow/ArrowScalarFunction.java b/chdb-arrow/src/main/java/org/chdb/arrow/ArrowScalarFunction.java index 5f1bb14..5c9d6fc 100644 --- a/chdb-arrow/src/main/java/org/chdb/arrow/ArrowScalarFunction.java +++ b/chdb-arrow/src/main/java/org/chdb/arrow/ArrowScalarFunction.java @@ -6,7 +6,7 @@ /** * A scalar function computed one batch of rows at a time, with Arrow vectors. Registered with - * {@link ArrowScalarFunctionBuilder#withFunction}. + * {@link ArrowScalarFunctionBuilder#withVectorizedFunction}. * *

    chDB calls it from several of its own threads at once, so it must be safe for concurrent * use, and it runs inside a query, so it must not use chDB. diff --git a/chdb-arrow/src/main/java/org/chdb/arrow/ArrowScalarFunctionBuilder.java b/chdb-arrow/src/main/java/org/chdb/arrow/ArrowScalarFunctionBuilder.java index 1ec50f4..9df877b 100644 --- a/chdb-arrow/src/main/java/org/chdb/arrow/ArrowScalarFunctionBuilder.java +++ b/chdb-arrow/src/main/java/org/chdb/arrow/ArrowScalarFunctionBuilder.java @@ -86,8 +86,8 @@ public ArrowScalarFunctionBuilder withBinaryStrings() { return this; } - /** The function. */ - public ArrowScalarFunctionBuilder withFunction(ArrowScalarFunction function) { + /** The function, called once per batch: {@code withVectorizedFunction} in duckdb-java. */ + public ArrowScalarFunctionBuilder withVectorizedFunction(ArrowScalarFunction function) { this.function = Objects.requireNonNull(function, "function"); return this; } @@ -105,7 +105,7 @@ public ChdbFunctions.RegisteredFunction register(Connection connection) throws S Objects.requireNonNull(connection, "connection"); if (name == null || returnType == null || function == null) { throw new IllegalStateException( - "a scalar function needs withName, withReturnType and withFunction before register"); + "a scalar function needs withName, withReturnType and withVectorizedFunction before register"); } ChdbConnection chdb; try { diff --git a/chdb-arrow/src/test/java/org/chdb/arrow/ArrowFunctionsTest.java b/chdb-arrow/src/test/java/org/chdb/arrow/ArrowFunctionsTest.java index 02c5072..9622e0c 100644 --- a/chdb-arrow/src/test/java/org/chdb/arrow/ArrowFunctionsTest.java +++ b/chdb-arrow/src/test/java/org/chdb/arrow/ArrowFunctionsTest.java @@ -98,7 +98,7 @@ private static BigIntVector longs(BufferAllocator allocator, int rows) { @Test void addsBatchesAcrossTheEngineThreads() throws SQLException { AtomicInteger batches = new AtomicInteger(); - register(function("a_add", "Int64", "Int64", "Int64").withFunction((arguments, allocator) -> { + register(function("a_add", "Int64", "Int64", "Int64").withVectorizedFunction((arguments, allocator) -> { batches.incrementAndGet(); BigIntVector left = (BigIntVector) arguments.getVector(0); BigIntVector right = (BigIntVector) arguments.getVector(1); @@ -123,8 +123,8 @@ void zeroArgumentFunctionsAndVolatility() throws SQLException { } return out; }; - register(function("a_next", "Int64").withFunction(next)); - register(function("a_next_volatile", "Int64").withVolatile().withFunction(next)); + register(function("a_next", "Int64").withVectorizedFunction(next)); + register(function("a_next_volatile", "Int64").withVolatile().withVectorizedFunction(next)); assertEquals(Arrays.asList("1"), query("SELECT count(DISTINCT a_next()) FROM numbers(5)")); assertEquals(Arrays.asList("5"), query("SELECT count(DISTINCT a_next_volatile()) FROM numbers(5)")); } @@ -132,14 +132,14 @@ void zeroArgumentFunctionsAndVolatility() throws SQLException { @Test void stringsBinaryStringsAndReturningAnArgument() throws SQLException { AtomicReference> argument = new AtomicReference<>(); - register(function("a_echo", "String", "String").withFunction((arguments, allocator) -> { + register(function("a_echo", "String", "String").withVectorizedFunction((arguments, allocator) -> { argument.set(arguments.getVector(0).getClass()); return (FieldVector) arguments.getVector(0); })); assertEquals(Arrays.asList("0", "héllo"), query("SELECT a_echo(arrayJoin(['0', 'héllo']))")); assertEquals(VarCharVector.class, argument.get()); - register(function("a_byte_length", "UInt64", "String").withBinaryStrings().withFunction((arguments, allocator) -> { + register(function("a_byte_length", "UInt64", "String").withBinaryStrings().withVectorizedFunction((arguments, allocator) -> { argument.set(arguments.getVector(0).getClass()); VarBinaryVector bytes = (VarBinaryVector) arguments.getVector(0); UInt8Vector out = new UInt8Vector("out", allocator); @@ -157,7 +157,7 @@ void stringsBinaryStringsAndReturningAnArgument() throws SQLException { @Test void nullHandling() throws SQLException { AtomicLong nullsSeen = new AtomicLong(); - register(function("a_plus_one", "Int64", "Int64").withFunction((arguments, allocator) -> { + register(function("a_plus_one", "Int64", "Int64").withVectorizedFunction((arguments, allocator) -> { BigIntVector in = (BigIntVector) arguments.getVector(0); nullsSeen.addAndGet(in.getNullCount()); BigIntVector out = longs(allocator, arguments.getRowCount()); @@ -170,7 +170,7 @@ void nullHandling() throws SQLException { query("SELECT a_plus_one(if(number % 2 = 0, NULL, toInt64(number))) FROM numbers(4)")); assertEquals(0, nullsSeen.get(), "a row with a NULL argument does not reach the function by default"); - register(function("a_is_null", "Bool", "Int64").withSpecialNullHandling().withFunction((arguments, allocator) -> { + register(function("a_is_null", "Bool", "Int64").withSpecialNullHandling().withVectorizedFunction((arguments, allocator) -> { FieldVector in = arguments.getVector(0); BitVector out = new BitVector("out", allocator); out.allocateNew(arguments.getRowCount()); @@ -187,7 +187,7 @@ void nullHandling() throws SQLException { @Test void nestedAndTemporalArgumentsArriveAsArrowTypes() throws SQLException { - register(function("a_array_sum", "Int64", "Array(Int64)").withFunction((arguments, allocator) -> { + register(function("a_array_sum", "Int64", "Array(Int64)").withVectorizedFunction((arguments, allocator) -> { ListVector lists = (ListVector) arguments.getVector(0); BigIntVector elements = (BigIntVector) lists.getDataVector(); BigIntVector out = longs(allocator, arguments.getRowCount()); @@ -203,7 +203,7 @@ void nestedAndTemporalArgumentsArriveAsArrowTypes() throws SQLException { assertEquals(Arrays.asList("6", "0"), query("SELECT a_array_sum(arrayJoin([[1, 2, 3], []]))")); AtomicReference zone = new AtomicReference<>(); - register(function("a_seconds", "Int64", "DateTime('Asia/Shanghai')", "Date").withFunction((arguments, allocator) -> { + register(function("a_seconds", "Int64", "DateTime('Asia/Shanghai')", "Date").withVectorizedFunction((arguments, allocator) -> { TimeStampSecTZVector times = (TimeStampSecTZVector) arguments.getVector(0); DateDayVector days = (DateDayVector) arguments.getVector(1); zone.set(times.getTimeZone()); @@ -221,7 +221,7 @@ void nestedAndTemporalArgumentsArriveAsArrowTypes() throws SQLException { @Test void resultsConvertToTheDeclaredType() throws SQLException { // Any Arrow type chDB converts without loss: a float64 for Float32, text for a Decimal. - register(function("a_third", "Float32", "Float64").withFunction((arguments, allocator) -> { + register(function("a_third", "Float32", "Float64").withVectorizedFunction((arguments, allocator) -> { Float8Vector in = (Float8Vector) arguments.getVector(0); Float8Vector out = new Float8Vector("out", allocator); out.allocateNew(arguments.getRowCount()); @@ -232,7 +232,7 @@ void resultsConvertToTheDeclaredType() throws SQLException { return out; })); assertEquals(Arrays.asList("Float32"), query("SELECT toTypeName(a_third(1))")); - register(function("a_price", "Decimal(10, 2)", "Int64").withFunction((arguments, allocator) -> { + register(function("a_price", "Decimal(10, 2)", "Int64").withVectorizedFunction((arguments, allocator) -> { VarCharVector out = new VarCharVector("out", allocator); out.allocateNew(arguments.getRowCount()); for (int i = 0; i < arguments.getRowCount(); i++) { @@ -246,11 +246,11 @@ void resultsConvertToTheDeclaredType() throws SQLException { @Test void failuresBecomeQueryErrors() throws SQLException { - register(function("a_throws", "Int64", "Int64").withFunction((arguments, allocator) -> { + register(function("a_throws", "Int64", "Int64").withVectorizedFunction((arguments, allocator) -> { throw new IllegalStateException("no batches today"); })); - register(function("a_null", "Int64", "Int64").withFunction((arguments, allocator) -> null)); - register(function("a_long", "Int64", "Int64").withFunction((arguments, allocator) -> + register(function("a_null", "Int64", "Int64").withVectorizedFunction((arguments, allocator) -> null)); + register(function("a_long", "Int64", "Int64").withVectorizedFunction((arguments, allocator) -> longs(allocator, arguments.getRowCount() + 1))); SQLException thrown = assertThrows(SQLException.class, () -> query("SELECT a_throws(1)")); assertTrue(thrown.getMessage().contains("java.lang.IllegalStateException: no batches today"), thrown.getMessage()); @@ -263,7 +263,7 @@ void failuresBecomeQueryErrors() throws SQLException { @Test void concurrentQueriesShareTheFunction() throws Exception { - register(function("a_double", "Int64", "Int64").withFunction((arguments, allocator) -> { + register(function("a_double", "Int64", "Int64").withVectorizedFunction((arguments, allocator) -> { BigIntVector in = (BigIntVector) arguments.getVector(0); BigIntVector out = longs(allocator, arguments.getRowCount()); for (int i = 0; i < arguments.getRowCount(); i++) { @@ -296,7 +296,7 @@ void concurrentQueriesShareTheFunction() throws Exception { @Test void theAllocatorIsEmptyOnceTheFunctionIsDropped() throws SQLException { AtomicReference used = new AtomicReference<>(); - RegisteredFunction function = function("a_length", "Int64", "String").withFunction((arguments, allocator) -> { + RegisteredFunction function = function("a_length", "Int64", "String").withVectorizedFunction((arguments, allocator) -> { used.set(allocator); VarCharVector in = (VarCharVector) arguments.getVector(0); BigIntVector out = longs(allocator, arguments.getRowCount()); diff --git a/docs/scalar-functions.md b/docs/scalar-functions.md index 30e996a..a8892d4 100644 --- a/docs/scalar-functions.md +++ b/docs/scalar-functions.md @@ -257,7 +257,7 @@ ArrowFunctions.scalarFunction() .withName("weighted") .withParameters("Float64", "Float64") .withReturnType("Float64") - .withFunction((arguments, allocator) -> { + .withVectorizedFunction((arguments, allocator) -> { Float8Vector values = (Float8Vector) arguments.getVector(0); Float8Vector weights = (Float8Vector) arguments.getVector(1); Float8Vector out = new Float8Vector("weighted", allocator); From 8403d3bbdefc1ead5a83f0f23f9a3f143df84ea0 Mon Sep 17 00:00:00 2001 From: wudidapaopao Date: Wed, 2 Dec 2026 03:25:13 +0000 Subject: [PATCH 4/4] Test scalar functions without an engine, and fix what the tests found 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) --- .../org/chdb/arrow/ArrowFunctionCallback.java | 5 +- .../arrow/ArrowScalarFunctionBuilder.java | 5 + .../chdb/arrow/ArrowFunctionCallbackTest.java | 215 ++++++++++++++++ .../arrow/ArrowScalarFunctionBuilderTest.java | 71 ++++++ .../java/org/chdb/it/ScalarFunctionIT.java | 4 +- .../java/org/chdb/internal/ArrowDecoder.java | 18 +- .../chdb/internal/ScalarFunctionCallback.java | 14 +- .../java/org/chdb/jdbc/ChdbFunctions.java | 80 ++++-- .../chdb/jdbc/ChdbScalarFunctionBuilder.java | 5 + .../org/chdb/jdbc/RowFunctionCallback.java | 9 +- .../java/org/chdb/internal/ArrowColumns.java | 38 +++ .../org/chdb/internal/ArrowDecoderTest.java | 234 ++++++++++++++++++ .../org/chdb/internal/ArrowEncoderTest.java | 196 +++++++++++++++ .../internal/ScalarFunctionCallbackTest.java | 88 ++++++- .../java/org/chdb/jdbc/ChdbFunctionsTest.java | 81 ++++++ .../jdbc/ChdbScalarFunctionBuilderTest.java | 27 ++ .../chdb/jdbc/RowFunctionCallbackTest.java | 120 +++++++++ chdb-jni/test/chdb_jni_test.cpp | 196 ++++++++++++++- docs/scalar-functions.md | 6 +- 19 files changed, 1370 insertions(+), 42 deletions(-) create mode 100644 chdb-arrow/src/test/java/org/chdb/arrow/ArrowFunctionCallbackTest.java create mode 100644 chdb-arrow/src/test/java/org/chdb/arrow/ArrowScalarFunctionBuilderTest.java create mode 100644 chdb-jdbc/src/test/java/org/chdb/internal/ArrowColumns.java create mode 100644 chdb-jdbc/src/test/java/org/chdb/jdbc/ChdbFunctionsTest.java create mode 100644 chdb-jdbc/src/test/java/org/chdb/jdbc/RowFunctionCallbackTest.java diff --git a/chdb-arrow/src/main/java/org/chdb/arrow/ArrowFunctionCallback.java b/chdb-arrow/src/main/java/org/chdb/arrow/ArrowFunctionCallback.java index b0d90f9..bf8521f 100644 --- a/chdb-arrow/src/main/java/org/chdb/arrow/ArrowFunctionCallback.java +++ b/chdb-arrow/src/main/java/org/chdb/arrow/ArrowFunctionCallback.java @@ -53,8 +53,9 @@ protected void apply(long argumentSchema, long arguments, long resultSchema, lon @Override protected void release() { - // Throws if a function kept a buffer past its call -- a transferred argument it never - // closed -- and the allocator then stays open with it rather than freeing memory in use. + // Throws if a function still holds a buffer from it -- an argument it transferred and never + // closed -- and frees nothing that is in use. destroyed() swallows the exception: chDB has + // let go of the function by then, and there is nobody left to tell. allocator.close(); } } diff --git a/chdb-arrow/src/main/java/org/chdb/arrow/ArrowScalarFunctionBuilder.java b/chdb-arrow/src/main/java/org/chdb/arrow/ArrowScalarFunctionBuilder.java index 9df877b..ae202ba 100644 --- a/chdb-arrow/src/main/java/org/chdb/arrow/ArrowScalarFunctionBuilder.java +++ b/chdb-arrow/src/main/java/org/chdb/arrow/ArrowScalarFunctionBuilder.java @@ -129,6 +129,11 @@ public ChdbFunctions.RegisteredFunction register(Connection connection) throws S } } + /** The {@code ScalarFunctionCallback} flag bits declared so far. For tests. */ + int flags() { + return flags; + } + private static String typeName(String clickHouseType) { Objects.requireNonNull(clickHouseType, "clickHouseType"); if (clickHouseType.trim().isEmpty()) { diff --git a/chdb-arrow/src/test/java/org/chdb/arrow/ArrowFunctionCallbackTest.java b/chdb-arrow/src/test/java/org/chdb/arrow/ArrowFunctionCallbackTest.java new file mode 100644 index 0000000..9944e1b --- /dev/null +++ b/chdb-arrow/src/test/java/org/chdb/arrow/ArrowFunctionCallbackTest.java @@ -0,0 +1,215 @@ +package org.chdb.arrow; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.Buffer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; +import org.apache.arrow.c.ArrowArray; +import org.apache.arrow.c.ArrowSchema; +import org.apache.arrow.c.Data; +import org.apache.arrow.memory.BufferAllocator; +import org.apache.arrow.memory.RootAllocator; +import org.apache.arrow.vector.BigIntVector; +import org.apache.arrow.vector.FieldVector; +import org.apache.arrow.vector.VectorSchemaRoot; +import org.apache.arrow.vector.types.pojo.Schema; +import org.apache.arrow.vector.util.TransferPair; +import org.chdb.internal.ScalarFunctionException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIf; + +/** + * A batch through {@link ArrowFunctionCallback} the way chDB passes one, without an engine: the + * test plays chDB, exporting the arguments into C Data structs and importing the result from + * them. Its allocator stands for chDB's memory, so closing it afterwards fails any test whose + * callback kept an argument or a result buffer it had to give back. + * + *

    Needs {@code --add-opens=java.base/java.nio=ALL-UNNAMED}, as every Arrow test here does. + */ +@EnabledIf("arrowCanAllocate") +class ArrowFunctionCallbackTest { + + private BufferAllocator chdb; + + /** Arrow's allocator reads java.nio internals, which a JVM since 16 opens only when asked. */ + static boolean arrowCanAllocate() { + return Buffer.class.getModule().isOpen("java.nio", ArrowFunctionCallbackTest.class.getModule()); + } + + @BeforeEach + void open() { + chdb = new RootAllocator(); + } + + @AfterEach + void everythingWasGivenBack() { + chdb.close(); + } + + /** + * Runs one batch: exports {@code arguments}, calls the callback with the structs' addresses, + * releases what it left in the argument structs, as chDB does, and imports the result. + */ + private FieldVector call(ArrowFunctionCallback callback, VectorSchemaRoot arguments) throws Exception { + try (ArrowArray array = ArrowArray.allocateNew(chdb); + ArrowSchema schema = ArrowSchema.allocateNew(chdb); + ArrowArray result = ArrowArray.allocateNew(chdb); + ArrowSchema resultSchema = ArrowSchema.allocateNew(chdb)) { + Data.exportVectorSchemaRoot(chdb, arguments, null, array, schema); + try { + callback.apply(schema.memoryAddress(), array.memoryAddress(), resultSchema.memoryAddress(), result.memoryAddress()); + } catch (Exception e) { + assertEquals(0, result.snapshot().release, "a failed batch leaves the result structs empty"); + throw e; + } finally { + assertEquals(0, array.snapshot().release, "the callback took the arguments over"); + array.release(); + schema.release(); + } + return Data.importVector(chdb, result, resultSchema, null); + } + } + + private VectorSchemaRoot longs(long... values) { + BigIntVector vector = new BigIntVector("c0", chdb); + vector.allocateNew(values.length); + for (int i = 0; i < values.length; i++) { + vector.set(i, values[i]); + } + vector.setValueCount(values.length); + VectorSchemaRoot root = VectorSchemaRoot.of(vector); + root.setRowCount(values.length); + return root; + } + + private static BigIntVector longs(BufferAllocator allocator, int rows, long value) { + BigIntVector out = new BigIntVector("out", allocator); + out.allocateNew(rows); + for (int i = 0; i < rows; i++) { + out.set(i, value); + } + out.setValueCount(rows); + return out; + } + + private static List values(FieldVector vector) { + List out = new ArrayList<>(); + for (int i = 0; i < vector.getValueCount(); i++) { + out.add(vector.getObject(i)); + } + return out; + } + + @Test + void aBatchIsImportedComputedAndExported() throws Exception { + AtomicReference own = new AtomicReference<>(); + ArrowFunctionCallback plusOne = new ArrowFunctionCallback((arguments, allocator) -> { + own.set(allocator); + BigIntVector in = (BigIntVector) arguments.getVector(0); + BigIntVector out = longs(allocator, arguments.getRowCount(), 0); + for (int i = 0; i < arguments.getRowCount(); i++) { + out.set(i, in.get(i) + 1); + } + return out; + }); + try (VectorSchemaRoot arguments = longs(1, 2, 3); FieldVector result = call(plusOne, arguments)) { + assertEquals(Arrays.asList(2L, 3L, 4L), values(result)); + assertTrue(own.get().getAllocatedMemory() > 0, "the result is the callback's until chDB releases it"); + } + assertEquals(0, own.get().getAllocatedMemory(), "releasing the result gave everything back"); + plusOne.abandon(); + } + + @Test + void aBatchWithoutArgumentsKeepsItsRowCount() throws Exception { + ArrowFunctionCallback rows = new ArrowFunctionCallback((arguments, allocator) -> { + assertEquals(0, arguments.getFieldVectors().size()); + return longs(allocator, arguments.getRowCount(), arguments.getRowCount()); + }); + try (VectorSchemaRoot none = new VectorSchemaRoot(new Schema(Collections.emptyList()), Collections.emptyList(), 3); + FieldVector result = call(rows, none)) { + assertEquals(Arrays.asList(3L, 3L, 3L), values(result)); + } + rows.abandon(); + } + + @Test + void anArgumentCanBeTheResult() throws Exception { + ArrowFunctionCallback identity = new ArrowFunctionCallback((arguments, allocator) -> (FieldVector) arguments.getVector(0)); + FieldVector result; + try (VectorSchemaRoot arguments = longs(7, 9)) { + result = call(identity, arguments); + } + // The arguments' own buffers, outliving both the batch and the root they came from. + try (FieldVector kept = result) { + assertEquals(Arrays.asList(7L, 9L), values(kept)); + } + identity.abandon(); + } + + @Test + void aResultOfTheWrongLengthOrNoneFailsTheBatch() throws Exception { + AtomicReference own = new AtomicReference<>(); + ArrowFunctionCallback tooLong = new ArrowFunctionCallback((arguments, allocator) -> { + own.set(allocator); + return longs(allocator, arguments.getRowCount() + 1, 0); + }); + ArrowFunctionCallback nothing = new ArrowFunctionCallback((arguments, allocator) -> null); + try (VectorSchemaRoot arguments = longs(1)) { + ScalarFunctionException e = assertThrows(ScalarFunctionException.class, () -> call(tooLong, arguments)); + assertEquals("the function returned 2 values for a batch of 1 rows", e.getMessage()); + assertEquals(0, own.get().getAllocatedMemory(), "the refused vector was closed"); + } + try (VectorSchemaRoot arguments = longs(1)) { + ScalarFunctionException e = assertThrows(ScalarFunctionException.class, () -> call(nothing, arguments)); + assertEquals("the function returned null instead of a vector", e.getMessage()); + } + tooLong.abandon(); + nothing.abandon(); + } + + @Test + void anExceptionGivesTheArgumentsBack() throws Exception { + IllegalStateException thrown = new IllegalStateException("no batches today"); + ArrowFunctionCallback failing = new ArrowFunctionCallback((arguments, allocator) -> { + throw thrown; + }); + try (VectorSchemaRoot arguments = longs(1, 2)) { + assertSame(thrown, assertThrows(IllegalStateException.class, () -> call(failing, arguments))); + } + failing.abandon(); + } + + @Test + void aTransferredArgumentOutlivesTheBatchUntilClosed() throws Exception { + AtomicReference own = new AtomicReference<>(); + AtomicReference kept = new AtomicReference<>(); + ArrowFunctionCallback keeping = new ArrowFunctionCallback((arguments, allocator) -> { + own.set(allocator); + TransferPair transfer = arguments.getVector(0).getTransferPair(allocator); + transfer.transfer(); + kept.set((FieldVector) transfer.getTo()); + return longs(allocator, arguments.getRowCount(), 0); + }); + try (VectorSchemaRoot arguments = longs(42); FieldVector result = call(keeping, arguments)) { + assertEquals(Collections.singletonList(0L), values(result)); + } + // chDB has released the batch, and the transferred argument is still there to read. + try (FieldVector buffer = kept.get()) { + assertEquals(Collections.singletonList(42L), values(buffer)); + assertTrue(own.get().getAllocatedMemory() > 0); + } + // Closed, it went back to chDB, and the registration's allocator closes without complaint. + assertEquals(0, own.get().getAllocatedMemory()); + keeping.release(); + } +} diff --git a/chdb-arrow/src/test/java/org/chdb/arrow/ArrowScalarFunctionBuilderTest.java b/chdb-arrow/src/test/java/org/chdb/arrow/ArrowScalarFunctionBuilderTest.java new file mode 100644 index 0000000..3e97062 --- /dev/null +++ b/chdb-arrow/src/test/java/org/chdb/arrow/ArrowScalarFunctionBuilderTest.java @@ -0,0 +1,71 @@ +package org.chdb.arrow; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.lang.reflect.Proxy; +import java.sql.Connection; +import java.sql.SQLException; +import org.chdb.internal.ScalarFunctionCallback; +import org.junit.jupiter.api.Test; + +/** + * What the Arrow builder refuses before it reaches a connection. Runs without an engine, and + * without the JVM options Arrow's allocator needs: every check here comes before one is created. + */ +class ArrowScalarFunctionBuilderTest { + + /** A Connection that is not a chDB one, failing anything but unwrap. */ + private static final Connection FOREIGN = (Connection) Proxy.newProxyInstance( + ArrowScalarFunctionBuilderTest.class.getClassLoader(), + new Class[] {Connection.class}, + (proxy, method, args) -> { + if (method.getName().equals("unwrap")) { + throw new SQLException("not a wrapper"); + } + throw new AssertionError("unexpected call to " + method.getName()); + }); + + private static final ArrowScalarFunction NOTHING = (arguments, allocator) -> null; + + private static ArrowScalarFunctionBuilder complete() { + return ArrowFunctions.scalarFunction().withName("f").withParameter("Int64").withReturnType("Int64") + .withVectorizedFunction(NOTHING); + } + + @Test + void aNameAReturnTypeAndAFunctionAreRequired() { + IllegalStateException e = assertThrows(IllegalStateException.class, () -> ArrowFunctions.scalarFunction() + .withParameter("Int64").withReturnType("Int64").withVectorizedFunction(NOTHING).register(FOREIGN)); + assertTrue(e.getMessage().contains("withVectorizedFunction"), e.getMessage()); + assertThrows(IllegalStateException.class, () -> ArrowFunctions.scalarFunction().withName("f") + .withVectorizedFunction(NOTHING).register(FOREIGN)); + assertThrows(IllegalStateException.class, () -> ArrowFunctions.scalarFunction().withName("f") + .withReturnType("Int64").register(FOREIGN)); + assertThrows(IllegalArgumentException.class, () -> ArrowFunctions.scalarFunction().withName("")); + assertThrows(IllegalArgumentException.class, () -> ArrowFunctions.scalarFunction().withParameters("Int64", " ")); + assertThrows(NullPointerException.class, () -> ArrowFunctions.scalarFunction().withVectorizedFunction(null)); + assertThrows(NullPointerException.class, () -> complete().register(null)); + } + + @Test + void eachOptionSetsItsOwnFlag() { + assertEquals(0, complete().flags()); + assertEquals(ScalarFunctionCallback.VOLATILE, complete().withVolatile().withVolatile().flags()); + assertEquals(ScalarFunctionCallback.SPECIAL_NULL_HANDLING, complete().withSpecialNullHandling().flags()); + assertEquals(ScalarFunctionCallback.BINARY_STRINGS, complete().withBinaryStrings().flags()); + assertEquals(ScalarFunctionCallback.VOLATILE | ScalarFunctionCallback.SPECIAL_NULL_HANDLING + | ScalarFunctionCallback.BINARY_STRINGS, + complete().withSpecialNullHandling().withBinaryStrings().withVolatile().flags()); + } + + @Test + void registrationNeedsAChdbConnection() { + SQLException e = assertThrows(SQLException.class, () -> complete().register(FOREIGN)); + assertTrue(e.getMessage().contains("chDB connection"), e.getMessage()); + assertTrue(e.getMessage().contains(FOREIGN.getClass().getName()), e.getMessage()); + assertEquals("HY000", e.getSQLState()); + assertEquals("not a wrapper", e.getCause().getMessage()); + } +} diff --git a/chdb-integration-tests/src/test/java/org/chdb/it/ScalarFunctionIT.java b/chdb-integration-tests/src/test/java/org/chdb/it/ScalarFunctionIT.java index b476e9c..2aacd11 100644 --- a/chdb-integration-tests/src/test/java/org/chdb/it/ScalarFunctionIT.java +++ b/chdb-integration-tests/src/test/java/org/chdb/it/ScalarFunctionIT.java @@ -190,9 +190,11 @@ void boolsAndStrings() throws SQLException { })); assertEquals(Arrays.asList("00FF01"), query("SELECT hex(j_reverse_bytes(unhex('01FF00')))")); - // A FixedString keeps its padding. + // A FixedString keeps its padding, and fails like a String when it is not valid UTF-8: + // chDB passes its bytes unchecked, so the driver checks them. register(function("j_length", "UInt64", "FixedString(4)").withFunction((String s) -> (long) s.length())); assertEquals(Arrays.asList("4"), query("SELECT j_length(toFixedString('ab', 4))")); + assertContains("a FixedString argument is not valid UTF-8", failure("SELECT j_length(toFixedString(unhex('FFFE'), 4))")); } @Test diff --git a/chdb-jdbc/src/main/java/org/chdb/internal/ArrowDecoder.java b/chdb-jdbc/src/main/java/org/chdb/internal/ArrowDecoder.java index a70b60a..e493545 100644 --- a/chdb-jdbc/src/main/java/org/chdb/internal/ArrowDecoder.java +++ b/chdb-jdbc/src/main/java/org/chdb/internal/ArrowDecoder.java @@ -6,6 +6,8 @@ import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.ByteOrder; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CharsetDecoder; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.time.LocalDate; @@ -229,7 +231,8 @@ private static Reader variable(ArrowColumn column, ClickHouseType.Kind kind, boo /** UUID, IPv6 and FixedString(N) all arrive as N bytes of fixed-size binary. */ private static Reader fixedBinary(ArrowColumn column, ClickHouseType.Kind kind, boolean binaryStrings) { int width = Integer.parseInt(column.format.substring(2)); - byte[] data = column.buffers[1]; + // An array of no rows may leave its buffer out, which the UUID reader below would wrap. + byte[] data = column.buffers[1] == null ? new byte[0] : column.buffers[1]; int offset = column.offset; Reader bytes = row -> Arrays.copyOfRange(data, (offset + row) * width, (offset + row + 1) * width); if (width == 16 && (kind == ClickHouseType.Kind.UUID || "arrow.uuid".equals(column.extension))) { @@ -241,7 +244,18 @@ private static Reader fixedBinary(ArrowColumn column, ClickHouseType.Kind kind, return row -> address((byte[]) bytes.read(row)); } if (kind == ClickHouseType.Kind.FIXED_STRING && !binaryStrings) { - return row -> new String((byte[]) bytes.read(row), StandardCharsets.UTF_8); + // chDB fails a query whose String argument is not valid UTF-8, but sends a FixedString + // as raw bytes, so this checks it: decoding leniently would hand the function + // replacement characters instead of the value. + CharsetDecoder utf8 = StandardCharsets.UTF_8.newDecoder(); + return row -> { + try { + return utf8.decode(ByteBuffer.wrap((byte[]) bytes.read(row))).toString(); + } catch (CharacterCodingException e) { + throw new ScalarFunctionException("a FixedString argument is not valid UTF-8; register the function" + + " withBinaryStrings() to receive it as byte[]"); + } + }; } return bytes; } diff --git a/chdb-jdbc/src/main/java/org/chdb/internal/ScalarFunctionCallback.java b/chdb-jdbc/src/main/java/org/chdb/internal/ScalarFunctionCallback.java index 3187189..f9e56fe 100644 --- a/chdb-jdbc/src/main/java/org/chdb/internal/ScalarFunctionCallback.java +++ b/chdb-jdbc/src/main/java/org/chdb/internal/ScalarFunctionCallback.java @@ -58,11 +58,19 @@ public static long liveCount() { * @throws ChdbNativeException carrying chDB's error if the registration is refused */ public final void register(long connection, byte[] name, byte[][] argumentTypes, byte[] returnType, int flags) { - // Counted first: once chDB has it, a drop by name on another thread can destroy it - // before the call below even returns. + handOver(() -> ChdbNative.createScalarFunction(connection, name, argumentTypes, returnType, flags, this)); + } + + /** + * Runs {@code registration}, which hands this object to chDB, with it counted as live. Counted + * first: once chDB has it, a drop by name on another thread can destroy it before the + * registration even returns. Uncounted again if the registration throws, since chDB then never + * had it. + */ + final void handOver(Runnable registration) { LIVE.incrementAndGet(); try { - ChdbNative.createScalarFunction(connection, name, argumentTypes, returnType, flags, this); + registration.run(); } catch (RuntimeException | Error e) { LIVE.decrementAndGet(); throw e; diff --git a/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbFunctions.java b/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbFunctions.java index 8da5f52..6da4963 100644 --- a/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbFunctions.java +++ b/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbFunctions.java @@ -52,11 +52,8 @@ */ public final class ChdbFunctions { - /** - * The registrations made through this class, by name. Lets a {@link RegisteredFunction} drop - * only the registration it came from, never a later one that reused the name. - */ - private static final Map REGISTERED = new HashMap<>(); + /** The registrations made through this class, dropped through chDB. */ + private static final Registry REGISTRY = new Registry(ChdbFunctions::drop); private ChdbFunctions() { } @@ -95,12 +92,7 @@ public static void dropScalarFunction(String name) throws SQLException { Objects.requireNonNull(name, "name"); refuseInsideAFunction(); requireSupport(); - synchronized (REGISTERED) { - // Forgotten even if chDB refuses: the only refusal left is that the name is not - // registered, and then there is nothing a handle could drop either. - REGISTERED.remove(name); - drop(name); - } + REGISTRY.dropByName(name); } /** @@ -114,12 +106,8 @@ static RegisteredFunction create( String returnType, int flags, ScalarFunctionCallback callback) { - synchronized (REGISTERED) { - callback.register(connection, Utf8.encode(name), Utf8.encodeAll(argumentTypes), Utf8.encode(returnType), flags); - RegisteredFunction registered = new RegisteredFunction(name); - REGISTERED.put(name, registered); - return registered; - } + return REGISTRY.add(name, () -> callback.register( + connection, Utf8.encode(name), Utf8.encodeAll(argumentTypes), Utf8.encode(returnType), flags)); } /** Refuses before anything else when the engine lacks the ABI, with the release that has it. */ @@ -152,14 +140,62 @@ private static void drop(String name) throws SQLException { } } + /** + * The registrations made through this class, by name. Lets a {@link RegisteredFunction} drop + * only the registration it came from, never a later one that reused the name. Each operation + * holds the monitor across chDB's call and the bookkeeping, so the two cannot disagree. + */ + static final class Registry { + + /** Unregisters a name: chDB's drop, in the driver. */ + @FunctionalInterface + interface Drop { + void drop(String name) throws SQLException; + } + + private final Map byName = new HashMap<>(); + private final Drop drop; + + Registry(Drop drop) { + this.drop = drop; + } + + /** Runs {@code registration} and, unless it throws, records a handle for {@code name}. */ + synchronized RegisteredFunction add(String name, Runnable registration) { + registration.run(); + RegisteredFunction handle = new RegisteredFunction(this, name); + byName.put(name, handle); + return handle; + } + + /** Drops {@code name}, whichever handle it belongs to. */ + synchronized void dropByName(String name) throws SQLException { + // Forgotten even if chDB refuses: the only refusal left is that the name is not + // registered, and then there is nothing a handle could drop either. + byName.remove(name); + drop.drop(name); + } + + /** Drops the handle's name if the handle still holds it, and otherwise does nothing. */ + synchronized void close(RegisteredFunction handle) throws SQLException { + if (byName.get(handle.name) != handle) { + return; + } + byName.remove(handle.name); + drop.drop(handle.name); + } + } + /** * A function registered through {@link ChdbScalarFunctionBuilder#register} or chdb-arrow's * {@code ArrowScalarFunctionBuilder}. Closing it drops the function. */ public static final class RegisteredFunction implements AutoCloseable { + private final Registry registry; private final String name; - private RegisteredFunction(String name) { + private RegisteredFunction(Registry registry, String name) { + this.registry = registry; this.name = name; } @@ -178,13 +214,7 @@ public String name() { @Override public void close() throws SQLException { refuseInsideAFunction(); - synchronized (REGISTERED) { - if (REGISTERED.get(name) != this) { - return; - } - REGISTERED.remove(name); - drop(name); - } + registry.close(this); } } } diff --git a/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbScalarFunctionBuilder.java b/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbScalarFunctionBuilder.java index ea24474..aeb6042 100644 --- a/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbScalarFunctionBuilder.java +++ b/chdb-jdbc/src/main/java/org/chdb/jdbc/ChdbScalarFunctionBuilder.java @@ -175,6 +175,11 @@ private ChdbScalarFunctionBuilder set(ChdbRowFunction function, int arity, Strin return this; } + /** The {@code ScalarFunctionCallback} flag bits declared so far. For tests. */ + int flags() { + return flags; + } + private static String typeName(String clickHouseType) { Objects.requireNonNull(clickHouseType, "clickHouseType"); if (clickHouseType.trim().isEmpty()) { diff --git a/chdb-jdbc/src/main/java/org/chdb/jdbc/RowFunctionCallback.java b/chdb-jdbc/src/main/java/org/chdb/jdbc/RowFunctionCallback.java index e4c533b..002d963 100644 --- a/chdb-jdbc/src/main/java/org/chdb/jdbc/RowFunctionCallback.java +++ b/chdb-jdbc/src/main/java/org/chdb/jdbc/RowFunctionCallback.java @@ -32,7 +32,12 @@ final class RowFunctionCallback extends ScalarFunctionCallback { @Override protected void apply(long argumentSchema, long arguments, long resultSchema, long result) throws Exception { - ArrowColumn batch = ChdbNative.copyArrowArray(argumentSchema, arguments); + ArrowColumn values = compute(ChdbNative.copyArrowArray(argumentSchema, arguments)); + ChdbNative.exportArrowArray(values, resultSchema, result); + } + + /** Computes one batch on the heap, from the copy of its arguments to the result to export. */ + ArrowColumn compute(ArrowColumn batch) throws Exception { ArrowDecoder.Reader[] readers = ArrowDecoder.readers(batch, parameters, binaryStrings); Object[] row = new Object[readers.length]; Object[] results = new Object[batch.length()]; @@ -42,6 +47,6 @@ protected void apply(long argumentSchema, long arguments, long resultSchema, lon } results[i] = function.apply(row); } - ChdbNative.exportArrowArray(this.result.encode(results), resultSchema, result); + return result.encode(results); } } diff --git a/chdb-jdbc/src/test/java/org/chdb/internal/ArrowColumns.java b/chdb-jdbc/src/test/java/org/chdb/internal/ArrowColumns.java new file mode 100644 index 0000000..9a93511 --- /dev/null +++ b/chdb-jdbc/src/test/java/org/chdb/internal/ArrowColumns.java @@ -0,0 +1,38 @@ +package org.chdb.internal; + +import java.util.ArrayList; +import java.util.List; + +/** + * Builds and reads {@link ArrowColumn}s for tests outside this package, which cannot see their + * constructor or fields. + */ +public final class ArrowColumns { + + private ArrowColumns() { + } + + /** A batch as chDB passes one: a struct of {@code rows} rows, one child per argument. */ + public static ArrowColumn batch(int rows, ArrowColumn... arguments) { + return new ArrowColumn("+s", null, false, rows, 0, 0, new byte[][] {null}, arguments); + } + + /** {@code values} as the column chDB would pass for an argument declared as {@code type}. */ + public static ArrowColumn argument(String type, Object... values) { + return ArrowEncoder.forType(ClickHouseType.parse(type)).encode(values); + } + + public static String format(ArrowColumn column) { + return column.format; + } + + /** Every row of {@code column}, read the way an argument declared as {@code type} is. */ + public static List values(ArrowColumn column, String type) { + ArrowDecoder.Reader reader = ArrowDecoder.reader(column, ClickHouseType.parse(type), false); + List out = new ArrayList<>(column.length); + for (int i = 0; i < column.length; i++) { + out.add(reader.read(i)); + } + return out; + } +} diff --git a/chdb-jdbc/src/test/java/org/chdb/internal/ArrowDecoderTest.java b/chdb-jdbc/src/test/java/org/chdb/internal/ArrowDecoderTest.java index 9e57c8a..8670991 100644 --- a/chdb-jdbc/src/test/java/org/chdb/internal/ArrowDecoderTest.java +++ b/chdb-jdbc/src/test/java/org/chdb/internal/ArrowDecoderTest.java @@ -14,11 +14,13 @@ import java.nio.charset.StandardCharsets; import java.time.Instant; import java.time.LocalDate; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.TimeZone; import java.util.UUID; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -285,4 +287,236 @@ void unsupported() { ArrowDecoder.checkReadable(ClickHouseType.parse("Map(String, Array(Nullable(Decimal(10, 2))))")); ArrowDecoder.checkReadable(ClickHouseType.parse("JSON(a Time)")); } + + /** A decimal's unscaled value as {@code width} bytes of little-endian two's complement. */ + private static byte[] decimal(BigInteger unscaled, int width) { + byte[] bigEndian = unscaled.toByteArray(); + byte[] out = new byte[width]; + Arrays.fill(out, (byte) (unscaled.signum() < 0 ? 0xff : 0)); + for (int i = 0; i < bigEndian.length; i++) { + out[i] = bigEndian[bigEndian.length - 1 - i]; + } + return out; + } + + private static List readAll(ArrowColumn column, String declared) { + List out = new ArrayList<>(); + for (int i = 0; i < column.length; i++) { + out.add(read(column, declared, i)); + } + return out; + } + + @Test + @DisplayName("every integer width at its limits, and unsigned values on both sides of the sign bit") + void integerLimits() { + ArrowColumn int8 = column("c", 2, null, new byte[] {Byte.MIN_VALUE, Byte.MAX_VALUE}); + assertEquals(Arrays.asList(Byte.MIN_VALUE, Byte.MAX_VALUE), readAll(int8, "Int8")); + // For an unsigned type the sign bit is a value bit, so 0x80 is 128 and not -128. + ArrowColumn uint8 = column("C", 3, null, new byte[] {0, (byte) 0x80, (byte) 0xff}); + assertEquals(Arrays.asList((short) 0, (short) 128, (short) 255), readAll(uint8, "UInt8")); + byte[] shorts = buffer(6).putShort(Short.MIN_VALUE).putShort(Short.MAX_VALUE).putShort((short) 0x8000).array(); + assertEquals(Arrays.asList(Short.MIN_VALUE, Short.MAX_VALUE, Short.MIN_VALUE), readAll(column("s", 3, null, shorts), "Int16")); + assertEquals(Arrays.asList(32768, 32767, 32768), readAll(column("S", 3, null, shorts), "UInt16")); + assertEquals(Arrays.asList(Integer.MIN_VALUE, Integer.MAX_VALUE), + readAll(column("i", 2, null, ints(Integer.MIN_VALUE, Integer.MAX_VALUE)), "Int32")); + assertEquals(Arrays.asList(2147483648L, 2147483647L), + readAll(column("I", 2, null, ints(Integer.MIN_VALUE, Integer.MAX_VALUE)), "UInt32")); + assertEquals(Arrays.asList(Long.MIN_VALUE, Long.MAX_VALUE), + readAll(column("l", 2, null, longs(Long.MIN_VALUE, Long.MAX_VALUE)), "Int64")); + // UInt64 is a BigInteger at every value, so a function's argument type does not change with it. + assertEquals(Arrays.asList(BigInteger.ZERO, BigInteger.valueOf(Long.MAX_VALUE), BigInteger.ONE.shiftLeft(63)), + readAll(column("L", 3, null, longs(0, Long.MAX_VALUE, Long.MIN_VALUE)), "UInt64")); + + BigInteger int128Min = BigInteger.ONE.shiftLeft(127).negate(); + BigInteger uint128Max = BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE); + BigInteger int256Min = BigInteger.ONE.shiftLeft(255).negate(); + BigInteger uint256Max = BigInteger.ONE.shiftLeft(256).subtract(BigInteger.ONE); + assertEquals(int128Min, read(textColumn("u", null, int128Min.toString()), "Int128", 0)); + assertEquals(uint128Max, read(textColumn("u", null, uint128Max.toString()), "UInt128", 0)); + assertEquals(int256Min, read(textColumn("u", null, int256Min.toString()), "Int256", 0)); + assertEquals(uint256Max, read(textColumn("z", null, uint256Max.toString()), "UInt256", 0)); + } + + @Test + @DisplayName("an offset applies to every flat layout, and validity bits need not start on a byte") + void slicedFlatLayouts() throws Exception { + // Slots 3..8 of ten: the slice crosses from the first byte of each bitmap into the second. + byte[] values = bitmap(false, false, false, true, false, true, true, false, true, false); + byte[] valid = bitmap(true, true, true, true, false, true, true, true, true, true); + ArrowColumn bools = column("b", null, 6, 3, valid, new byte[][] {values}, NONE); + assertEquals(Arrays.asList(true, null, true, true, false, true), readAll(bools, "Bool")); + + ArrowColumn strings = column("u", null, 2, 1, null, text("skipped", "a", "héllo", "z"), NONE); + assertEquals(Arrays.asList("a", "héllo"), readAll(strings, "String")); + + UUID second = UUID.fromString("123e4567-e89b-12d3-a456-426614174000"); + byte[] uuids = ByteBuffer.allocate(32).putLong(1).putLong(2) + .putLong(second.getMostSignificantBits()).putLong(second.getLeastSignificantBits()).array(); + assertEquals(second, read(column("w:16", "arrow.uuid", 1, 1, null, new byte[][] {uuids}, NONE), "UUID", 0)); + byte[] ipv6 = new byte[32]; + System.arraycopy(InetAddress.getByName("2001:db8::1").getAddress(), 0, ipv6, 16, 16); + assertEquals(InetAddress.getByName("2001:db8::1"), read(column("w:16", null, 1, 1, null, new byte[][] {ipv6}, NONE), "IPv6", 0)); + ArrowColumn fixed = column("w:2", null, 1, 2, null, new byte[][] {"aabbcc".getBytes(StandardCharsets.UTF_8)}, NONE); + assertEquals("cc", read(fixed, "FixedString(2)", 0)); + + assertEquals(LocalDate.of(2024, 1, 2), read(column("tdD", null, 1, 1, null, new byte[][] {ints(0, 19724)}, NONE), "Date", 0)); + assertEquals(Instant.parse("2024-01-02T03:04:05.678Z"), + read(column("tsm:UTC", null, 1, 1, null, new byte[][] {longs(0, 1704164645678L)}, NONE), "DateTime64(3, 'UTC')", 0)); + byte[] decimals = new byte[32]; + System.arraycopy(decimal(BigInteger.valueOf(-1234), 16), 0, decimals, 16, 16); + assertEquals(new BigDecimal("-12.34"), read(column("d:10,2", null, 1, 1, null, new byte[][] {decimals}, NONE), "Decimal(10, 2)", 0)); + + // A null count of -1 means the producer did not count them: the bitmap still decides. + ArrowColumn uncounted = new ArrowColumn("l", null, true, 2, 0, -1, new byte[][] {bitmap(true, false), longs(1, 2)}, NONE); + assertEquals(Arrays.asList(1L, null), readAll(uncounted, "Int64")); + } + + @Test + @DisplayName("an offset applies to lists and maps, and a child can be sliced on its own") + void slicedNestedLayouts() { + ArrowColumn elements = column("l", 6, null, longs(1, 2, 3, 4, 5, 6)); + ArrowColumn lists = column("+l", null, 2, 1, null, new byte[][] {ints(0, 1, 3, 6)}, new ArrowColumn[] {elements}); + assertEquals(Arrays.asList(Arrays.asList(2L, 3L), Arrays.asList(4L, 5L, 6L)), readAll(lists, "Array(Int64)")); + + // The list's offsets index the child as the child sees itself, after its own offset. + ArrowColumn slicedChild = column("l", null, 4, 2, null, new byte[][] {longs(9, 9, 1, 2, 3, 4)}, NONE); + ArrowColumn overSlice = column("+l", null, 2, 0, null, new byte[][] {ints(0, 2, 4)}, new ArrowColumn[] {slicedChild}); + assertEquals(Arrays.asList(Arrays.asList(1L, 2L), Arrays.asList(3L, 4L)), readAll(overSlice, "Array(Int64)")); + + ArrowColumn entries = column("+s", null, 3, 0, null, new byte[0][], + new ArrowColumn[] {textColumn("u", null, "x", "k", "j"), column("l", 3, null, longs(0, 5, 6))}); + ArrowColumn map = column("+m", null, 1, 1, null, new byte[][] {ints(0, 1, 3)}, new ArrowColumn[] {entries}); + Map expected = new LinkedHashMap<>(); + expected.put("k", 5L); + expected.put("j", 6L); + assertEquals(expected, read(map, "Map(String, Int64)", 0)); + } + + @Test + @DisplayName("a decimal keeps its declared scale, zero included, and its sign at 128 and 256 bits") + void decimalScales() { + byte[] oneFifty = decimal(BigInteger.valueOf(150), 16); + // BigDecimal equality includes the scale: what arrives is 1.50, not 1.5. + assertEquals(new BigDecimal("1.50"), read(column("d:10,2", 1, null, oneFifty), "Decimal(10, 2)", 0)); + assertEquals(new BigDecimal("150"), read(column("d:10,0", 1, null, oneFifty), "Decimal(10, 0)", 0)); + + BigInteger max38 = BigInteger.TEN.pow(38).subtract(BigInteger.ONE); + byte[] limits = new byte[48]; + System.arraycopy(decimal(max38, 16), 0, limits, 0, 16); + System.arraycopy(decimal(max38.negate(), 16), 0, limits, 16, 16); + // The most negative 128-bit value, written as two words rather than through BigInteger. + System.arraycopy(buffer(16).putLong(0).putLong(Long.MIN_VALUE).array(), 0, limits, 32, 16); + ArrowColumn decimal128 = column("d:38,10", 3, null, limits); + assertEquals(new BigDecimal(max38, 10), read(decimal128, "Decimal(38, 10)", 0)); + assertEquals(new BigDecimal(max38.negate(), 10), read(decimal128, "Decimal(38, 10)", 1)); + assertEquals(new BigDecimal(BigInteger.ONE.shiftLeft(127).negate(), 10), read(decimal128, "Decimal(38, 10)", 2)); + + BigInteger max76 = BigInteger.TEN.pow(76).subtract(BigInteger.ONE); + ArrowColumn decimal256 = column("d:76,40,256", 1, null, decimal(max76.negate(), 32)); + assertEquals(new BigDecimal(max76.negate(), 40), read(decimal256, "Decimal(76, 40)", 0)); + } + + @Test + @DisplayName("a FixedString keeps its padding, and one that is not valid UTF-8 fails instead of arriving altered") + void fixedStringUtf8() { + byte[] data = {'a', 'b', 0, 0, (byte) 0xff, (byte) 0xfe, 0, 0, (byte) 0xc3, (byte) 0xa9, 'x', 0}; + ArrowColumn fixed = column("w:4", null, 3, 0, null, new byte[][] {data}, NONE); + assertEquals("ab\0\0", read(fixed, "FixedString(4)", 0)); + assertEquals("éx\0", read(fixed, "FixedString(4)", 2)); + // chDB refuses a String argument that is not valid UTF-8 but passes a FixedString's bytes as + // they are, so decoding them leniently would replace them with U+FFFD. + ScalarFunctionException e = assertThrows(ScalarFunctionException.class, () -> read(fixed, "FixedString(4)", 1)); + assertTrue(e.getMessage().contains("withBinaryStrings()"), e.getMessage()); + ArrowColumn cut = column("w:1", null, 1, 0, null, new byte[][] {{(byte) 0xc3}}, NONE); + assertThrows(ScalarFunctionException.class, () -> read(cut, "FixedString(1)", 0), "half a character"); + // With binary strings the bytes arrive exactly. + assertArrayEquals(new byte[] {(byte) 0xff, (byte) 0xfe, 0, 0}, + (byte[]) ArrowDecoder.reader(fixed, ClickHouseType.parse("FixedString(4)"), true).read(1)); + } + + @Test + @DisplayName("dates and instants depend on neither the JVM's zone nor the column's") + void temporalIgnoresZones() { + ArrowColumn dates = column("tdD", 2, null, ints(-1, 0)); + ArrowColumn shanghai = column("tss:Asia/Shanghai", 1, null, longs(0)); + ArrowColumn newYork = column("tsu:America/New_York", 1, null, longs(-1_500_000)); + TimeZone saved = TimeZone.getDefault(); + try { + for (String zone : new String[] {"Pacific/Kiritimati", "Pacific/Pago_Pago", "America/St_Johns"}) { + TimeZone.setDefault(TimeZone.getTimeZone(zone)); + assertEquals(Arrays.asList(LocalDate.of(1969, 12, 31), LocalDate.of(1970, 1, 1)), readAll(dates, "Date32"), zone); + // The zone in the format is the one the column is shown in; the instant is the same. + assertEquals(Instant.EPOCH, read(shanghai, "DateTime('Asia/Shanghai')", 0), zone); + assertEquals(Instant.parse("1969-12-31T23:59:58.500Z"), + read(newYork, "DateTime64(6, 'America/New_York')", 0), zone); + } + } finally { + TimeZone.setDefault(saved); + } + } + + @Test + @DisplayName("containers nest: arrays of arrays and of tuples, maps of arrays, and a NULL row unlike an empty one") + void nestedContainers() { + // Array(Array(Int32)): [[1, 2], []], NULL, [[3]] + ArrowColumn innermost = column("i", 3, null, ints(1, 2, 3)); + ArrowColumn inner = column("+l", null, 3, 0, null, new byte[][] {ints(0, 2, 2, 3)}, new ArrowColumn[] {innermost}); + ArrowColumn outer = column("+l", null, 3, 0, bitmap(true, false, true), new byte[][] {ints(0, 2, 2, 3)}, + new ArrowColumn[] {inner}); + assertEquals(Arrays.asList(Arrays.asList(Arrays.asList(1, 2), Collections.emptyList()), null, + Collections.singletonList(Collections.singletonList(3))), readAll(outer, "Array(Array(Int32))")); + + // Array(Tuple(Int128, LowCardinality(Nullable(String)))): the declaration reaches the fields. + ArrowColumn tuples = column("+s", null, 2, 0, null, new byte[0][], + new ArrowColumn[] {textColumn("u", null, "7", "-8"), textColumn("u", bitmap(true, false), "a", null)}); + ArrowColumn list = column("+l", null, 1, 0, null, new byte[][] {ints(0, 2)}, new ArrowColumn[] {tuples}); + List got = (List) read(list, "Array(Tuple(Int128, LowCardinality(Nullable(String))))", 0); + assertArrayEquals(new Object[] {BigInteger.valueOf(7), "a"}, (Object[]) got.get(0)); + assertArrayEquals(new Object[] {BigInteger.valueOf(-8), null}, (Object[]) got.get(1)); + + // Map(String, Array(UInt64)), then a NULL map. + ArrowColumn arrays = column("+l", null, 2, 0, null, new byte[][] {ints(0, 2, 3)}, + new ArrowColumn[] {column("L", 3, null, longs(1, 2, -1))}); + ArrowColumn entries = column("+s", null, 2, 0, null, new byte[0][], new ArrowColumn[] {textColumn("u", null, "k", "j"), arrays}); + ArrowColumn maps = column("+m", null, 2, 0, bitmap(true, false), new byte[][] {ints(0, 2, 2)}, new ArrowColumn[] {entries}); + Map expected = new LinkedHashMap<>(); + expected.put("k", Arrays.asList(BigInteger.ONE, BigInteger.valueOf(2))); + expected.put("j", Collections.singletonList(BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE))); + assertEquals(Arrays.asList(expected, null), readAll(maps, "Map(String, Array(UInt64))")); + + ArrowColumn nullableTuple = column("+s", null, 2, 0, bitmap(false, true), new byte[0][], + new ArrowColumn[] {column("l", 2, null, longs(0, 5))}); + assertNull(read(nullableTuple, "Tuple(Int64)", 0)); + assertArrayEquals(new Object[] {5L}, (Object[]) read(nullableTuple, "Tuple(Int64)", 1)); + } + + @Test + @DisplayName("a batch of no rows reads nothing, even where the producer left every buffer out") + void emptyBatch() { + // C Data lets a buffer of zero bytes be a null pointer, which the shim passes on as null. + String[] types = {"Bool", "Int64", "String", "FixedString(2)", "UUID", "IPv6", "Decimal(10, 2)", "Date", + "DateTime64(3)", "Array(Int64)", "Map(String, Int64)", "Tuple(Int64)"}; + String[] formats = {"b", "l", "u", "w:2", "w:16", "w:16", "d:10,2", "tdD", "tsm:UTC", "+l", "+m", "+s"}; + ArrowColumn[] arguments = new ArrowColumn[types.length]; + for (int i = 0; i < types.length; i++) { + int buffers = formats[i].equals("+s") ? 1 : formats[i].equals("u") ? 3 : 2; + ArrowColumn[] children = NONE; + if (formats[i].equals("+l") || formats[i].equals("+s")) { + children = new ArrowColumn[] {new ArrowColumn("l", null, false, 0, 0, 0, new byte[2][], NONE)}; + } else if (formats[i].equals("+m")) { + children = new ArrowColumn[] {new ArrowColumn("+s", null, false, 0, 0, 0, new byte[1][], new ArrowColumn[] { + new ArrowColumn("u", null, false, 0, 0, 0, new byte[3][], NONE), + new ArrowColumn("l", null, false, 0, 0, 0, new byte[2][], NONE)})}; + } + arguments[i] = new ArrowColumn(formats[i], formats[i].equals("w:16") && i == 4 ? "arrow.uuid" : null, false, + 0, 0, 0, new byte[buffers][], children); + } + List declared = new ArrayList<>(); + for (String type : types) { + declared.add(ClickHouseType.parse(type)); + } + ArrowColumn batch = column("+s", null, 0, 0, null, new byte[0][], arguments); + assertEquals(types.length, ArrowDecoder.readers(batch, declared, false).length); + } } diff --git a/chdb-jdbc/src/test/java/org/chdb/internal/ArrowEncoderTest.java b/chdb-jdbc/src/test/java/org/chdb/internal/ArrowEncoderTest.java index e9c7a87..f361b33 100644 --- a/chdb-jdbc/src/test/java/org/chdb/internal/ArrowEncoderTest.java +++ b/chdb-jdbc/src/test/java/org/chdb/internal/ArrowEncoderTest.java @@ -25,6 +25,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.TimeZone; import java.util.UUID; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -226,4 +227,199 @@ void mapsAndTuples() { () -> encode("Tuple(a Int64, b String)", (Object) new Object[] {1L})); assertTrue(e.getMessage().contains("1 elements"), e.getMessage()); } + + private static int[] offsets(ArrowColumn column) { + ByteBuffer buffer = buffer(column, 1); + int[] out = new int[column.length + 1]; + for (int i = 0; i < out.length; i++) { + out[i] = buffer.getInt(i * 4); + } + return out; + } + + /** + * Checks a column and its children against the C Data layout of its format. The shim copies + * what it is given without looking inside, so an offset past the data would be read by chDB. + */ + private static void checkLayout(ArrowColumn column) { + String format = column.format; + int rows = column.length; + int buffers = format.equals("+s") ? 1 : format.equals("u") || format.equals("z") ? 3 : 2; + assertEquals(buffers, column.buffers.length, format + " buffers"); + if (column.nullCount == 0) { + assertNull(column.buffers[0], format + ": no NULLs, no validity bitmap"); + assertFalse(column.nullable, format); + } else { + assertEquals((rows + 7) / 8, column.buffers[0].length, format + " validity bytes"); + assertTrue(column.nullable, format); + } + switch (format) { + case "u": + case "z": + case "+l": + case "+m": { + int[] offsets = offsets(column); + assertEquals(0, offsets[0], format + " starts at 0"); + for (int i = 0; i < rows; i++) { + assertTrue(offsets[i] <= offsets[i + 1], format + " offsets never decrease"); + } + int end = format.startsWith("+") ? column.children[0].length : column.buffers[2].length; + assertEquals(end, offsets[rows], format + " ends where its values do"); + break; + } + case "b": + assertEquals((rows + 7) / 8, column.buffers[1].length, "bit-packed values"); + break; + case "+s": + break; + default: + int width = format.equals("tdD") ? 4 : 8; + assertEquals(rows * width, column.buffers[1].length, format + " values"); + } + for (ArrowColumn child : column.children) { + if (format.equals("+s")) { + assertEquals(rows, child.length, "a struct's fields have its length"); + } + checkLayout(child); + } + } + + @Test + @DisplayName("every encoder lays its buffers out as C Data does, for a batch of no rows as for one with NULLs") + void bufferLayout() throws Exception { + Map map = Collections.singletonMap("k", 1L); + Object[][] samples = { + {"Bool", true}, {"Int64", 1L}, {"UInt64", BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE)}, + {"Float64", 1.5}, {"String", "héllo"}, {"String", new byte[] {1, 2}}, {"Date", LocalDate.of(2024, 1, 2)}, + {"DateTime64(3)", Instant.EPOCH}, {"Decimal(10, 2)", BigDecimal.ONE}, {"UUID", UUID.randomUUID()}, + {"IPv6", InetAddress.getByName("::1")}, {"Array(Nullable(Int64))", Arrays.asList(1L, null)}, + {"Map(String, Nullable(Int64))", map}, {"Tuple(a Int64, b Array(String))", new Object[] {1L, Arrays.asList("x")}}, + }; + for (Object[] sample : samples) { + String type = (String) sample[0]; + ArrowColumn empty = encode(type); + assertEquals(0, empty.length, type); + checkLayout(empty); + ArrowColumn some = encode(type, sample[1], null, sample[1]); + assertEquals(3, some.length, type); + assertEquals(1, some.nullCount, type); + checkLayout(some); + } + } + + @Test + @DisplayName("integers stay exact at the 64-bit limits, and a BigInteger one past them goes as text, not wrapped") + void integerLimits() { + ArrowColumn column = encode("Int64", Long.MIN_VALUE, Long.MAX_VALUE, Byte.MIN_VALUE, Short.MAX_VALUE, + Integer.MIN_VALUE, BigInteger.valueOf(Long.MIN_VALUE), BigInteger.valueOf(Long.MAX_VALUE)); + assertEquals("l", column.format); + long[] expected = {Long.MIN_VALUE, Long.MAX_VALUE, -128, 32767, Integer.MIN_VALUE, Long.MIN_VALUE, Long.MAX_VALUE}; + ByteBuffer data = buffer(column, 1); + for (int i = 0; i < expected.length; i++) { + assertEquals(expected[i], data.getLong(i * 8), "row " + i); + } + + // One past either end needs 65 bits, where longValue() would wrap. + BigInteger above = BigInteger.ONE.shiftLeft(63); + BigInteger below = above.negate().subtract(BigInteger.ONE); + assertEquals(Arrays.asList("9223372036854775808", "-9223372036854775809", "5"), texts(encode("Int128", above, below, 5L))); + // A negative value for an unsigned type is sent as it is, for chDB's range check to refuse. + assertEquals(-1L, buffer(encode("UInt64", -1L), 1).getLong(0)); + } + + @Test + @DisplayName("a decimal goes in plain notation with its scale, a float as its shortest decimal, NaN as text") + void decimalText() { + assertEquals(Arrays.asList("120000", "1.50", "-0.000001", "12345678901234567890123456789012345678"), + texts(encode("Decimal(38, 2)", new BigDecimal("1.2E+5"), new BigDecimal("1.50"), new BigDecimal("-1E-6"), + new BigInteger("12345678901234567890123456789012345678")))); + // 0.1, not 0.1000000000000000055511151231257827: the decimal a double prints as. + assertEquals(Arrays.asList("0.1", "0.10000000149011612", "NaN", "-Infinity"), + texts(encode("Decimal(10, 2)", 0.1, 0.1f, Double.NaN, Float.NEGATIVE_INFINITY))); + } + + @Test + @DisplayName("text goes as valid UTF-8 whatever the String holds, and bytes go exactly") + void stringBytes() { + // Java's encoder replaces an unpaired surrogate, so a utf8 column never carries invalid UTF-8. + assertArrayEquals("a?b😀".getBytes(StandardCharsets.UTF_8), encode("String", "a\uD800b", "😀").buffers[2]); + ArrowColumn bytes = encode("FixedString(2)", new byte[] {(byte) 0xff, 0}, "é"); + assertEquals("z", bytes.format); + assertArrayEquals(new byte[] {(byte) 0xff, 0, (byte) 0xc3, (byte) 0xa9}, bytes.buffers[2]); + } + + @Test + @DisplayName("an instant encodes the same from any zone, and a date does not depend on the JVM's zone") + void temporalAcrossZones() { + Instant instant = Instant.parse("2024-03-10T07:30:00.123456789Z"); + long nanos = buffer(encode("DateTime64(9)", instant), 1).getLong(0); + assertEquals(1710055800123456789L, nanos); + TimeZone saved = TimeZone.getDefault(); + try { + for (String zone : new String[] {"Pacific/Kiritimati", "America/St_Johns", "Pacific/Pago_Pago"}) { + TimeZone.setDefault(TimeZone.getTimeZone(zone)); + ZonedDateTime local = instant.atZone(ZoneId.of(zone)); + assertEquals(nanos, buffer(encode("DateTime64(9)", local), 1).getLong(0), zone); + assertEquals(nanos, buffer(encode("DateTime64(9)", local.toOffsetDateTime()), 1).getLong(0), zone); + assertEquals(-1, buffer(encode("Date", LocalDate.of(1969, 12, 31)), 1).getInt(0), zone); + } + } finally { + TimeZone.setDefault(saved); + } + // Date32's last day, and a date no date type holds. + assertEquals(120529, buffer(encode("Date32", LocalDate.of(2299, 12, 31)), 1).getInt(0)); + ScalarFunctionException e = assertThrows(ScalarFunctionException.class, () -> encode("Date32", LocalDate.MAX)); + assertTrue(e.getMessage().contains("no date type holds"), e.getMessage()); + // Microseconds before the epoch are cut toward the past too. + assertEquals(-1L, buffer(encode("DateTime64(6)", Instant.parse("1969-12-31T23:59:59.9999995Z")), 1).getLong(0)); + } + + @Test + @DisplayName("containers nest, and a NULL row is not an empty one") + void nestedContainers() { + // Array(Array(Int64)): [[1, 2], []], NULL, [] + ArrowColumn outer = encode("Array(Array(Int64))", + Arrays.asList(Arrays.asList(1L, 2L), Collections.emptyList()), null, Collections.emptyList()); + assertArrayEquals(new int[] {0, 2, 2, 2}, offsets(outer)); + assertTrue(outer.isNull(1)); + assertFalse(outer.isNull(2), "an empty array is not NULL"); + ArrowColumn inner = outer.children[0]; + assertEquals("+l", inner.format); + assertArrayEquals(new int[] {0, 2, 2}, offsets(inner)); + assertEquals(2L, buffer(inner.children[0], 1).getLong(8)); + + ArrowColumn tuples = encode("Array(Tuple(Int64, String))", Collections.singletonList(new Object[] {7L, "x"})); + assertEquals("+s", tuples.children[0].format); + assertEquals(Collections.singletonList("x"), texts(tuples.children[0].children[1])); + + Map> map = new LinkedHashMap<>(); + map.put("k", Arrays.asList(1L, 2L)); + map.put("j", Collections.emptyList()); + ArrowColumn values = encode("Map(String, Array(Int64))", map).children[0].children[1]; + assertEquals("+l", values.format); + assertArrayEquals(new int[] {0, 2, 2}, offsets(values)); + + // An element of bytes makes the whole element column binary. + assertEquals("z", encode("Array(String)", Arrays.asList("a", new byte[] {1})).children[0].format); + } + + @Test + @DisplayName("a result of the wrong Java type fails the batch, at any depth, naming the type it was for") + void wrongTypes() throws Exception { + Object[][] cases = { + {"Map(String, Int64)", Collections.singletonList("k"), "a Map"}, + {"Tuple(Int64)", "x", "an Object[] or a List"}, + {"IPv4", 16909060, "an InetAddress or a String"}, + {"Bool", "true", "a Boolean"}, + // The java.sql types JDBC code tends to have to hand are not taken for granted. + {"Date", java.sql.Date.valueOf("2024-01-02"), "a LocalDate"}, + {"DateTime", java.sql.Timestamp.from(Instant.EPOCH), "an Instant, OffsetDateTime or ZonedDateTime"}, + {"Array(Array(Int64))", Collections.singletonList(Collections.singletonList("1")), "for a Int64 result"}, + {"Map(String, Int64)", Collections.singletonMap(1, 1L), "for a String result"}, + }; + for (Object[] c : cases) { + ScalarFunctionException e = assertThrows(ScalarFunctionException.class, () -> encode((String) c[0], c[1]), (String) c[0]); + assertTrue(e.getMessage().contains((String) c[2]), c[0] + ": " + e.getMessage()); + } + } } diff --git a/chdb-jdbc/src/test/java/org/chdb/internal/ScalarFunctionCallbackTest.java b/chdb-jdbc/src/test/java/org/chdb/internal/ScalarFunctionCallbackTest.java index 11f77a6..b2e1d2d 100644 --- a/chdb-jdbc/src/test/java/org/chdb/internal/ScalarFunctionCallbackTest.java +++ b/chdb-jdbc/src/test/java/org/chdb/internal/ScalarFunctionCallbackTest.java @@ -1,13 +1,17 @@ package org.chdb.internal; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.charset.StandardCharsets; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -107,10 +111,90 @@ void causeCycle() { @Test @DisplayName("abandoning a callback releases it once and swallows what release throws") void release() { - // destroyed() takes the same path, and also uncounts a live registration, which only a - // real one has; the integration suite checks that the count returns to zero. TestCallback abandoned = new TestCallback(() -> { }); + long live = ScalarFunctionCallback.liveCount(); abandoned.abandon(); assertEquals(1, abandoned.releases.get()); + assertEquals(live, ScalarFunctionCallback.liveCount(), "a callback chDB never had was never counted"); + } + + @Test + @DisplayName("a cause chain is cut after eight exceptions") + void longCauseChain() { + RuntimeException failure = new RuntimeException("cause 11"); + for (int i = 10; i >= 0; i--) { + failure = new RuntimeException("cause " + i, failure); + } + RuntimeException thrown = failure; + String message = failure(new TestCallback(() -> { + throw thrown; + })); + assertEquals(8, message.split("; caused by ", -1).length, message); + assertTrue(message.startsWith("java.lang.RuntimeException: cause 0;"), message); + assertTrue(message.endsWith("java.lang.RuntimeException: cause 7"), message); + } + + @Test + @DisplayName("the driver's own report reads as a sentence even as the cause of another exception") + void driverReportAsACause() { + String message = failure(new TestCallback(() -> { + throw new IllegalStateException("while encoding", new ScalarFunctionException("the function returned null")); + })); + assertEquals("java.lang.IllegalStateException: while encoding; caused by the function returned null", message); + } + + @Test + @DisplayName("a message goes to the shim as standard UTF-8, not JNI's modified UTF-8") + void messageEncoding() { + // Modified UTF-8 would write the emoji as two three-byte surrogates and the NUL as two bytes. + byte[] message = new TestCallback(() -> { + throw new ScalarFunctionException("é😀\0"); + }).invoke(1, 2, 3, 4); + assertArrayEquals(new byte[] {(byte) 0xc3, (byte) 0xa9, (byte) 0xf0, (byte) 0x9f, (byte) 0x98, (byte) 0x80, 0}, message); + } + + @Test + @DisplayName("the flag bits are chdb.h's chdb_scalar_function_flag values") + void flagValues() { + assertEquals(1, ScalarFunctionCallback.VOLATILE); + assertEquals(2, ScalarFunctionCallback.SPECIAL_NULL_HANDLING); + assertEquals(4, ScalarFunctionCallback.BINARY_STRINGS); + } + + @Test + @DisplayName("a registration is counted while chDB has it: from before the hand-over until destroyed") + void liveCount() { + long live = ScalarFunctionCallback.liveCount(); + TestCallback callback = new TestCallback(() -> { }); + AtomicLong during = new AtomicLong(); + callback.handOver(() -> during.set(ScalarFunctionCallback.liveCount())); + assertEquals(live + 1, during.get(), "counted before chDB can see it"); + assertEquals(live + 1, ScalarFunctionCallback.liveCount()); + callback.destroyed(); + assertEquals(live, ScalarFunctionCallback.liveCount()); + assertEquals(1, callback.releases.get(), "destroying releases it"); + + // A drop by name on another thread can destroy it before the registration returns. + TestCallback raced = new TestCallback(() -> { }); + raced.handOver(raced::destroyed); + assertEquals(live, ScalarFunctionCallback.liveCount()); + } + + @Test + @DisplayName("a refused registration is uncounted again, and its exception is the one that reaches the caller") + void refusedRegistration() { + long live = ScalarFunctionCallback.liveCount(); + TestCallback callback = new TestCallback(() -> { }); + ChdbNativeException refused = new ChdbNativeException("Scalar function 'f' is already registered"); + assertSame(refused, assertThrows(ChdbNativeException.class, () -> callback.handOver(() -> { + throw refused; + }))); + assertEquals(live, ScalarFunctionCallback.liveCount()); + OutOfMemoryError exhausted = new OutOfMemoryError("deliberate"); + assertSame(exhausted, assertThrows(OutOfMemoryError.class, () -> callback.handOver(() -> { + throw exhausted; + }))); + assertEquals(live, ScalarFunctionCallback.liveCount()); + assertEquals(0, callback.releases.get(), "refused, it is still the caller's to abandon"); } } diff --git a/chdb-jdbc/src/test/java/org/chdb/jdbc/ChdbFunctionsTest.java b/chdb-jdbc/src/test/java/org/chdb/jdbc/ChdbFunctionsTest.java new file mode 100644 index 0000000..791e587 --- /dev/null +++ b/chdb-jdbc/src/test/java/org/chdb/jdbc/ChdbFunctionsTest.java @@ -0,0 +1,81 @@ +package org.chdb.jdbc; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import org.chdb.internal.ChdbNativeException; +import org.chdb.jdbc.ChdbFunctions.RegisteredFunction; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * Which drops a {@link RegisteredFunction} makes, against a registry whose drop is recorded rather + * than sent to chDB. Names are process-wide, so a handle must never drop a name that was dropped + * and registered again since it was made. + */ +class ChdbFunctionsTest { + + private final List dropped = new ArrayList<>(); + private final ChdbFunctions.Registry registry = new ChdbFunctions.Registry(dropped::add); + + @Test + @DisplayName("closing a handle drops its name once, and only while the name is still the handle's") + void closeDropsOnlyItsOwnRegistration() throws SQLException { + RegisteredFunction first = registry.add("f", () -> { }); + assertEquals("f", first.name()); + first.close(); + first.close(); + assertEquals(Collections.singletonList("f"), dropped); + + // Dropped by name, then registered again: the older handle has nothing left to drop. + RegisteredFunction second = registry.add("f", () -> { }); + registry.dropByName("f"); + RegisteredFunction third = registry.add("f", () -> { }); + second.close(); + assertEquals(Arrays.asList("f", "f"), dropped); + third.close(); + assertEquals(Arrays.asList("f", "f", "f"), dropped); + + // Names are independent of each other. + RegisteredFunction a = registry.add("a", () -> { }); + RegisteredFunction b = registry.add("b", () -> { }); + a.close(); + b.close(); + assertEquals(Arrays.asList("f", "f", "f", "a", "b"), dropped); + } + + @Test + @DisplayName("a refused registration records nothing, and the handle that holds the name keeps it") + void refusedRegistration() throws SQLException { + RegisteredFunction existing = registry.add("f", () -> { }); + ChdbNativeException refused = new ChdbNativeException("Scalar function 'f' is already registered"); + assertSame(refused, assertThrows(ChdbNativeException.class, () -> registry.add("f", () -> { + throw refused; + }))); + existing.close(); + assertEquals(Collections.singletonList("f"), dropped); + } + + @Test + @DisplayName("a drop chDB refuses still forgets the name, so the handle does not try again") + void refusedDrop() throws SQLException { + List attempts = new ArrayList<>(); + ChdbFunctions.Registry refusing = new ChdbFunctions.Registry(name -> { + attempts.add(name); + throw new SQLException("Scalar function '" + name + "' is not registered"); + }); + RegisteredFunction f = refusing.add("f", () -> { }); + assertThrows(SQLException.class, f::close); + f.close(); + RegisteredFunction g = refusing.add("g", () -> { }); + assertThrows(SQLException.class, () -> refusing.dropByName("g")); + g.close(); + assertEquals(Arrays.asList("f", "g"), attempts); + } +} diff --git a/chdb-jdbc/src/test/java/org/chdb/jdbc/ChdbScalarFunctionBuilderTest.java b/chdb-jdbc/src/test/java/org/chdb/jdbc/ChdbScalarFunctionBuilderTest.java index 15c3250..7be5d08 100644 --- a/chdb-jdbc/src/test/java/org/chdb/jdbc/ChdbScalarFunctionBuilderTest.java +++ b/chdb-jdbc/src/test/java/org/chdb/jdbc/ChdbScalarFunctionBuilderTest.java @@ -8,6 +8,7 @@ import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; +import org.chdb.internal.ScalarFunctionCallback; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -79,5 +80,31 @@ void unreadableParameter() { void foreignConnection() { SQLException e = assertThrows(SQLException.class, () -> complete().register(FOREIGN)); assertTrue(e.getMessage().contains("chDB connection"), e.getMessage()); + // Named, with unwrap's own refusal kept as the cause. + assertTrue(e.getMessage().contains(FOREIGN.getClass().getName()), e.getMessage()); + assertEquals("HY000", e.getSQLState()); + assertEquals("not a wrapper", e.getCause().getMessage()); + assertThrows(NullPointerException.class, () -> complete().register(null)); + } + + @Test + @DisplayName("each option sets its own flag bit, once however often it is asked for") + void flags() { + assertEquals(0, complete().flags()); + assertEquals(ScalarFunctionCallback.VOLATILE, complete().withVolatile().flags()); + assertEquals(ScalarFunctionCallback.SPECIAL_NULL_HANDLING, complete().withSpecialNullHandling().flags()); + assertEquals(ScalarFunctionCallback.BINARY_STRINGS, complete().withBinaryStrings().withBinaryStrings().flags()); + assertEquals(ScalarFunctionCallback.VOLATILE | ScalarFunctionCallback.SPECIAL_NULL_HANDLING + | ScalarFunctionCallback.BINARY_STRINGS, + complete().withBinaryStrings().withVolatile().withSpecialNullHandling().flags()); + } + + @Test + @DisplayName("a type name the driver cannot parse is left to chDB to refuse, not refused here") + void unparseableTypeName() { + // Past the builder's own checks: what stops it is the connection, where chDB would be asked. + SQLException e = assertThrows(SQLException.class, () -> ChdbFunctions.scalarFunction().withName("f") + .withParameter("Array(").withReturnType("Map(String,").withRowFunction(args -> null).register(FOREIGN)); + assertTrue(e.getMessage().contains("chDB connection"), e.getMessage()); } } diff --git a/chdb-jdbc/src/test/java/org/chdb/jdbc/RowFunctionCallbackTest.java b/chdb-jdbc/src/test/java/org/chdb/jdbc/RowFunctionCallbackTest.java new file mode 100644 index 0000000..a7ea57f --- /dev/null +++ b/chdb-jdbc/src/test/java/org/chdb/jdbc/RowFunctionCallbackTest.java @@ -0,0 +1,120 @@ +package org.chdb.jdbc; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import org.chdb.internal.ArrowColumn; +import org.chdb.internal.ArrowColumns; +import org.chdb.internal.ClickHouseType; +import org.chdb.internal.ScalarFunctionCallback; +import org.chdb.internal.ScalarFunctionException; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * A function computed one row at a time, over whole batches on the heap: everything the callback + * does between the shim's copy of chDB's arguments and its export of the result. + */ +class RowFunctionCallbackTest { + + private static RowFunctionCallback callback(ChdbRowFunction function, String returnType, int flags, String... parameters) { + List types = new ArrayList<>(); + for (String parameter : parameters) { + types.add(ClickHouseType.parse(parameter)); + } + return new RowFunctionCallback(function, types, ClickHouseType.parse(returnType), flags); + } + + @Test + @DisplayName("each row is computed in order, with one arguments array reused from row to row") + void rowsInOrder() throws Exception { + Map arrays = new IdentityHashMap<>(); + RowFunctionCallback repeat = callback(args -> { + arrays.put(args, Boolean.TRUE); + StringBuilder out = new StringBuilder(); + for (long i = 0; i < (Long) args[0]; i++) { + out.append((String) args[1]); + } + return out.toString(); + }, "String", 0, "Int64", "String"); + ArrowColumn batch = ArrowColumns.batch(3, + ArrowColumns.argument("Int64", 2L, 0L, 3L), ArrowColumns.argument("String", "ab", "x", "é")); + ArrowColumn result = repeat.compute(batch); + assertEquals("u", ArrowColumns.format(result)); + assertEquals(Arrays.asList("abab", "", "ééé"), ArrowColumns.values(result, "String")); + assertEquals(1, arrays.size(), "the documented reuse: copy the array to keep it"); + } + + @Test + @DisplayName("a function without arguments is called once per row of the batch, and not at all for none") + void batchesWithoutArgumentsOrRows() throws Exception { + AtomicInteger calls = new AtomicInteger(); + RowFunctionCallback next = callback(args -> { + assertEquals(0, args.length); + return (long) calls.incrementAndGet(); + }, "Int64", ScalarFunctionCallback.VOLATILE); + assertEquals(Arrays.asList(1L, 2L, 3L), ArrowColumns.values(next.compute(ArrowColumns.batch(3)), "Int64")); + + RowFunctionCallback never = callback(args -> { + throw new AssertionError("called for a batch of no rows"); + }, "String", 0, "String"); + ArrowColumn empty = never.compute(ArrowColumns.batch(0, ArrowColumns.argument("String"))); + assertEquals(0, empty.length()); + assertEquals(Collections.emptyList(), ArrowColumns.values(empty, "String")); + } + + @Test + @DisplayName("binary strings make a String argument a byte[]; without them it is a String") + void binaryStrings() throws Exception { + ArrowColumn batch = ArrowColumns.batch(1, ArrowColumns.argument("String", "héllo")); + RowFunctionCallback asText = callback(args -> args[0].getClass().getSimpleName(), "String", 0, "String"); + assertEquals(Collections.singletonList("String"), ArrowColumns.values(asText.compute(batch), "String")); + RowFunctionCallback asBytes = callback(args -> { + assertArrayEquals("héllo".getBytes(StandardCharsets.UTF_8), (byte[]) args[0]); + return ((byte[]) args[0]).length; + }, "UInt64", ScalarFunctionCallback.BINARY_STRINGS, "String"); + assertEquals(Collections.singletonList(6L), ArrowColumns.values(asBytes.compute(batch), "Int64")); + } + + @Test + @DisplayName("a NULL argument arrives as null, and a null result is a NULL") + void nulls() throws Exception { + RowFunctionCallback describe = callback(args -> args[0] == null ? null : "got " + args[0], "Nullable(String)", + ScalarFunctionCallback.SPECIAL_NULL_HANDLING, "Int64"); + ArrowColumn batch = ArrowColumns.batch(3, ArrowColumns.argument("Nullable(Int64)", 1L, null, 3L)); + assertEquals(Arrays.asList("got 1", null, "got 3"), ArrowColumns.values(describe.compute(batch), "String")); + } + + @Test + @DisplayName("an exception leaves the batch as thrown, and a result of the wrong type is named") + void failures() { + ArrowColumn batch = ArrowColumns.batch(2, ArrowColumns.argument("Int64", 1L, 0L)); + IOException thrown = new IOException("zero is not allowed"); + RowFunctionCallback failing = callback(args -> { + if ((Long) args[0] == 0) { + throw thrown; + } + return args[0]; + }, "Int64", 0, "Int64"); + assertSame(thrown, assertThrows(IOException.class, () -> failing.compute(batch))); + + RowFunctionCallback wrongType = callback(args -> "one", "Int64", 0, "Int64"); + ScalarFunctionException e = assertThrows(ScalarFunctionException.class, () -> wrongType.compute(batch)); + assertTrue(e.getMessage().contains("returned a java.lang.String for a Int64 result"), e.getMessage()); + + RowFunctionCallback twoArguments = callback(args -> args[0], "Int64", 0, "Int64", "Int64"); + assertThrows(ScalarFunctionException.class, () -> twoArguments.compute(batch), "one column for two parameters"); + } +} diff --git a/chdb-jni/test/chdb_jni_test.cpp b/chdb-jni/test/chdb_jni_test.cpp index 5cff403..8bdfa46 100644 --- a/chdb-jni/test/chdb_jni_test.cpp +++ b/chdb-jni/test/chdb_jni_test.cpp @@ -439,6 +439,24 @@ void testArrowExtensionName() put("arrow.uuid"); check(arrowExtensionName(metadata.data()) == "arrow.uuid", "reads the extension name"); check(arrowExtensionName(nullptr).empty(), "no metadata, no extension"); + + // Only the whole key counts: neither a longer key that starts with it nor a shorter one. + std::string near; + auto putNear = [&near](const std::string & text) + { + const int32_t length = static_cast(text.size()); + near.append(reinterpret_cast(&length), sizeof(length)); + near += text; + }; + near.append(reinterpret_cast(&count), sizeof(count)); + putNear("ARROW:extension:names"); + putNear("x"); + putNear("ARROW:extension:nam"); + putNear("y"); + check(arrowExtensionName(near.data()).empty(), "a key is matched whole"); + + const int32_t none = 0; + check(arrowExtensionName(reinterpret_cast(&none)).empty(), "metadata with no entries"); } ArrowOwnedArray ownedInt64(std::vector values) @@ -449,7 +467,9 @@ ArrowOwnedArray ownedInt64(std::vector values) array.buffers.resize(2); array.buffers[1].present = true; array.buffers[1].bytes.resize(values.size() * sizeof(int64_t)); - std::memcpy(array.buffers[1].bytes.data(), values.data(), array.buffers[1].bytes.size()); + // An empty vector's data() may be null, and memcpy from null is undefined even for no bytes. + if (!values.empty()) + std::memcpy(array.buffers[1].bytes.data(), values.data(), array.buffers[1].bytes.size()); return array; } @@ -574,17 +594,188 @@ void testWriteErrorMessage() writeErrorMessage("much too long", buffer, sizeof(buffer)); check(std::strcmp(buffer, "much to") == 0, "a long one is cut to size - 1 bytes"); - // "aaaaaé" is 7 bytes, the last two one character: cut at 7 bytes it would end in half of it. + // Cut at 7 bytes, "aaaaaa\xc3\xa9!" would end in the first half of the e-acute. std::memset(buffer, 'x', sizeof(buffer)); writeErrorMessage("aaaaaa\xc3\xa9!", buffer, sizeof(buffer)); check(std::strcmp(buffer, "aaaaaa") == 0, "the cut does not split a UTF-8 character"); + // The same at the other character widths: three bytes (the euro sign) and four (an emoji). + writeErrorMessage("abcdef\xe2\x82\xac", buffer, sizeof(buffer)); + check(std::strcmp(buffer, "abcdef") == 0, "a three-byte character is not split"); + writeErrorMessage("abcde\xf0\x9f\x98\x80", buffer, sizeof(buffer)); + check(std::strcmp(buffer, "abcde") == 0, "a four-byte character is not split"); + writeErrorMessage("abc\xf0\x9f\x98\x80", buffer, sizeof(buffer)); + check(std::strcmp(buffer, "abc\xf0\x9f\x98\x80") == 0, "a character that fits is kept whole"); + + // Exactly size - 1 bytes fit; one more is cut. + writeErrorMessage("1234567", buffer, sizeof(buffer)); + check(std::strcmp(buffer, "1234567") == 0, "size - 1 bytes fit"); + writeErrorMessage("12345678", buffer, sizeof(buffer)); + check(std::strcmp(buffer, "1234567") == 0, "size bytes do not"); + + char two[2] = {'x', 'x'}; + writeErrorMessage("\xc3\xa9", two, sizeof(two)); + check(two[0] == '\0', "no room for a whole character leaves the message empty, not half of one"); + char one[1] = {'x'}; writeErrorMessage("anything", one, sizeof(one)); check(one[0] == '\0', "a one-byte buffer gets the terminator"); writeErrorMessage("anything", nullptr, 0); } +void testArrowLayoutEdges() +{ + std::string error; + const uint8_t bits[4] = {0xff, 0xff, 0xff, 0xff}; + const int64_t longs[8] = {0}; + + // The rest of the fixed widths: half floats, times, dates in milliseconds, durations, intervals, + // a timestamp without a zone, and decimals whose width is named. + const std::pair widths[] = { + {"e", 2}, {"tts", 4}, {"ttm", 4}, {"ttu", 8}, {"ttn", 8}, {"tdm", 8}, {"tDs", 8}, {"tDn", 8}, + {"tiM", 4}, {"tiD", 8}, {"tin", 16}, {"tsu:", 8}, {"d:9,2,32", 4}, {"d:18,2,64", 8}, {"d:38,10,128", 16}}; + for (const auto & width : widths) + { + TestArray test(width.first, 2, 1, {nullptr, longs}); + auto extents = extentsOf(test, error); + check(extents.size() == 2 && extents[1].size == static_cast(3 * width.second), + std::string("offset plus length slots of ") + width.first); + } + // A bitmap of exactly eight slots is one byte, not two. + { + TestArray test("b", 8, 0, {bits, bits}); + auto extents = extentsOf(test, error); + check(extents.size() == 2 && extents[0].size == 1 && extents[1].size == 1, "eight bits are one byte"); + } + // The null type has no buffers at all. + { + TestArray test("n", 5, 0, {}); + check(extentsOf(test, error).empty() && error.empty(), "a null array has no buffers"); + } + // 64-bit offsets, for a large list and, with an offset, for large text. + { + const int64_t offsets[] = {0, 1, 4, 6}; + TestArray list("+L", 2, 1, {nullptr, offsets}); + auto extents = extentsOf(list, error); + check(extents.size() == 2 && extents[1].size == 4 * 8, "large list offsets"); + TestArray text("U", 2, 1, {nullptr, offsets, "abcdef"}); + extents = extentsOf(text, error); + check(extents.size() == 3 && extents[1].size == 4 * 8 && extents[2].size == 6, "large text ends at its last offset"); + } + // A fixed-size list has a bitmap and no offsets; its child carries the values. + { + TestArray test("+w:3", 4, 0, {bits}); + auto extents = extentsOf(test, error); + check(extents.size() == 1 && extents[0].size == 1, "fixed-size list"); + } + const char * refused[] = {"+w:0", "w:0", "d:0,2", "tsx:UTC", "ts", "tDx", "tiX", "d:10"}; + for (const char * format : refused) + { + TestArray test(format, 1, 0, {nullptr, longs}); + check(extentsOf(test, error).empty() && !error.empty(), std::string("refuses ") + format); + } + { + TestArray test("l", int64_t{1} << 41, 0, {nullptr, longs}); + check(extentsOf(test, error).empty() && !error.empty(), "refuses a length no batch has"); + } + + // Exports. A batch of no rows: an empty data buffer may be exported as a null pointer, which + // C Data allows for a buffer of zero bytes, and still releases cleanly. + { + ArrowOwnedArray empty; + empty.format = "u"; + empty.buffers.resize(3); + empty.buffers[1].present = true; + empty.buffers[1].bytes.assign(sizeof(int32_t), 0); + empty.buffers[2].present = true; + ArrowSchema schema{}; + ArrowArray array{}; + check(exportArrowArray(std::move(empty), &schema, &array, error), "exports no rows of text"); + check(array.length == 0 && array.n_buffers == 3 && array.buffers[1] != nullptr, "the one offset is there"); + schema.release(&schema); + array.release(&array); + } + // A list of tuples: "item", then the fields by position; and a fixed-size list's child. + { + ArrowOwnedArray tuple; + tuple.format = "+s"; + tuple.length = 2; + tuple.buffers.resize(1); + tuple.children.push_back(ownedInt64({1, 2})); + tuple.children.push_back(ownedInt64({3, 4})); + ArrowOwnedArray list; + list.format = "+l"; + list.length = 1; + list.buffers.resize(2); + list.buffers[1].present = true; + const int32_t offsets[] = {0, 2}; + list.buffers[1].bytes.assign(reinterpret_cast(offsets), reinterpret_cast(offsets) + sizeof(offsets)); + list.children.push_back(std::move(tuple)); + ArrowSchema schema{}; + ArrowArray array{}; + check(exportArrowArray(std::move(list), &schema, &array, error), "exports a list of tuples"); + const ArrowSchema * item = schema.children[0]; + check(std::strcmp(item->name, "item") == 0 && item->n_children == 2 && std::strcmp(item->children[1]->name, "2") == 0, + "nested children are named at every level"); + check(array.children[0]->children[1]->length == 2, "a nested child keeps its length"); + schema.release(&schema); + array.release(&array); + + ArrowOwnedArray fixed; + fixed.format = "+w:2"; + fixed.length = 2; + fixed.offset = 1; + fixed.buffers.resize(1); + fixed.children.push_back(ownedInt64({1, 2, 3, 4, 5, 6})); + check(exportArrowArray(std::move(fixed), &schema, &array, error), "exports a fixed-size list"); + check(array.n_buffers == 1 && array.offset == 1 && std::strcmp(schema.children[0]->name, "item") == 0, + "a fixed-size list keeps its offset and names its child"); + schema.release(&schema); + array.release(&array); + + ArrowOwnedArray nothing; + nothing.format = "+s"; + nothing.length = 3; + nothing.buffers.resize(1); + check(exportArrowArray(std::move(nothing), &schema, &array, error), "exports a struct of no fields"); + check(schema.n_children == 0 && schema.children == nullptr && array.length == 3, "no fields, three rows"); + schema.release(&schema); + array.release(&array); + } + // What is refused leaves both structs as they were. + auto refusedExport = [&error](ArrowOwnedArray owned, const char * what) + { + ArrowSchema schema{}; + ArrowArray array{}; + const bool exported = exportArrowArray(std::move(owned), &schema, &array, error); + check(!exported && !error.empty() && schema.release == nullptr && array.release == nullptr, + std::string("refuses ") + what); + }; + { + ArrowOwnedArray negative = ownedInt64({1}); + negative.offset = -1; + refusedExport(std::move(negative), "a negative offset"); + } + { + ArrowOwnedArray map; + map.format = "+m"; + map.buffers.resize(2); + map.children.push_back(ownedInt64({})); + refusedExport(std::move(map), "a map whose child is not a struct"); + } + { + ArrowOwnedArray entries; + entries.format = "+s"; + entries.buffers.resize(1); + entries.children.push_back(ownedInt64({})); + ArrowOwnedArray map; + map.format = "+m"; + map.buffers.resize(2); + map.children.push_back(std::move(entries)); + refusedExport(std::move(map), "a map whose entries are not a key and a value"); + } +} + } // namespace int main() @@ -598,6 +789,7 @@ int main() testArrowExtensionName(); testExportArrowArray(); testWriteErrorMessage(); + testArrowLayoutEdges(); std::printf("\n%d checks, %d failures\n", checks, failures); return failures == 0 ? 0 : 1; diff --git a/docs/scalar-functions.md b/docs/scalar-functions.md index a8892d4..0a5de3d 100644 --- a/docs/scalar-functions.md +++ b/docs/scalar-functions.md @@ -168,9 +168,9 @@ again under its name. ## Binary strings -A `String` argument arrives as a Java `String`, so text that is not valid UTF-8 fails the query. -`withBinaryStrings()` passes `String` and `FixedString` arguments as `byte[]` instead, nested ones -included, for binary data: +A `String` or `FixedString` argument arrives as a Java `String`, so text that is not valid UTF-8 +fails the query. `withBinaryStrings()` passes `String` and `FixedString` arguments as `byte[]` +instead, nested ones included, for binary data: ```java ChdbFunctions.scalarFunction()