Skip to content

Move the driver logic to Java on top of C API v2 entry points - #1017

Open
Robinho-MR wants to merge 10 commits into
duckdb:mainfrom
Robinho-MR:java-v2-port
Open

Robinho-MR wants to merge 10 commits into
duckdb:mainfrom
Robinho-MR:java-v2-port

Conversation

@Robinho-MR

@Robinho-MR Robinho-MR commented Nov 27, 2026 •

Copy link
Copy Markdown

Moves the driver logic from C++ into Java, on top of thin native entry points that map 1:1 to C API v2 calls (duckdb_v2_* in DuckDBBindings). src/jni does not include any engine header anymore. This is the direction discussed in #1010, it replaces that approach (the stable C++ API) with the C API v2.

// DuckDBNative.duckdb_jdbc_execute(stmt, params) is now plain Java over the entry points:
ByteBuffer result = duckdb_v2_prepared_statement_execute(prepared, values);
ByteBuffer chunk = duckdb_v2_result_fetch_chunk(result);
Details

What changed

  • Entry points: src/jni/bindings_v2.cpp has the thin JNI entry points, one per C API v2 call, without driver logic: instances, connections, configuration and custom options, parsing, prepared statements, execution, schemas, results, values, types, vectors, column data collections, profiling. The names are the C API names, so they can later be replaced by FFM calls.
  • Statements and results: DuckDBCore implements prepare, multi-statement handling, execute, pending queries, streaming and materialized results, result metadata, fetching (the former ProcessVector), the string casts, parameter conversion, schema and catalog in Java. The DuckDBNative.duckdb_jdbc_* signatures that the rest of the driver calls are kept, they now delegate to DuckDBCore and DuckDBInstances.
  • Startup and connections: DuckDBInstances opens the instances (duckdb_v2_instance_open_shared with an initializer for the shared ones, an environment of its own for the others) and connections, registers the jdbc_stream_results option, writes the settings that need a running instance, copies the session settings in duplicate(). The connection reference is the C API v2 connection handle, the instance is reference counted in Java.
  • Appenders: C API v2 has no appender, so DuckDBAppender and DuckDBSingleValueAppender use DuckDBV2Appender: the chunks are collected into a column data collection and a prepared INSERT INTO table SELECT * FROM <collection> is executed on flush.
  • Arrow: src/jni/arrow_export.cpp. An Arrow stream is a C structure with callbacks, so it cannot be implemented in Java. The export binds the rows of a result to SELECT * FROM <rows> that runs with the Arrow result format on a connection of its own, the stream owns it and is closed with the connection if it is not released before. registerArrowStream registers the stream with a table function (__jdbc_arrow_stream_scan, written over the C API v2 table function and Arrow importer calls) that a view of the stream selects from.
  • Removed: the generated native entry points (functions.*, generator.py), config.cpp, holders of the engine, types.cpp, arrow.cpp, the appender bindings of the C API v1.
  • Vendoring: the vendored sources have Add Value::VariantToValue to the v2 C API and C++ API duckdb#29425 applied by hand (Value::VariantToValue), the next run of the vendoring workflow replaces it.

