Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .agents/skills/chdb-arrow/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
5 changes: 3 additions & 2 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
53 changes: 44 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.<n>`
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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -202,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

| | |
Expand All @@ -215,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` |
Expand Down Expand Up @@ -268,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 |
Expand Down Expand Up @@ -316,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-<platform>/ one Maven package per platform
chdb-bom/ legacy RC BOM (not published to Central)
chdb-integration-tests/ tests that need a real engine
Expand Down
60 changes: 50 additions & 10 deletions chdb-arrow/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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")
.withVectorizedFunction((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
Expand Down Expand Up @@ -238,15 +278,15 @@ 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 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:

Expand All @@ -269,7 +309,7 @@ platform, and run its `scripts/build-native.sh <platform-id>` 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`.
2 changes: 1 addition & 1 deletion chdb-arrow/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<parent>
<groupId>com.clickhouse.chdb</groupId>
<artifactId>chdb-java-parent</artifactId>
<version>1.1.0</version>
<version>1.2.0-SNAPSHOT</version>
</parent>
<artifactId>chdb-arrow</artifactId>
<properties>
Expand Down
61 changes: 61 additions & 0 deletions chdb-arrow/src/main/java/org/chdb/arrow/ArrowFunctionCallback.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
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.
*
* <h2>Memory</h2>
* 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 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();
}
}
38 changes: 38 additions & 0 deletions chdb-arrow/src/main/java/org/chdb/arrow/ArrowFunctions.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package org.chdb.arrow;

/**
* Scalar user-defined functions computed with Arrow vectors, a batch of rows per call.
*
* <pre>{@code
* ArrowFunctions.scalarFunction()
* .withName("weighted")
* .withParameters("Float64", "Float64")
* .withReturnType("Float64")
* .withVectorizedFunction((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);
* }</pre>
*
* <p>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();
}
}
Loading
Loading