Differences that I know of

  • C API v2 has one live result per connection. Queries on a connection are run one by one (DuckDBConnection.queryGate), and a result that is streamed (jdbc_stream_results) blocks the next query on its connection until it is closed.

  • The batches of an exported Arrow stream are at most the requested size and can be smaller, as the threads of the query fill them (the Javadoc and two Arrow tests say so now).

  • Preparing a statement plans it twice, once to prepare and once (statement_bind) to get the column and parameter types, as C API v2 has no metadata of a prepared statement.

  • Error messages come from the C API v2. A shared instance that is opened with a different configuration fails with a message of the C API v2.

  • Reading results: the vectors are read from their raw data in Java: the fixed-size values and the validity directly from the vector buffers, the strings of up to 12 bytes from the 16-byte entries of the vector, and the longer ones (or the types that are read as strings, e.g. ENUM and INTERVAL, after a cast by the engine) with one call per vector. There are no calls per value.

  • Native calls per query: a few calls per result (the names and the type IDs of the columns are read for all the columns at once, the config and the factory of the connection are kept, the metadata of a statement is cached when the types have no parameters, the types of a prepared statement are read when its metadata is asked), which is what matters for the small queries.

  • Performance compared to the unchanged driver (main), on the same loaded machine (load average of 70 on 96 cores, so noisy), seconds, lower is better:

    main this PR
    scan 10M integers 0.18 0.20
    scan 2M strings 1.84 0.17
    scan 1M long strings 0.91 0.11
    scan 500k structs 0.79 0.07
    scan 500k lists 0.15 0.06
    scan 1M enum 0.59 0.08
    scan 2M decimals / dates / timestamps 0.09 / 0.12 / 0.19 0.09 / 0.08 / 0.19
    chunk appender, 2M rows 0.77 0.76
    50k tiny prepared executions 3.0-3.3 3.6
    5k prepares 1.24 1.15

    A tiny query is about 10-15% slower: the part that is left is in the C API v2 result (prepared_statement_execute, then one result_fetch_chunk for the rows and one for the end of the result), not in the driver.

Tests

  • TestDuckDBJDBC (all the test classes it runs): 595 pass. The one failure is test_table_function_multiple_threads, which expects as many threads as processors and gets 1 when the machine is loaded, same as on the unchanged driver.
  • src/test/external/test_arrow.sh: 35 of 35 pass.
  • TestBindings has the appender tests moved to DuckDBV2Appender, as the appender bindings of the C API v1 do not exist anymore.
  • Not run: the Spark, GraalVM, DuckLake and MinIO external tests, sanitizers, other platforms.

@Robinho-MR
Robinho-MR marked this pull request as ready for review November 27, 2026 15:30
@staticlibs

Copy link
Copy Markdown
Member

@Robinho-MR

Thanks for the update! It will take some time to review it, meanwhile can you please check, whether the former ProcessVector logic (original source for JDBC-standard result set) can now be unified with DuckDBChunkedResult.java (non-standard low-overhead direct DataChunk reader) - for example be built on top of it adding necessary type conversions there?

@Robinho-MR

Copy link
Copy Markdown
Author

@staticlibs thanks, I looked at it. In this PR ProcessVector is DuckDBCore.processVector (Java, on top of the v2 vector API), so the question is whether the DuckDBVector it builds can sit on DuckDBReadableVector/DuckDBDataChunkReader.

What overlaps

  • Type classification and element width (DuckDBVectorTypeInfo vs fixedWidth/decimalWidth/the type-detail string).
  • Reading data and validity from the vector (duckdb_vector_get_data/get_validity, the validity bit test).
  • The fixed-width conversions: DECIMAL, DATE, TIMESTAMP(_S/_MS/_NS/_TZ), HUGEINT/UHUGEINT, unsigned types.
  • Strings. DuckDBReadableVector.getString still does one native call per value (duckdb_vector_get_string), while readStringData in DuckDBCore reads inlined strings from the vector data directly and copies all long ones with one call. The reader should use the same code.

What differs

  • DuckDBReadableVector is lazy and strict: it requires the exact type and throws on NULL for primitives, supports no nested types, BLOB, UUID, TIME*, ENUM or VARIANT, and is only valid while the chunk is open.
  • DuckDBVector is eager and lenient: it materializes a null mask and strings per chunk, the ResultSet getters convert between types (getInt on a BIGINT column, getTimestamp(Calendar), ...), and nested values (LIST/ARRAY/STRUCT/MAP/UNION/VARIANT) are DuckDBVectors themselves because DuckDBArray/DuckDBStruct need to keep them after the chunk is advanced.

What I'd do

  1. Move the shared pieces below both: extend DuckDBVectorTypeInfo to all the types and use it in processVector instead of the width tables and type-detail strings. Add one string/BLOB bulk reader and one validity reader, used by both.
  2. Add the missing scalar types (HUGEINT conversions, TIME*, BLOB, UUID) to DuckDBReadableVector, then make the scalar getters of DuckDBVector delegate to it, keeping the lenient conversions in DuckDBVector.
  3. Leave nested types and the eager null mask/strings of DuckDBVector as they are.

A full replacement (the ResultSet reading directly through the lazy reader) isn't something I'd do in this PR. ResultSet access is random access by row and column, and the eager copy is what keeps Array/Struct/Blob objects valid after next(). It also changes lifetime and locking behaviour (chunkRefLock per call) in the hot path, and I'd want to benchmark that separately.

I'd rather do steps 1 and 2 as a separate follow-up PR, so that this one stays reviewable and the results/perf here don't change. Does that match what you had in mind, or did you want the lazy reader to be the only path?

@staticlibs

Copy link
Copy Markdown
Member

@Robinho-MR

I'd rather do steps 1 and 2 as a separate follow-up PR, so that this one stays reviewable and the results/perf here don't change. Does that match what you had in mind, or did you want the lazy reader to be the only path?

Yes, I agree with this. Ultimately we want to unify both code paths, modifying their lazyness and strictness (as needed and as much as allowed by JDBC spec). But it is indeed better to do this as a follow-up. I will submit the review to this PR (in its current form) when the review is ready.

@staticlibs

Copy link
Copy Markdown
Member

@Robinho-MR

General comments:

  1. remove DuckDBSingleValueAppender completely, it was kept for compatibility and is no longer needed (should have been removed earlier)

  2. in JNI layer, to every new function that implements a JNI entry point add a comment on top with the signature like this:

/*
 * Class:     org_duckdb_DuckDBBindings
 * Method:    duckdb_init_get_column_count
 * Signature: (Ljava/nio/ByteBuffer;)J
 */

Also please check whether the following comments can be addressed:

[
  {
    "file": "src/main/java/org/duckdb/DuckDBInstances.java",
    "line": 27,
    "summary": "`allowed_directories` and `allowed_paths` are now set with SET GLOBAL after startup. DuckDB refuses that when `enable_external_access=false`, which the old `config.cpp` worked around by writing them straight into DBConfig.",
    "failure_scenario": "Properties `{enable_external_access=false, allowed_directories=[\"/data\"]}` is the usual sandboxing setup. `initInstance` calls `duckdb_v2_config_set_option_text`, which throws 'Cannot change allowed_directories when enable_external_access is disabled' (custom_settings.cpp:301), so `DriverManager.getConnection` fails. Before this change it succeeded."
  },
  {
    "file": "src/main/java/org/duckdb/DuckDBV2Appender.java",
    "line": 65,
    "summary": "The appender takes its columns from `SELECT * FROM table`, which includes generated columns. It then builds `INSERT INTO t (all columns) SELECT * FROM buffer`, and DuckDB rejects that whenever the table has a generated column.",
    "failure_scenario": "`CREATE TABLE t(a INT, b INT GENERATED ALWAYS AS (a*2))`. Appending through `DuckDBAppender` fails on every `flush()` with 'Cannot insert into a generated column'. The appender also asks the caller for 2 values per row instead of 1. The old `duckdb_appender_create_ext` only exposed physical columns and worked."
  },
  {
    "file": "src/main/java/org/duckdb/DuckDBV2Appender.java",
    "line": 215,
    "summary": "Column defaults are looked up in `duckdb_columns()` with an exact, case-sensitive `table_name` match. When no schema or catalog is given, the lookup is not limited to one table, so defaults are missing or taken from the wrong table.",
    "failure_scenario": "(a) Table created as `Foo`, appender opened as `foo`: no rows match, so `appendDefault` writes NULL instead of the declared DEFAULT. (b) Both `main.t` and `temp.t` exist and schema is null: the rows of both tables come back interleaved by column_index, so column i gets another table's default."
  },
  {
    "file": "src/main/java/org/duckdb/DuckDBCore.java",
    "line": 1390,
    "summary": "`variantToVector` copies only the top-level vector's data (`retainConstlenData`) and then destroys the temporary vector. Child vectors of LIST/STRUCT/ARRAY values still point into the freed native memory (use-after-free).",
    "failure_scenario": "`SELECT [1,2,3]::VARIANT`, then `rs.getObject(1)` and reading the array. The child INTEGER vector's direct buffer points into the destroyed `single` vector, so the read returns garbage or crashes the JVM under ASan. No test covers nested VARIANT values."
  },
  {
    "file": "src/main/java/org/duckdb/DuckDBSingleValueAppender.java",
    "line": 34,
    "summary": "The rewritten `DuckDBSingleValueAppender` holds native collection, statement and chunk handles tied to the instance, but it is not tracked in `conn.appenders`. Closing the connection does not close it, and a later `close()` uses freed instance memory.",
    "failure_scenario": "Open a connection, create the appender, append rows, close the connection (last ref, so the instance is destroyed), then call `appender.close()`. `appendChunk` and `column_data_collection_clear/destroy` run against a freed buffer manager. The old engine Appender held a `shared_ptr<ClientContext>`, which kept the DB alive."
  },
  {
    "file": "src/main/java/org/duckdb/DuckDBCore.java",
    "line": 475,
    "summary": "`getSchema`, `getCatalog`, `setSchema` and `setCatalog` now run SQL statements on the user's connection instead of reading or setting the catalog search path directly.",
    "failure_scenario": "With `jdbc_stream_results=true`, calling `conn.getSchema()` (or DatabaseMetaData code that calls it) while a streaming ResultSet is open runs a new query, which invalidates the open stream; the next `rs.next()` fails. Inside a transaction that already failed (autoCommit=false), `getSchema()` now throws 'Current transaction is aborted' where it used to return the schema."
  },
  {
    "file": "src/main/java/org/duckdb/DuckDBInstances.java",
    "line": 249,
    "summary": "For cached instances, `dbAddress` is now a 32-bit `String.hashCode` of the path (ORed with 1) instead of the real DatabaseInstance address, so two different database files can share an identity.",
    "failure_scenario": "Two cached databases whose normalized paths collide in `hashCode`, both opened with a JFR memory monitor. `DuckDBMemoryMonitor.monitors.compute(conn.dbAddress, ...)` merges them into one monitor, so memory is reported for the wrong DB and the monitor can be torn down while the other DB is still open."
  },
  {
    "file": "src/main/java/org/duckdb/DuckDBCore.java",
    "line": 706,
    "summary": "`exportArrow` first copies the whole result, including all of a streamed result, into a ColumnDataCollection, then runs a second query to produce Arrow batches. Streaming results are fully held in memory, the rows are copied twice, and batch sizes are no longer exact (the TestArrow assertions were loosened to hide this).",
    "failure_scenario": "A large streaming SELECT exported with `arrowExportStream`: the old code streamed batches directly from the QueryResult. The new code buffers every row in memory before the first batch, which can run out of memory on results that used to stream. Consumers that relied on fixed batch sizes now get variable, smaller batches."
  },
  {
    "file": "src/main/java/org/duckdb/DuckDBV2Appender.java",
    "line": 234,
    "summary": "Each `appendDefault` call runs a full SQL query (`SELECT <default expr>`, which takes the connection's query lock) for every row and column. Each flush also re-plans the unprepared INSERT ... SELECT from scratch.",
    "failure_scenario": "Appending 1M rows with 2 defaulted columns runs 2M separate parse/bind/execute round trips over JNI, plus one fresh INSERT plan per 2048-row chunk. Before, defaults were evaluated inside the engine's appender. Cheaper: rely on the column defaults of `INSERT INTO t (non-default columns)`, or prepare the INSERT once and reuse it, instead of evaluating defaults row by row."
  }
]

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants