From 51a6ddd7747b8ba6970c66efaabc292ca2e1d823 Mon Sep 17 00:00:00 2001 From: Robinho-MR Date: Fri, 27 Nov 2026 13:41:52 +0000 Subject: [PATCH 01/21] Add thin C API v2 JNI entry points --- CMakeLists.txt | 1 + CMakeLists.txt.in | 1 + src/jni/bindings_v2.cpp | 505 +++++++++++++++++++ src/main/java/org/duckdb/DuckDBBindings.java | 134 +++++ 4 files changed, 641 insertions(+) create mode 100644 src/jni/bindings_v2.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index e6b2b45a4..a655e3d0f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -669,6 +669,7 @@ add_library(duckdb_java SHARED src/jni/bindings_table_function.cpp src/jni/bindings_table_function_bind.cpp src/jni/bindings_table_function_init.cpp + src/jni/bindings_v2.cpp src/jni/bindings_validity.cpp src/jni/bindings_vector.cpp src/jni/bindings_value.cpp diff --git a/CMakeLists.txt.in b/CMakeLists.txt.in index ddbd6cce8..a5221e688 100644 --- a/CMakeLists.txt.in +++ b/CMakeLists.txt.in @@ -148,6 +148,7 @@ add_library(duckdb_java SHARED src/jni/bindings_table_function.cpp src/jni/bindings_table_function_bind.cpp src/jni/bindings_table_function_init.cpp + src/jni/bindings_v2.cpp src/jni/bindings_validity.cpp src/jni/bindings_vector.cpp src/jni/bindings_value.cpp diff --git a/src/jni/bindings_v2.cpp b/src/jni/bindings_v2.cpp new file mode 100644 index 000000000..38195d13e --- /dev/null +++ b/src/jni/bindings_v2.cpp @@ -0,0 +1,505 @@ +// Thin JNI entry points over the C API v2 calls, one entry point per call. They contain no driver logic: +// the logic that uses them is implemented in Java. +#include "bindings.hpp" +#include "holders.hpp" +#include "refs.hpp" +#include "util.hpp" + +#include + +template +static H buf_to_handle(JNIEnv *env, jobject buf, const char *what) { + if (buf == nullptr) { + env->ThrowNew(J_SQLException, (std::string("Invalid ") + what + " buffer").c_str()); + return nullptr; + } + auto handle = reinterpret_cast(env->GetDirectBufferAddress(buf)); + if (handle == nullptr) { + env->ThrowNew(J_SQLException, (std::string("Invalid ") + what).c_str()); + return nullptr; + } + return handle; +} + +// An interrupted query is reported to Java as a timeout, same as the C++ part of the driver does +static void throw_v2_error(JNIEnv *env, const v2_error &err) { + if (env->ExceptionCheck()) { + return; + } + jclass type = err.code() == DUCKDB_V2_ERROR_RUNTIME_INTERRUPT ? J_SQLTimeoutException : J_SQLException; + env->ThrowNew(type, err.message().c_str()); +} + +#define CHECK_BUF(var, buf, T, what) \ + auto var = buf_to_handle(env, buf, what); \ + if (env->ExceptionCheck()) { \ + return; \ + } + +#define CHECK_BUF_RET(var, buf, T, what, ret) \ + auto var = buf_to_handle(env, buf, what); \ + if (env->ExceptionCheck()) { \ + return ret; \ + } + +#define CALL_V2(call, ret) \ + do { \ + v2_error err; \ + if ((call) != DUCKDB_V2_ERROR_NONE) { \ + throw_v2_error(env, err); \ + return ret; \ + } \ + } while (0) + +// The `err` out parameter of a call, used inside CALL_V2 only +#define ERR_OUT err.out() + +/* --- connection --- */ + +// Transitional: the C API v2 handle of the connection of a connection holder +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1from_1ref(JNIEnv *env, jclass, jobject conn_ref) { + auto conn = conn_ref_buf_to_conn(env, conn_ref); + if (env->ExceptionCheck()) { + return nullptr; + } + return make_ptr_buf(env, conn); +} + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1interrupt(JNIEnv *env, jclass, jobject conn_buf) { + CHECK_BUF(conn, conn_buf, duckdb_v2_connection_handle, "connection"); + CALL_V2(duckdb_v2_connection_interrupt(conn, ERR_OUT), ); +} + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1progress_1get(JNIEnv *env, jclass, jobject conn_buf) { + CHECK_BUF_RET(conn, conn_buf, duckdb_v2_connection_handle, "connection", nullptr); + double percentage = -1; + uint64_t rows_processed = 0; + uint64_t total_rows = 0; + CALL_V2(duckdb_v2_connection_progress_get(conn, &percentage, &rows_processed, &total_rows, ERR_OUT), nullptr); + return env->NewObject(J_QueryProgress, J_QueryProgress_init, static_cast(percentage), + uint64_to_jlong(rows_processed), uint64_to_jlong(total_rows)); +} + +/* --- parsing --- */ + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1parse_1sql(JNIEnv *env, jclass, jobject conn_buf, jbyteArray sql_j) { + CHECK_BUF_RET(conn, conn_buf, duckdb_v2_connection_handle, "connection", nullptr); + auto sql = jbyteArray_to_string(env, sql_j); + if (env->ExceptionCheck()) { + return nullptr; + } + duckdb_v2_statement_iterator_handle it = nullptr; + CALL_V2(duckdb_v2_parse_sql(conn, sql.data(), sql.size(), false, &it, ERR_OUT), nullptr); + return make_ptr_buf(env, it); +} + +// Returns null when there are no more statements +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1iterator_1next(JNIEnv *env, jclass, jobject it_buf) { + CHECK_BUF_RET(it, it_buf, duckdb_v2_statement_iterator_handle, "statement iterator", nullptr); + duckdb_v2_sql_statement_handle statement = nullptr; + CALL_V2(duckdb_v2_statement_iterator_next(it, &statement, ERR_OUT), nullptr); + return make_ptr_buf(env, statement); +} + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1iterator_1destroy(JNIEnv *env, jclass, jobject it_buf) { + CHECK_BUF(it, it_buf, duckdb_v2_statement_iterator_handle, "statement iterator"); + duckdb_v2_statement_iterator_destroy(&it); +} + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement_1destroy(JNIEnv *env, jclass, jobject st_buf) { + CHECK_BUF(st, st_buf, duckdb_v2_sql_statement_handle, "statement"); + duckdb_v2_sql_statement_destroy(&st); +} + +JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement_1get_1type(JNIEnv *env, jclass, jobject st_buf) { + CHECK_BUF_RET(st, st_buf, duckdb_v2_sql_statement_handle, "statement", 0); + DUCKDB_V2_STATEMENT_TYPE type = DUCKDB_V2_STATEMENT_TYPE_INVALID; + CALL_V2(duckdb_v2_sql_statement_get_type(st, &type, ERR_OUT), 0); + return static_cast(type); +} + +JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement_1get_1parameter_1count(JNIEnv *env, jclass, jobject st_buf) { + CHECK_BUF_RET(st, st_buf, duckdb_v2_sql_statement_handle, "statement", 0); + idx_t count = 0; + CALL_V2(duckdb_v2_sql_statement_get_parameter_count(st, &count, ERR_OUT), 0); + return uint64_to_jlong(count); +} + +/* --- prepared statements --- */ + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1prepared_1statement_1create(JNIEnv *env, jclass, jobject conn_buf, jobject st_buf, + jboolean require_cacheable) { + CHECK_BUF_RET(conn, conn_buf, duckdb_v2_connection_handle, "connection", nullptr); + CHECK_BUF_RET(st, st_buf, duckdb_v2_sql_statement_handle, "statement", nullptr); + duckdb_v2_prepared_statement_handle prepared = nullptr; + CALL_V2(duckdb_v2_prepared_statement_create(conn, st, require_cacheable == JNI_TRUE, &prepared, ERR_OUT), nullptr); + return make_ptr_buf(env, prepared); +} + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1prepared_1statement_1destroy(JNIEnv *env, jclass, jobject prepared_buf) { + CHECK_BUF(prepared, prepared_buf, duckdb_v2_prepared_statement_handle, "prepared statement"); + duckdb_v2_prepared_statement_destroy(&prepared); +} + +// The values of the positional parameters are borrowed for the call +static bool read_values(JNIEnv *env, jobjectArray values_j, std::vector &values) { + if (values_j == nullptr) { + return true; + } + jsize count = env->GetArrayLength(values_j); + for (jsize i = 0; i < count; i++) { + jobject value_buf = env->GetObjectArrayElement(values_j, i); + auto value = buf_to_handle(env, value_buf, "value"); + env->DeleteLocalRef(value_buf); + if (env->ExceptionCheck()) { + return false; + } + values.push_back(value); + } + return true; +} + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1prepared_1statement_1execute(JNIEnv *env, jclass, jobject prepared_buf, + jobjectArray values_j) { + CHECK_BUF_RET(prepared, prepared_buf, duckdb_v2_prepared_statement_handle, "prepared statement", nullptr); + std::vector values; + if (!read_values(env, values_j, values)) { + return nullptr; + } + duckdb_v2_result_handle result = nullptr; + CALL_V2(duckdb_v2_prepared_statement_execute(prepared, nullptr, nullptr, values.data(), values.size(), &result, + ERR_OUT), + nullptr); + return make_ptr_buf(env, result); +} + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1execute(JNIEnv *env, jclass, jobject conn_buf, jobject st_buf, + jobjectArray values_j) { + CHECK_BUF_RET(conn, conn_buf, duckdb_v2_connection_handle, "connection", nullptr); + CHECK_BUF_RET(st, st_buf, duckdb_v2_sql_statement_handle, "statement", nullptr); + std::vector values; + if (!read_values(env, values_j, values)) { + return nullptr; + } + duckdb_v2_result_handle result = nullptr; + CALL_V2(duckdb_v2_statement_execute(conn, st, nullptr, nullptr, values.data(), values.size(), &result, ERR_OUT), + nullptr); + return make_ptr_buf(env, result); +} + +// Returns the output schema and the parameters schema +JNIEXPORT jobjectArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1bind(JNIEnv *env, jclass, jobject conn_buf, jobject st_buf) { + CHECK_BUF_RET(conn, conn_buf, duckdb_v2_connection_handle, "connection", nullptr); + CHECK_BUF_RET(st, st_buf, duckdb_v2_sql_statement_handle, "statement", nullptr); + v2_schema output; + v2_schema parameters; + CALL_V2(duckdb_v2_statement_bind(conn, st, output.out(), parameters.out(), ERR_OUT), nullptr); + auto res = env->NewObjectArray(2, J_ByteBuffer, nullptr); + if (res == nullptr) { + return nullptr; + } + jobject output_buf = make_ptr_buf(env, output.get()); + if (output_buf == nullptr) { + return nullptr; + } + output.release(); + env->SetObjectArrayElement(res, 0, output_buf); + jobject parameters_buf = make_ptr_buf(env, parameters.get()); + if (parameters_buf != nullptr) { + parameters.release(); + env->SetObjectArrayElement(res, 1, parameters_buf); + } + return res; +} + +/* --- schemas --- */ + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1destroy(JNIEnv *env, jclass, jobject schema_buf) { + CHECK_BUF(schema, schema_buf, duckdb_v2_schema_handle, "schema"); + duckdb_v2_schema_destroy(&schema); +} + +JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1count(JNIEnv *env, jclass, jobject schema_buf) { + CHECK_BUF_RET(schema, schema_buf, duckdb_v2_schema_handle, "schema", 0); + idx_t count = 0; + CALL_V2(duckdb_v2_schema_get_count(schema, &count, ERR_OUT), 0); + return uint64_to_jlong(count); +} + +JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1name(JNIEnv *env, jclass, jobject schema_buf, jlong index) { + CHECK_BUF_RET(schema, schema_buf, duckdb_v2_schema_handle, "schema", nullptr); + idx_t idx = jlong_to_idx(env, index); + if (env->ExceptionCheck()) { + return nullptr; + } + const char *name = nullptr; + idx_t name_len = 0; + duckdb_v2_logical_type_handle type = nullptr; + CALL_V2(duckdb_v2_schema_get_field(schema, idx, &name, &name_len, &type, ERR_OUT), nullptr); + return make_jbyteArray(env, name, name_len); +} + +// The returned type is borrowed from the schema and must not be destroyed +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1type(JNIEnv *env, jclass, jobject schema_buf, jlong index) { + CHECK_BUF_RET(schema, schema_buf, duckdb_v2_schema_handle, "schema", nullptr); + idx_t idx = jlong_to_idx(env, index); + if (env->ExceptionCheck()) { + return nullptr; + } + const char *name = nullptr; + idx_t name_len = 0; + duckdb_v2_logical_type_handle type = nullptr; + CALL_V2(duckdb_v2_schema_get_field(schema, idx, &name, &name_len, &type, ERR_OUT), nullptr); + return make_ptr_buf(env, type); +} + +/* --- results --- */ + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1destroy(JNIEnv *env, jclass, jobject result_buf) { + CHECK_BUF(result, result_buf, duckdb_v2_result_handle, "result"); + duckdb_v2_result_destroy(&result); +} + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1get_1schema(JNIEnv *env, jclass, jobject result_buf) { + CHECK_BUF_RET(result, result_buf, duckdb_v2_result_handle, "result", nullptr); + duckdb_v2_schema_handle schema = nullptr; + CALL_V2(duckdb_v2_result_get_schema(result, &schema, ERR_OUT), nullptr); + return make_ptr_buf(env, schema); +} + +JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1get_1result_1type(JNIEnv *env, jclass, jobject result_buf) { + CHECK_BUF_RET(result, result_buf, duckdb_v2_result_handle, "result", 0); + DUCKDB_V2_RESULT_TYPE type = DUCKDB_V2_RESULT_TYPE_NOTHING; + CALL_V2(duckdb_v2_result_get_result_type(result, &type, ERR_OUT), 0); + return static_cast(type); +} + +JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1get_1statement_1type(JNIEnv *env, jclass, jobject result_buf) { + CHECK_BUF_RET(result, result_buf, duckdb_v2_result_handle, "result", 0); + DUCKDB_V2_STATEMENT_TYPE type = DUCKDB_V2_STATEMENT_TYPE_INVALID; + CALL_V2(duckdb_v2_result_get_statement_type(result, &type, ERR_OUT), 0); + return static_cast(type); +} + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1wait(JNIEnv *env, jclass, jobject result_buf) { + CHECK_BUF(result, result_buf, duckdb_v2_result_handle, "result"); + CALL_V2(duckdb_v2_result_wait(result, ERR_OUT), ); +} + +JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1drain(JNIEnv *env, jclass, jobject result_buf) { + CHECK_BUF_RET(result, result_buf, duckdb_v2_result_handle, "result", 0); + idx_t rows_changed = 0; + CALL_V2(duckdb_v2_result_drain(result, &rows_changed, ERR_OUT), 0); + return uint64_to_jlong(rows_changed); +} + +// Steps the result once, the status (DUCKDB_V2_RESULT_STEP_STATUS) is written to status_out[0], the returned chunk is +// null unless the status is CHUNK +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1step(JNIEnv *env, jclass, jobject result_buf, jintArray status_out) { + CHECK_BUF_RET(result, result_buf, duckdb_v2_result_handle, "result", nullptr); + duckdb_v2_data_chunk_handle chunk = nullptr; + DUCKDB_V2_RESULT_STEP_STATUS status = DUCKDB_V2_RESULT_STEP_STATUS_WAITING; + CALL_V2(duckdb_v2_result_step(result, &chunk, &status, ERR_OUT), nullptr); + jint status_j = static_cast(status); + env->SetIntArrayRegion(status_out, 0, 1, &status_j); + return make_data_chunk_buf(env, chunk); +} + +// Returns null at the end of the result +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1fetch_1chunk(JNIEnv *env, jclass, jobject result_buf) { + CHECK_BUF_RET(result, result_buf, duckdb_v2_result_handle, "result", nullptr); + duckdb_v2_data_chunk_handle chunk = nullptr; + CALL_V2(duckdb_v2_result_fetch_chunk(result, &chunk, ERR_OUT), nullptr); + return make_data_chunk_buf(env, chunk); +} + +/* --- factory and values --- */ + +// The factory is borrowed from the connection +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1factory(JNIEnv *env, jclass, jobject conn_buf) { + CHECK_BUF_RET(conn, conn_buf, duckdb_v2_connection_handle, "connection", nullptr); + duckdb_v2_factory_handle factory = nullptr; + CALL_V2(duckdb_v2_connection_get_factory(conn, &factory, ERR_OUT), nullptr); + return make_ptr_buf(env, factory); +} + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1factory_1create_1type_1from_1text(JNIEnv *env, jclass, jobject factory_buf, + jbyteArray text_j) { + CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); + auto text = jbyteArray_to_string(env, text_j); + if (env->ExceptionCheck()) { + return nullptr; + } + duckdb_v2_logical_type_handle type = nullptr; + CALL_V2(duckdb_v2_factory_create_type_from_text(factory, text.data(), text.size(), &type, ERR_OUT), nullptr); + return make_logical_type_buf(env, type); +} + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1destroy(JNIEnv *env, jclass, jobject value_buf) { + CHECK_BUF(value, value_buf, duckdb_v2_value_handle, "value"); + duckdb_v2_value_destroy(&value); +} + +#define VALUE_CREATE_SCALAR(FN, JTYPE, CALL) \ + JNIEXPORT jobject JNICALL FN(JNIEnv *env, jclass, jobject factory_buf, JTYPE in_value) { \ + CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); \ + duckdb_v2_value_handle value = nullptr; \ + CALL_V2(CALL, nullptr); \ + return make_ptr_buf(env, value); \ + } + +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1bool, jboolean, duckdb_v2_value_create_bool(factory, in_value == JNI_TRUE, &value, ERR_OUT)) +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1tinyint, jbyte, duckdb_v2_value_create_tinyint(factory, in_value, &value, ERR_OUT)) +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1smallint, jshort, duckdb_v2_value_create_smallint(factory, in_value, &value, ERR_OUT)) +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1int, jint, duckdb_v2_value_create_int(factory, in_value, &value, ERR_OUT)) +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1bigint, jlong, duckdb_v2_value_create_bigint(factory, in_value, &value, ERR_OUT)) +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1float, jfloat, duckdb_v2_value_create_float(factory, in_value, &value, ERR_OUT)) +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1double, jdouble, duckdb_v2_value_create_double(factory, in_value, &value, ERR_OUT)) +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1date, jint, duckdb_v2_value_create_date(factory, in_value, &value, ERR_OUT)) +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1time, jlong, duckdb_v2_value_create_time(factory, in_value, &value, ERR_OUT)) +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp, jlong, duckdb_v2_value_create_timestamp(factory, in_value, &value, ERR_OUT)) +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp_1ns, jlong, duckdb_v2_value_create_timestamp_ns(factory, in_value, &value, ERR_OUT)) +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp_1tz, jlong, duckdb_v2_value_create_timestamp_tz(factory, in_value, &value, ERR_OUT)) + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1null(JNIEnv *env, jclass, jobject factory_buf, jobject type_buf) { + CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); + auto type = logical_type_buf_to_logical_type(env, type_buf); + if (env->ExceptionCheck()) { + return nullptr; + } + duckdb_v2_value_handle value = nullptr; + CALL_V2(duckdb_v2_value_create_null(factory, type, &value, ERR_OUT), nullptr); + return make_ptr_buf(env, value); +} + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1hugeint(JNIEnv *env, jclass, jobject factory_buf, jlong lower, + jlong upper) { + CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); + duckdb_v2_hugeint_t in_value {static_cast(lower), static_cast(upper)}; + duckdb_v2_value_handle value = nullptr; + CALL_V2(duckdb_v2_value_create_hugeint(factory, &in_value, &value, ERR_OUT), nullptr); + return make_ptr_buf(env, value); +} + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1uuid(JNIEnv *env, jclass, jobject factory_buf, jlong lower, + jlong upper) { + CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); + duckdb_v2_hugeint_t in_value {static_cast(lower), static_cast(upper)}; + duckdb_v2_value_handle value = nullptr; + CALL_V2(duckdb_v2_value_create_uuid(factory, &in_value, &value, ERR_OUT), nullptr); + return make_ptr_buf(env, value); +} + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1decimal(JNIEnv *env, jclass, jobject factory_buf, jlong lower, + jlong upper, jint width, jint scale) { + CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); + duckdb_v2_hugeint_t in_value {static_cast(lower), static_cast(upper)}; + duckdb_v2_value_handle value = nullptr; + CALL_V2(duckdb_v2_value_create_decimal(factory, &in_value, static_cast(width), + static_cast(scale), &value, ERR_OUT), + nullptr); + return make_ptr_buf(env, value); +} + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1varchar(JNIEnv *env, jclass, jobject factory_buf, + jbyteArray in_value_j) { + CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); + auto in_value = jbyteArray_to_string(env, in_value_j); + if (env->ExceptionCheck()) { + return nullptr; + } + duckdb_v2_value_handle value = nullptr; + CALL_V2(duckdb_v2_value_create_varchar(factory, in_value.data(), in_value.size(), &value, ERR_OUT), nullptr); + return make_ptr_buf(env, value); +} + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1blob(JNIEnv *env, jclass, jobject factory_buf, + jbyteArray in_value_j) { + CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); + auto in_value = jbyteArray_to_string(env, in_value_j); + if (env->ExceptionCheck()) { + return nullptr; + } + duckdb_v2_value_handle value = nullptr; + CALL_V2(duckdb_v2_value_create_blob(factory, in_value.data(), in_value.size(), &value, ERR_OUT), nullptr); + return make_ptr_buf(env, value); +} + +// The child values are borrowed for the call +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1list(JNIEnv *env, jclass, jobject factory_buf, jobject type_buf, + jobjectArray children_j) { + CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); + auto type = logical_type_buf_to_logical_type(env, type_buf); + if (env->ExceptionCheck()) { + return nullptr; + } + std::vector children; + if (!read_values(env, children_j, children)) { + return nullptr; + } + duckdb_v2_value_handle value = nullptr; + CALL_V2(duckdb_v2_value_create_list(factory, type, children.data(), children.size(), &value, ERR_OUT), nullptr); + return make_ptr_buf(env, value); +} + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1struct(JNIEnv *env, jclass, jobject factory_buf, + jobjectArray names_j, jobjectArray children_j) { + CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); + std::vector children; + if (!read_values(env, children_j, children)) { + return nullptr; + } + std::vector names; + jsize count = names_j == nullptr ? 0 : env->GetArrayLength(names_j); + for (jsize i = 0; i < count; i++) { + auto name_j = reinterpret_cast(env->GetObjectArrayElement(names_j, i)); + names.push_back(jbyteArray_to_string(env, name_j)); + env->DeleteLocalRef(name_j); + if (env->ExceptionCheck()) { + return nullptr; + } + } + if (names.size() != children.size()) { + env->ThrowNew(J_SQLException, "Struct names and values count mismatch"); + return nullptr; + } + std::vector name_ptrs; + std::vector name_lens; + for (auto &name : names) { + name_ptrs.push_back(name.data()); + name_lens.push_back(name.size()); + } + duckdb_v2_value_handle value = nullptr; + CALL_V2(duckdb_v2_value_create_struct(factory, name_ptrs.data(), name_lens.data(), children.data(), + children.size(), &value, ERR_OUT), + nullptr); + return make_ptr_buf(env, value); +} + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1map(JNIEnv *env, jclass, jobject factory_buf, jobject key_type_buf, + jobject value_type_buf, jobjectArray keys_j, + jobjectArray values_j) { + CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); + auto key_type = logical_type_buf_to_logical_type(env, key_type_buf); + if (env->ExceptionCheck()) { + return nullptr; + } + auto value_type = logical_type_buf_to_logical_type(env, value_type_buf); + if (env->ExceptionCheck()) { + return nullptr; + } + std::vector keys; + std::vector values; + if (!read_values(env, keys_j, keys) || !read_values(env, values_j, values)) { + return nullptr; + } + if (keys.size() != values.size()) { + env->ThrowNew(J_SQLException, "Map keys and values count mismatch"); + return nullptr; + } + duckdb_v2_value_handle value = nullptr; + CALL_V2(duckdb_v2_value_create_map(factory, key_type, value_type, keys.data(), values.data(), keys.size(), &value, + ERR_OUT), + nullptr); + return make_ptr_buf(env, value); +} diff --git a/src/main/java/org/duckdb/DuckDBBindings.java b/src/main/java/org/duckdb/DuckDBBindings.java index 7d4995e83..0066364e0 100644 --- a/src/main/java/org/duckdb/DuckDBBindings.java +++ b/src/main/java/org/duckdb/DuckDBBindings.java @@ -297,6 +297,140 @@ static native int duckdb_appender_create_ext(ByteBuffer connection, byte[] catal static native byte[] duckdb_result_error(ByteBuffer result); + // C API v2 + + // transitional: the C API v2 connection of a connection reference + static native ByteBuffer duckdb_v2_connection_from_ref(ByteBuffer conn_ref) throws SQLException; + + static native void duckdb_v2_connection_interrupt(ByteBuffer conn) throws SQLException; + + static native QueryProgress duckdb_v2_connection_progress_get(ByteBuffer conn) throws SQLException; + + static native ByteBuffer duckdb_v2_parse_sql(ByteBuffer conn, byte[] sql) throws SQLException; + + // returns null when there are no more statements + static native ByteBuffer duckdb_v2_statement_iterator_next(ByteBuffer iterator) throws SQLException; + + static native void duckdb_v2_statement_iterator_destroy(ByteBuffer iterator) throws SQLException; + + static native void duckdb_v2_sql_statement_destroy(ByteBuffer statement) throws SQLException; + + static native int duckdb_v2_sql_statement_get_type(ByteBuffer statement) throws SQLException; + + static native long duckdb_v2_sql_statement_get_parameter_count(ByteBuffer statement) throws SQLException; + + static native ByteBuffer duckdb_v2_prepared_statement_create(ByteBuffer conn, ByteBuffer statement, + boolean require_cacheable) throws SQLException; + + static native void duckdb_v2_prepared_statement_destroy(ByteBuffer prepared) throws SQLException; + + // the values are borrowed for the call + static native ByteBuffer duckdb_v2_prepared_statement_execute(ByteBuffer prepared, ByteBuffer[] values) + throws SQLException; + + static native ByteBuffer duckdb_v2_statement_execute(ByteBuffer conn, ByteBuffer statement, ByteBuffer[] values) + throws SQLException; + + // returns the output schema and the parameters schema + static native ByteBuffer[] duckdb_v2_statement_bind(ByteBuffer conn, ByteBuffer statement) throws SQLException; + + static native void duckdb_v2_schema_destroy(ByteBuffer schema) throws SQLException; + + static native long duckdb_v2_schema_get_count(ByteBuffer schema) throws SQLException; + + static native byte[] duckdb_v2_schema_get_field_name(ByteBuffer schema, long index) throws SQLException; + + // the returned type is borrowed from the schema and must not be destroyed + static native ByteBuffer duckdb_v2_schema_get_field_type(ByteBuffer schema, long index) throws SQLException; + + static native void duckdb_v2_result_destroy(ByteBuffer result) throws SQLException; + + static native ByteBuffer duckdb_v2_result_get_schema(ByteBuffer result) throws SQLException; + + static native int duckdb_v2_result_get_result_type(ByteBuffer result) throws SQLException; + + static native int duckdb_v2_result_get_statement_type(ByteBuffer result) throws SQLException; + + static native void duckdb_v2_result_wait(ByteBuffer result) throws SQLException; + + static native long duckdb_v2_result_drain(ByteBuffer result) throws SQLException; + + // the step status is written to status_out[0], the chunk is null unless the status is RESULT_STEP_CHUNK + static native ByteBuffer duckdb_v2_result_step(ByteBuffer result, int[] status_out) throws SQLException; + + // returns null at the end of the result + static native ByteBuffer duckdb_v2_result_fetch_chunk(ByteBuffer result) throws SQLException; + + // factory and values + + // the returned factory is borrowed from the connection + static native ByteBuffer duckdb_v2_connection_get_factory(ByteBuffer conn) throws SQLException; + + static native ByteBuffer duckdb_v2_factory_create_type_from_text(ByteBuffer factory, byte[] text) + throws SQLException; + + static native void duckdb_v2_value_destroy(ByteBuffer value) throws SQLException; + + static native ByteBuffer duckdb_v2_value_create_null(ByteBuffer factory, ByteBuffer type) throws SQLException; + + static native ByteBuffer duckdb_v2_value_create_bool(ByteBuffer factory, boolean value) throws SQLException; + + static native ByteBuffer duckdb_v2_value_create_tinyint(ByteBuffer factory, byte value) throws SQLException; + + static native ByteBuffer duckdb_v2_value_create_smallint(ByteBuffer factory, short value) throws SQLException; + + static native ByteBuffer duckdb_v2_value_create_int(ByteBuffer factory, int value) throws SQLException; + + static native ByteBuffer duckdb_v2_value_create_bigint(ByteBuffer factory, long value) throws SQLException; + + static native ByteBuffer duckdb_v2_value_create_float(ByteBuffer factory, float value) throws SQLException; + + static native ByteBuffer duckdb_v2_value_create_double(ByteBuffer factory, double value) throws SQLException; + + static native ByteBuffer duckdb_v2_value_create_date(ByteBuffer factory, int days) throws SQLException; + + static native ByteBuffer duckdb_v2_value_create_time(ByteBuffer factory, long micros) throws SQLException; + + static native ByteBuffer duckdb_v2_value_create_timestamp(ByteBuffer factory, long micros) throws SQLException; + + static native ByteBuffer duckdb_v2_value_create_timestamp_ns(ByteBuffer factory, long nanos) throws SQLException; + + static native ByteBuffer duckdb_v2_value_create_timestamp_tz(ByteBuffer factory, long micros) throws SQLException; + + static native ByteBuffer duckdb_v2_value_create_hugeint(ByteBuffer factory, long lower, long upper) + throws SQLException; + + static native ByteBuffer duckdb_v2_value_create_uuid(ByteBuffer factory, long lower, long upper) + throws SQLException; + + static native ByteBuffer duckdb_v2_value_create_decimal(ByteBuffer factory, long lower, long upper, int width, + int scale) throws SQLException; + + static native ByteBuffer duckdb_v2_value_create_varchar(ByteBuffer factory, byte[] value) throws SQLException; + + static native ByteBuffer duckdb_v2_value_create_blob(ByteBuffer factory, byte[] value) throws SQLException; + + // the child values are borrowed for the call + static native ByteBuffer duckdb_v2_value_create_list(ByteBuffer factory, ByteBuffer childType, + ByteBuffer[] children) throws SQLException; + + static native ByteBuffer duckdb_v2_value_create_struct(ByteBuffer factory, byte[][] names, ByteBuffer[] children) + throws SQLException; + + static native ByteBuffer duckdb_v2_value_create_map(ByteBuffer factory, ByteBuffer keyType, ByteBuffer valueType, + ByteBuffer[] keys, ByteBuffer[] values) throws SQLException; + + // DUCKDB_V2_RESULT_STEP_STATUS + static final int RESULT_STEP_WAITING = 0; + static final int RESULT_STEP_CHUNK = 1; + static final int RESULT_STEP_FINISHED = 2; + static final int RESULT_STEP_CANCELLED = 3; + + // DUCKDB_V2_RESULT_TYPE + static final int RESULT_TYPE_QUERY_RESULT = 0; + static final int RESULT_TYPE_CHANGED_ROWS = 1; + static final int RESULT_TYPE_NOTHING = 2; + enum CAPIType { DUCKDB_TYPE_INVALID(0, 0), // bool From e5de9498460b60283a3efa80d05dd904c802395b Mon Sep 17 00:00:00 2001 From: Robinho-MR Date: Fri, 27 Nov 2026 13:47:06 +0000 Subject: [PATCH 02/21] Apply duckdb/duckdb#29425 to the vendored sources until the next vendoring --- .../duckdb/main/capi_v2/extension_api_v2.hpp | 3 +++ src/duckdb/src/include/duckdb_extension_v2.h | 5 ++++ src/duckdb/src/include/duckdb_v2.h | 25 +++++++++++++++++++ src/duckdb/src/main/capi/v2/capi_v2_value.cpp | 24 ++++++++++++++++++ 4 files changed, 57 insertions(+) diff --git a/src/duckdb/src/include/duckdb/main/capi_v2/extension_api_v2.hpp b/src/duckdb/src/include/duckdb/main/capi_v2/extension_api_v2.hpp index 405f0bd0b..80741a7d5 100644 --- a/src/duckdb/src/include/duckdb/main/capi_v2/extension_api_v2.hpp +++ b/src/duckdb/src/include/duckdb/main/capi_v2/extension_api_v2.hpp @@ -1713,6 +1713,8 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_connection_get_profiling_information) (duckdb_v2_connection_handle conn, const char *format, idx_t format_length, duckdb_v2_text_sink_fn sink, void *user_data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_value_variant_to_value) + (duckdb_v2_value_handle value, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); } duckdb_ext_api_v2; //===--------------------------------------------------------------------===// @@ -2482,6 +2484,7 @@ inline duckdb_ext_api_v2 CreateAPIv2(void) { result.duckdb_v2_table_function_to_string_set = duckdb_v2_table_function_to_string_set; result.duckdb_v2_instance_open_shared = duckdb_v2_instance_open_shared; result.duckdb_v2_connection_get_profiling_information = duckdb_v2_connection_get_profiling_information; + result.duckdb_v2_value_variant_to_value = duckdb_v2_value_variant_to_value; return result; } diff --git a/src/duckdb/src/include/duckdb_extension_v2.h b/src/duckdb/src/include/duckdb_extension_v2.h index 39ee5458d..012074a33 100644 --- a/src/duckdb/src/include/duckdb_extension_v2.h +++ b/src/duckdb/src/include/duckdb_extension_v2.h @@ -1787,6 +1787,8 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_connection_get_profiling_information) (duckdb_v2_connection_handle conn, const char *format, idx_t format_length, duckdb_v2_text_sink_fn sink, void *user_data, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_value_variant_to_value) + (duckdb_v2_value_handle value, duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); #endif // capigen:end appended } duckdb_ext_api_v2; @@ -4066,6 +4068,9 @@ typedef struct { #if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_connection_get_profiling_information duckdb_ext_api.duckdb_v2_connection_get_profiling_information #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_value_variant_to_value duckdb_ext_api.duckdb_v2_value_variant_to_value +#endif // capigen:end appended #endif // DUCKDB_BUILD_STATIC_EXTENSION diff --git a/src/duckdb/src/include/duckdb_v2.h b/src/duckdb/src/include/duckdb_v2.h index 0ff4262d7..7f0330ad6 100644 --- a/src/duckdb/src/include/duckdb_v2.h +++ b/src/duckdb/src/include/duckdb_v2.h @@ -18990,6 +18990,31 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_child(duckdb_v2_value_handle va duckdb_v2_error_info_handle *err); #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Returns the value that a VARIANT value holds, as a value of its own type. + * + * A VARIANT holds a value of any other type, e.g. a TINYINT, a VARCHAR or a LIST of STRUCTs, that is only known per + * value: this reads it back, with the type that it was stored with. The value is built with the content of the variant, + * so a stored list gives a LIST with its elements, and a stored object a STRUCT with its fields. The elements of a list + * that were stored with different types, which a LIST cannot hold, stay VARIANT values: a LIST of VARIANT. Convert + * those with this function in turn. A NULL VARIANT gives a NULL value. A value that is not a VARIANT returns + * ERROR_INPUT_INVALID. The inverse is value_cast to a VARIANT type, which factory_create_type_from_text gives. The + * returned value is caller-owned; destroy it via value_destroy. + * + * history: + * - unstable: v2.0.0 + * + * @param value The VARIANT value to convert. + * @param out_value Receives the owned value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_variant_to_value(duckdb_v2_value_handle value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); +#endif + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! * Casts a value to a target type, using a factory. diff --git a/src/duckdb/src/main/capi/v2/capi_v2_value.cpp b/src/duckdb/src/main/capi/v2/capi_v2_value.cpp index 649703a1f..90270952e 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_value.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_value.cpp @@ -7,6 +7,7 @@ #include "duckdb/common/types/interval.hpp" #include "duckdb/common/types/uuid.hpp" #include "duckdb/common/types/value.hpp" +#include "duckdb/function/scalar/variant_utils.hpp" #include @@ -919,6 +920,29 @@ DUCKDB_V2_ERROR duckdb_v2_value_get_child_count(duckdb_v2_value_handle value, id return WithErrorHandler(err, [&]() { *out_count = CompositeChildCount(*Convert(value)); }); } +DUCKDB_V2_ERROR duckdb_v2_value_variant_to_value(duckdb_v2_value_handle value, duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(value); + DUCKDB_CHECK_ARG(out_value); + *out_value = nullptr; + return WithErrorHandler(err, [&]() { + auto &v = *Convert(value); + if (v.type().id() != duckdb::LogicalTypeId::VARIANT) { + throw duckdb::InvalidInputException("duckdb_v2_value_variant_to_value expects a VARIANT value"); + } + if (v.IsNull()) { + *out_value = Emit(duckdb::Value()); + return; + } + duckdb::Vector vec(v.type()); + vec.SetValue(0, v); + duckdb::RecursiveUnifiedVectorFormat format; + duckdb::Vector::RecursiveToUnifiedFormat(vec, format); + duckdb::UnifiedVariantVectorData data(format); + *out_value = Emit(duckdb::VariantUtils::ConvertVariantToValue(data, 0, 0)); + }); +} + DUCKDB_V2_ERROR duckdb_v2_value_get_child(duckdb_v2_value_handle value, idx_t index, duckdb_v2_value_handle *out_child, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(value); From 7df95501bac2fbd6a76a4171e1b0fd56140cdfb4 Mon Sep 17 00:00:00 2001 From: Robinho-MR Date: Fri, 27 Nov 2026 13:53:59 +0000 Subject: [PATCH 03/21] Add C API v2 entry points for types, values and vectors --- src/jni/bindings_v2.cpp | 174 +++++++++++++++++++ src/main/java/org/duckdb/DuckDBBindings.java | 48 +++++ src/main/java/org/duckdb/DuckDBVector.java | 6 +- 3 files changed, 225 insertions(+), 3 deletions(-) diff --git a/src/jni/bindings_v2.cpp b/src/jni/bindings_v2.cpp index 38195d13e..bd65b4fb7 100644 --- a/src/jni/bindings_v2.cpp +++ b/src/jni/bindings_v2.cpp @@ -503,3 +503,177 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1crea nullptr); return make_ptr_buf(env, value); } + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1type(JNIEnv *env, jclass, jobject factory_buf, jobject type_buf) { + CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); + auto type = logical_type_buf_to_logical_type(env, type_buf); + if (env->ExceptionCheck()) { + return nullptr; + } + duckdb_v2_value_handle value = nullptr; + CALL_V2(duckdb_v2_value_create_type(factory, type, &value, ERR_OUT), nullptr); + return make_ptr_buf(env, value); +} + +JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1to_1string(JNIEnv *env, jclass, jobject value_buf) { + CHECK_BUF_RET(value, value_buf, duckdb_v2_value_handle, "value", nullptr); + idx_t length = 0; + CALL_V2(duckdb_v2_value_to_string(value, nullptr, 0, &length, ERR_OUT), nullptr); + std::vector text(length + 1); + CALL_V2(duckdb_v2_value_to_string(value, text.data(), text.size(), &length, ERR_OUT), nullptr); + return make_jbyteArray(env, text.data(), length); +} + +/* --- vectors --- */ + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1flatten(JNIEnv *env, jclass, jobject vector_buf) { + CHECK_BUF(vector, vector_buf, duckdb_v2_vector_handle, "vector"); + CALL_V2(duckdb_v2_vector_flatten(vector, ERR_OUT), ); +} + +// The returned value is owned by the caller +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1value(JNIEnv *env, jclass, jobject vector_buf, jlong row) { + CHECK_BUF_RET(vector, vector_buf, duckdb_v2_vector_handle, "vector", nullptr); + idx_t idx = jlong_to_idx(env, row); + if (env->ExceptionCheck()) { + return nullptr; + } + duckdb_v2_value_handle value = nullptr; + CALL_V2(duckdb_v2_vector_get_value(vector, idx, &value, ERR_OUT), nullptr); + return make_ptr_buf(env, value); +} + +/* --- logical type parameters --- */ + +JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1get_1param_1count(JNIEnv *env, jclass, jobject type_buf) { + auto type = logical_type_buf_to_logical_type(env, type_buf); + if (env->ExceptionCheck()) { + return 0; + } + idx_t count = 0; + CALL_V2(duckdb_v2_logical_type_get_param_count(type, &count, ERR_OUT), 0); + return uint64_to_jlong(count); +} + +// The returned value is owned by the caller +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1get_1param_1value(JNIEnv *env, jclass, jobject type_buf, jlong index) { + auto type = logical_type_buf_to_logical_type(env, type_buf); + if (env->ExceptionCheck()) { + return nullptr; + } + idx_t idx = jlong_to_idx(env, index); + if (env->ExceptionCheck()) { + return nullptr; + } + const char *name = nullptr; + idx_t name_len = 0; + duckdb_v2_value_handle value = nullptr; + CALL_V2(duckdb_v2_logical_type_get_param(type, idx, &name, &name_len, &value, ERR_OUT), nullptr); + return make_ptr_buf(env, value); +} + +// Returns null for a positional parameter +JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1get_1param_1name(JNIEnv *env, jclass, jobject type_buf, + jlong index) { + auto type = logical_type_buf_to_logical_type(env, type_buf); + if (env->ExceptionCheck()) { + return nullptr; + } + idx_t idx = jlong_to_idx(env, index); + if (env->ExceptionCheck()) { + return nullptr; + } + const char *name = nullptr; + idx_t name_len = 0; + duckdb_v2_value_handle value = nullptr; + CALL_V2(duckdb_v2_logical_type_get_param(type, idx, &name, &name_len, &value, ERR_OUT), nullptr); + duckdb_v2_value_destroy(&value); + if (name == nullptr || name_len == 0) { + return nullptr; + } + return make_jbyteArray(env, name, name_len); +} + +// Unwraps the type of a TYPE value, the returned type is owned by the caller +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1get_1type(JNIEnv *env, jclass, jobject value_buf) { + CHECK_BUF_RET(value, value_buf, duckdb_v2_value_handle, "value", nullptr); + duckdb_v2_logical_type_handle type = nullptr; + CALL_V2(duckdb_v2_value_get_type(value, &type, ERR_OUT), nullptr); + return make_logical_type_buf(env, type); +} + +/* --- configuration --- */ + +// The returned config is borrowed from the connection +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1config(JNIEnv *env, jclass, jobject conn_buf) { + CHECK_BUF_RET(conn, conn_buf, duckdb_v2_connection_handle, "connection", nullptr); + duckdb_v2_config_handle config = nullptr; + CALL_V2(duckdb_v2_connection_get_config(conn, &config, ERR_OUT), nullptr); + return make_ptr_buf(env, config); +} + +// The returned value is owned by the caller +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1value(JNIEnv *env, jclass, jobject config_buf, + jbyteArray name_j) { + CHECK_BUF_RET(config, config_buf, duckdb_v2_config_handle, "config", nullptr); + auto name = jbyteArray_to_string(env, name_j); + if (env->ExceptionCheck()) { + return nullptr; + } + duckdb_v2_value_handle value = nullptr; + DUCKDB_V2_SETTING_SCOPE scope = DUCKDB_V2_SETTING_SCOPE_DEFAULT; + CALL_V2(duckdb_v2_config_get_option_value(config, name.data(), name.size(), &value, &scope, ERR_OUT), nullptr); + return make_ptr_buf(env, value); +} + +/* --- transitional --- */ + +// Wraps the result into a chunked result of the bindings API, the holder takes the ownership of the result +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1chunked_1result_1create(JNIEnv *env, jclass, jobject result_buf) { + CHECK_BUF_RET(result, result_buf, duckdb_v2_result_handle, "result", nullptr); + try { + return env->NewDirectByteBuffer(new ChunkedResultHolder(result), 0); + } catch (const std::exception &e) { + duckdb_v2_result_destroy(&result); + env->ThrowNew(J_SQLException, e.what()); + return nullptr; + } +} + +/* --- variants --- */ + +// The returned value is owned by the caller +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1variant_1to_1value(JNIEnv *env, jclass, jobject value_buf) { + CHECK_BUF_RET(value, value_buf, duckdb_v2_value_handle, "value", nullptr); + duckdb_v2_value_handle out_value = nullptr; + CALL_V2(duckdb_v2_value_variant_to_value(value, &out_value, ERR_OUT), nullptr); + return make_ptr_buf(env, out_value); +} + +// The returned type is owned by the caller +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1get_1logical_1type(JNIEnv *env, jclass, jobject value_buf) { + CHECK_BUF_RET(value, value_buf, duckdb_v2_value_handle, "value", nullptr); + duckdb_v2_logical_type_handle type = nullptr; + CALL_V2(duckdb_v2_value_get_logical_type(value, &type, ERR_OUT), nullptr); + return make_logical_type_buf(env, type); +} + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1set_1value(JNIEnv *env, jclass, jobject vector_buf, jlong row, + jobject value_buf) { + CHECK_BUF(vector, vector_buf, duckdb_v2_vector_handle, "vector"); + CHECK_BUF(value, value_buf, duckdb_v2_value_handle, "value"); + idx_t idx = jlong_to_idx(env, row); + if (env->ExceptionCheck()) { + return; + } + CALL_V2(duckdb_v2_vector_set_value(vector, idx, value, ERR_OUT), ); +} + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1set_1size(JNIEnv *env, jclass, jobject vector_buf, jlong size) { + CHECK_BUF(vector, vector_buf, duckdb_v2_vector_handle, "vector"); + idx_t sz = jlong_to_idx(env, size); + if (env->ExceptionCheck()) { + return; + } + CALL_V2(duckdb_v2_vector_set_size(vector, sz, ERR_OUT), ); +} diff --git a/src/main/java/org/duckdb/DuckDBBindings.java b/src/main/java/org/duckdb/DuckDBBindings.java index 0066364e0..10d28475c 100644 --- a/src/main/java/org/duckdb/DuckDBBindings.java +++ b/src/main/java/org/duckdb/DuckDBBindings.java @@ -420,6 +420,54 @@ static native ByteBuffer duckdb_v2_value_create_struct(ByteBuffer factory, byte[ static native ByteBuffer duckdb_v2_value_create_map(ByteBuffer factory, ByteBuffer keyType, ByteBuffer valueType, ByteBuffer[] keys, ByteBuffer[] values) throws SQLException; + static native ByteBuffer duckdb_v2_value_create_type(ByteBuffer factory, ByteBuffer type) throws SQLException; + + static native byte[] duckdb_v2_value_to_string(ByteBuffer value) throws SQLException; + + // vectors + + // forces the vector (not its children) into the flat representation, in place + static native void duckdb_v2_vector_flatten(ByteBuffer vector) throws SQLException; + + // the returned value is owned by the caller + static native ByteBuffer duckdb_v2_vector_get_value(ByteBuffer vector, long row) throws SQLException; + + // logical type parameters: the child types of nested types come back as TYPE values + + static native long duckdb_v2_logical_type_get_param_count(ByteBuffer type) throws SQLException; + + // the returned value is owned by the caller + static native ByteBuffer duckdb_v2_logical_type_get_param_value(ByteBuffer type, long index) throws SQLException; + + // returns null for a positional parameter + static native byte[] duckdb_v2_logical_type_get_param_name(ByteBuffer type, long index) throws SQLException; + + // unwraps the type of a TYPE value, the returned type is owned by the caller + static native ByteBuffer duckdb_v2_value_get_type(ByteBuffer value) throws SQLException; + + // configuration + + // the returned config is borrowed from the connection + static native ByteBuffer duckdb_v2_connection_get_config(ByteBuffer conn) throws SQLException; + + // the returned value is owned by the caller + static native ByteBuffer duckdb_v2_config_get_option_value(ByteBuffer config, byte[] name) throws SQLException; + + // transitional: wraps the result into a chunked result of the bindings API that takes the ownership of the result + static native ByteBuffer duckdb_v2_chunked_result_create(ByteBuffer result) throws SQLException; + + // variants + + // the returned value is owned by the caller + static native ByteBuffer duckdb_v2_value_variant_to_value(ByteBuffer value) throws SQLException; + + // the returned type is owned by the caller + static native ByteBuffer duckdb_v2_value_get_logical_type(ByteBuffer value) throws SQLException; + + static native void duckdb_v2_vector_set_value(ByteBuffer vector, long row, ByteBuffer value) throws SQLException; + + static native void duckdb_v2_vector_set_size(ByteBuffer vector, long size) throws SQLException; + // DUCKDB_V2_RESULT_STEP_STATUS static final int RESULT_STEP_WAITING = 0; static final int RESULT_STEP_CHUNK = 1; diff --git a/src/main/java/org/duckdb/DuckDBVector.java b/src/main/java/org/duckdb/DuckDBVector.java index d8fc851ae..d1f38ab68 100644 --- a/src/main/java/org/duckdb/DuckDBVector.java +++ b/src/main/java/org/duckdb/DuckDBVector.java @@ -45,8 +45,8 @@ class DuckDBVector { protected final DuckDBColumnType duckdb_type; final int length; private final boolean[] nullmask; - private ByteBuffer constlen_data = null; - private Object[] varlen_data = null; + ByteBuffer constlen_data = null; + Object[] varlen_data = null; String[] string_data = null; DuckDBVector(String duckdb_type, int length, boolean[] nullmask) { @@ -59,7 +59,7 @@ class DuckDBVector { this.nullmask = nullmask; } - private void retainConstlenData() { + void retainConstlenData() { if (null != constlen_data) { byte[] constlenBytes = new byte[constlen_data.capacity()]; constlen_data.get(constlenBytes); From e5b98d96ba5332b290041238958c7e24d0e4532f Mon Sep 17 00:00:00 2001 From: Robinho-MR Date: Fri, 27 Nov 2026 14:17:14 +0000 Subject: [PATCH 04/21] Implement statements and results in Java on top of the C API v2 --- duckdb_java.def | 80 +- duckdb_java.exp | 80 +- duckdb_java.map | 80 +- src/jni/bindings_v2.cpp | 244 ++-- src/jni/duckdb_java.cpp | 809 ------------ src/jni/functions.cpp | 160 --- src/jni/functions.hpp | 60 - .../java/org/duckdb/DuckDBConnection.java | 3 + src/main/java/org/duckdb/DuckDBCore.java | 1121 +++++++++++++++++ src/main/java/org/duckdb/DuckDBNative.java | 77 +- .../java/org/duckdb/DuckDBPendingQuery.java | 5 +- .../org/duckdb/DuckDBPreparedStatement.java | 14 +- src/main/java/org/duckdb/DuckDBResultSet.java | 4 +- 13 files changed, 1549 insertions(+), 1188 deletions(-) create mode 100644 src/main/java/org/duckdb/DuckDBCore.java diff --git a/duckdb_java.def b/duckdb_java.def index 9ad70e84e..d252d9cc1 100644 --- a/duckdb_java.def +++ b/duckdb_java.def @@ -22,32 +22,17 @@ Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1end_1row Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1flush Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1close_1streams Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1register -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1stream Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1connect Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1create_1appender Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1create_1db_1ref Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1destroy_1db_1ref Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1db_1address Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1disconnect -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1execute -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1execute_1capi -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1execute_1pending -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1fetch -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1cast_1result_1to_1strings Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1fetch_1size -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1free_1result Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1auto_1commit Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1catalog Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1profiling_1information Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1schema -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1interrupt -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1pending_1query -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1prepare -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1prepared_1statement_1meta -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1query_1result_1meta -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1query_1progress -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1release -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1release_1pending Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1auto_1commit Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1catalog Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1schema @@ -185,6 +170,71 @@ Java_org_duckdb_DuckDBBindings_duckdb_1column_1name Java_org_duckdb_DuckDBBindings_duckdb_1column_1type Java_org_duckdb_DuckDBBindings_duckdb_1column_1count Java_org_duckdb_DuckDBBindings_duckdb_1result_1error +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1chunked_1result_1create +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1value +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1from_1ref +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1config +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1factory +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1interrupt +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1progress_1get +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1factory_1create_1type_1from_1text +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1get_1param_1count +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1get_1param_1name +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1get_1param_1value +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1parse_1sql +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1prepared_1statement_1create +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1prepared_1statement_1destroy +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1prepared_1statement_1execute +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1destroy +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1drain +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1fetch_1chunk +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1get_1result_1type +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1get_1schema +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1get_1statement_1type +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1step +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1wait +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1destroy +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1count +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1name +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1type +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement_1destroy +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement_1get_1parameter_1count +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement_1get_1type +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1bind +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1execute +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1iterator_1destroy +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1iterator_1next +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1blob +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1decimal +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1hugeint +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1list +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1map +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1null +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1struct +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1type +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1uuid +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1varchar +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1destroy +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1get_1logical_1type +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1get_1type +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1to_1string +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1variant_1to_1value +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1flatten +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1value +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1set_1size +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1set_1value +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1bigint +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1bool +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1date +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1double +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1float +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1int +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1smallint +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1time +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp_1ns +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp_1tz +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1tinyint ; ADBC entry point duckdb_adbc_init diff --git a/duckdb_java.exp b/duckdb_java.exp index aceb8881f..cc9213587 100644 --- a/duckdb_java.exp +++ b/duckdb_java.exp @@ -19,32 +19,17 @@ _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1end_1row _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1flush _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1close_1streams _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1register -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1stream _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1connect _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1create_1appender _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1create_1db_1ref _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1destroy_1db_1ref _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1db_1address _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1disconnect -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1execute -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1execute_1capi -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1execute_1pending -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1fetch -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1cast_1result_1to_1strings _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1fetch_1size -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1free_1result _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1auto_1commit _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1catalog _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1profiling_1information _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1schema -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1interrupt -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1pending_1query -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1prepare -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1prepared_1statement_1meta -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1query_1result_1meta -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1query_1progress -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1release -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1release_1pending _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1auto_1commit _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1catalog _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1schema @@ -182,6 +167,71 @@ _Java_org_duckdb_DuckDBBindings_duckdb_1column_1name _Java_org_duckdb_DuckDBBindings_duckdb_1column_1type _Java_org_duckdb_DuckDBBindings_duckdb_1column_1count _Java_org_duckdb_DuckDBBindings_duckdb_1result_1error +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1chunked_1result_1create +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1value +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1from_1ref +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1config +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1factory +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1interrupt +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1progress_1get +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1factory_1create_1type_1from_1text +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1get_1param_1count +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1get_1param_1name +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1get_1param_1value +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1parse_1sql +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1prepared_1statement_1create +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1prepared_1statement_1destroy +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1prepared_1statement_1execute +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1destroy +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1drain +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1fetch_1chunk +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1get_1result_1type +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1get_1schema +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1get_1statement_1type +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1step +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1wait +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1destroy +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1count +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1name +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1type +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement_1destroy +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement_1get_1parameter_1count +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement_1get_1type +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1bind +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1execute +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1iterator_1destroy +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1iterator_1next +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1blob +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1decimal +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1hugeint +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1list +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1map +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1null +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1struct +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1type +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1uuid +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1varchar +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1destroy +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1get_1logical_1type +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1get_1type +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1to_1string +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1variant_1to_1value +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1flatten +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1value +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1set_1size +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1set_1value +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1bigint +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1bool +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1date +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1double +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1float +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1int +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1smallint +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1time +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp_1ns +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp_1tz +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1tinyint # ADBC entry point _duckdb_adbc_init diff --git a/duckdb_java.map b/duckdb_java.map index 972f0db48..e4f25c288 100644 --- a/duckdb_java.map +++ b/duckdb_java.map @@ -21,32 +21,17 @@ DUCKDB_JAVA { Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1flush; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1close_1streams; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1register; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1stream; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1connect; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1create_1appender; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1create_1db_1ref; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1destroy_1db_1ref; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1db_1address; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1disconnect; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1execute; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1execute_1capi; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1execute_1pending; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1fetch; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1cast_1result_1to_1strings; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1fetch_1size; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1free_1result; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1auto_1commit; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1catalog; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1profiling_1information; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1schema; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1interrupt; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1pending_1query; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1prepare; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1prepared_1statement_1meta; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1query_1result_1meta; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1query_1progress; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1release; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1release_1pending; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1auto_1commit; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1catalog; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1schema; @@ -184,6 +169,71 @@ DUCKDB_JAVA { Java_org_duckdb_DuckDBBindings_duckdb_1column_1type; Java_org_duckdb_DuckDBBindings_duckdb_1column_1count; Java_org_duckdb_DuckDBBindings_duckdb_1result_1error; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1chunked_1result_1create; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1value; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1from_1ref; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1config; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1factory; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1interrupt; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1progress_1get; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1factory_1create_1type_1from_1text; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1get_1param_1count; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1get_1param_1name; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1get_1param_1value; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1parse_1sql; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1prepared_1statement_1create; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1prepared_1statement_1destroy; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1prepared_1statement_1execute; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1destroy; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1drain; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1fetch_1chunk; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1get_1result_1type; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1get_1schema; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1get_1statement_1type; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1step; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1wait; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1destroy; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1count; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1name; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1type; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement_1destroy; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement_1get_1parameter_1count; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement_1get_1type; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1bind; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1execute; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1iterator_1destroy; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1iterator_1next; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1blob; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1decimal; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1hugeint; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1list; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1map; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1null; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1struct; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1type; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1uuid; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1varchar; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1destroy; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1get_1logical_1type; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1get_1type; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1to_1string; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1variant_1to_1value; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1flatten; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1value; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1set_1size; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1set_1value; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1bigint; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1bool; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1date; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1double; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1float; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1int; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1smallint; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1time; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp_1ns; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp_1tz; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1tinyint; /* ADBC entry point */ duckdb_adbc_init; diff --git a/src/jni/bindings_v2.cpp b/src/jni/bindings_v2.cpp index bd65b4fb7..604c53cfd 100644 --- a/src/jni/bindings_v2.cpp +++ b/src/jni/bindings_v2.cpp @@ -57,7 +57,8 @@ static void throw_v2_error(JNIEnv *env, const v2_error &err) { /* --- connection --- */ // Transitional: the C API v2 handle of the connection of a connection holder -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1from_1ref(JNIEnv *env, jclass, jobject conn_ref) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1from_1ref(JNIEnv *env, jclass, + jobject conn_ref) { auto conn = conn_ref_buf_to_conn(env, conn_ref); if (env->ExceptionCheck()) { return nullptr; @@ -65,12 +66,14 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_ return make_ptr_buf(env, conn); } -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1interrupt(JNIEnv *env, jclass, jobject conn_buf) { +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1interrupt(JNIEnv *env, jclass, + jobject conn_buf) { CHECK_BUF(conn, conn_buf, duckdb_v2_connection_handle, "connection"); CALL_V2(duckdb_v2_connection_interrupt(conn, ERR_OUT), ); } -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1progress_1get(JNIEnv *env, jclass, jobject conn_buf) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1progress_1get(JNIEnv *env, jclass, + jobject conn_buf) { CHECK_BUF_RET(conn, conn_buf, duckdb_v2_connection_handle, "connection", nullptr); double percentage = -1; uint64_t rows_processed = 0; @@ -82,7 +85,8 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_ /* --- parsing --- */ -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1parse_1sql(JNIEnv *env, jclass, jobject conn_buf, jbyteArray sql_j) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1parse_1sql(JNIEnv *env, jclass, jobject conn_buf, + jbyteArray sql_j) { CHECK_BUF_RET(conn, conn_buf, duckdb_v2_connection_handle, "connection", nullptr); auto sql = jbyteArray_to_string(env, sql_j); if (env->ExceptionCheck()) { @@ -94,31 +98,36 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1parse_1sql( } // Returns null when there are no more statements -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1iterator_1next(JNIEnv *env, jclass, jobject it_buf) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1iterator_1next(JNIEnv *env, jclass, + jobject it_buf) { CHECK_BUF_RET(it, it_buf, duckdb_v2_statement_iterator_handle, "statement iterator", nullptr); duckdb_v2_sql_statement_handle statement = nullptr; CALL_V2(duckdb_v2_statement_iterator_next(it, &statement, ERR_OUT), nullptr); return make_ptr_buf(env, statement); } -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1iterator_1destroy(JNIEnv *env, jclass, jobject it_buf) { +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1iterator_1destroy(JNIEnv *env, jclass, + jobject it_buf) { CHECK_BUF(it, it_buf, duckdb_v2_statement_iterator_handle, "statement iterator"); duckdb_v2_statement_iterator_destroy(&it); } -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement_1destroy(JNIEnv *env, jclass, jobject st_buf) { +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement_1destroy(JNIEnv *env, jclass, + jobject st_buf) { CHECK_BUF(st, st_buf, duckdb_v2_sql_statement_handle, "statement"); duckdb_v2_sql_statement_destroy(&st); } -JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement_1get_1type(JNIEnv *env, jclass, jobject st_buf) { +JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement_1get_1type(JNIEnv *env, jclass, + jobject st_buf) { CHECK_BUF_RET(st, st_buf, duckdb_v2_sql_statement_handle, "statement", 0); DUCKDB_V2_STATEMENT_TYPE type = DUCKDB_V2_STATEMENT_TYPE_INVALID; CALL_V2(duckdb_v2_sql_statement_get_type(st, &type, ERR_OUT), 0); return static_cast(type); } -JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement_1get_1parameter_1count(JNIEnv *env, jclass, jobject st_buf) { +JNIEXPORT jlong JNICALL +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement_1get_1parameter_1count(JNIEnv *env, jclass, jobject st_buf) { CHECK_BUF_RET(st, st_buf, duckdb_v2_sql_statement_handle, "statement", 0); idx_t count = 0; CALL_V2(duckdb_v2_sql_statement_get_parameter_count(st, &count, ERR_OUT), 0); @@ -127,8 +136,8 @@ JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statemen /* --- prepared statements --- */ -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1prepared_1statement_1create(JNIEnv *env, jclass, jobject conn_buf, jobject st_buf, - jboolean require_cacheable) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1prepared_1statement_1create( + JNIEnv *env, jclass, jobject conn_buf, jobject st_buf, jboolean require_cacheable) { CHECK_BUF_RET(conn, conn_buf, duckdb_v2_connection_handle, "connection", nullptr); CHECK_BUF_RET(st, st_buf, duckdb_v2_sql_statement_handle, "statement", nullptr); duckdb_v2_prepared_statement_handle prepared = nullptr; @@ -136,7 +145,8 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1prepared_1s return make_ptr_buf(env, prepared); } -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1prepared_1statement_1destroy(JNIEnv *env, jclass, jobject prepared_buf) { +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1prepared_1statement_1destroy(JNIEnv *env, jclass, + jobject prepared_buf) { CHECK_BUF(prepared, prepared_buf, duckdb_v2_prepared_statement_handle, "prepared statement"); duckdb_v2_prepared_statement_destroy(&prepared); } @@ -159,8 +169,8 @@ static bool read_values(JNIEnv *env, jobjectArray values_j, std::vector values; if (!read_values(env, values_j, values)) { @@ -173,8 +183,10 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1prepared_1s return make_ptr_buf(env, result); } -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1execute(JNIEnv *env, jclass, jobject conn_buf, jobject st_buf, - jobjectArray values_j) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1execute(JNIEnv *env, jclass, + jobject conn_buf, + jobject st_buf, + jobjectArray values_j) { CHECK_BUF_RET(conn, conn_buf, duckdb_v2_connection_handle, "connection", nullptr); CHECK_BUF_RET(st, st_buf, duckdb_v2_sql_statement_handle, "statement", nullptr); std::vector values; @@ -188,7 +200,9 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1 } // Returns the output schema and the parameters schema -JNIEXPORT jobjectArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1bind(JNIEnv *env, jclass, jobject conn_buf, jobject st_buf) { +JNIEXPORT jobjectArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1bind(JNIEnv *env, jclass, + jobject conn_buf, + jobject st_buf) { CHECK_BUF_RET(conn, conn_buf, duckdb_v2_connection_handle, "connection", nullptr); CHECK_BUF_RET(st, st_buf, duckdb_v2_sql_statement_handle, "statement", nullptr); v2_schema output; @@ -214,19 +228,23 @@ JNIEXPORT jobjectArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statem /* --- schemas --- */ -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1destroy(JNIEnv *env, jclass, jobject schema_buf) { +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1destroy(JNIEnv *env, jclass, + jobject schema_buf) { CHECK_BUF(schema, schema_buf, duckdb_v2_schema_handle, "schema"); duckdb_v2_schema_destroy(&schema); } -JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1count(JNIEnv *env, jclass, jobject schema_buf) { +JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1count(JNIEnv *env, jclass, + jobject schema_buf) { CHECK_BUF_RET(schema, schema_buf, duckdb_v2_schema_handle, "schema", 0); idx_t count = 0; CALL_V2(duckdb_v2_schema_get_count(schema, &count, ERR_OUT), 0); return uint64_to_jlong(count); } -JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1name(JNIEnv *env, jclass, jobject schema_buf, jlong index) { +JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1name(JNIEnv *env, jclass, + jobject schema_buf, + jlong index) { CHECK_BUF_RET(schema, schema_buf, duckdb_v2_schema_handle, "schema", nullptr); idx_t idx = jlong_to_idx(env, index); if (env->ExceptionCheck()) { @@ -240,7 +258,9 @@ JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1 } // The returned type is borrowed from the schema and must not be destroyed -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1type(JNIEnv *env, jclass, jobject schema_buf, jlong index) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1type(JNIEnv *env, jclass, + jobject schema_buf, + jlong index) { CHECK_BUF_RET(schema, schema_buf, duckdb_v2_schema_handle, "schema", nullptr); idx_t idx = jlong_to_idx(env, index); if (env->ExceptionCheck()) { @@ -255,38 +275,44 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get /* --- results --- */ -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1destroy(JNIEnv *env, jclass, jobject result_buf) { +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1destroy(JNIEnv *env, jclass, + jobject result_buf) { CHECK_BUF(result, result_buf, duckdb_v2_result_handle, "result"); duckdb_v2_result_destroy(&result); } -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1get_1schema(JNIEnv *env, jclass, jobject result_buf) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1get_1schema(JNIEnv *env, jclass, + jobject result_buf) { CHECK_BUF_RET(result, result_buf, duckdb_v2_result_handle, "result", nullptr); duckdb_v2_schema_handle schema = nullptr; CALL_V2(duckdb_v2_result_get_schema(result, &schema, ERR_OUT), nullptr); return make_ptr_buf(env, schema); } -JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1get_1result_1type(JNIEnv *env, jclass, jobject result_buf) { +JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1get_1result_1type(JNIEnv *env, jclass, + jobject result_buf) { CHECK_BUF_RET(result, result_buf, duckdb_v2_result_handle, "result", 0); DUCKDB_V2_RESULT_TYPE type = DUCKDB_V2_RESULT_TYPE_NOTHING; CALL_V2(duckdb_v2_result_get_result_type(result, &type, ERR_OUT), 0); return static_cast(type); } -JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1get_1statement_1type(JNIEnv *env, jclass, jobject result_buf) { +JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1get_1statement_1type(JNIEnv *env, jclass, + jobject result_buf) { CHECK_BUF_RET(result, result_buf, duckdb_v2_result_handle, "result", 0); DUCKDB_V2_STATEMENT_TYPE type = DUCKDB_V2_STATEMENT_TYPE_INVALID; CALL_V2(duckdb_v2_result_get_statement_type(result, &type, ERR_OUT), 0); return static_cast(type); } -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1wait(JNIEnv *env, jclass, jobject result_buf) { +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1wait(JNIEnv *env, jclass, + jobject result_buf) { CHECK_BUF(result, result_buf, duckdb_v2_result_handle, "result"); CALL_V2(duckdb_v2_result_wait(result, ERR_OUT), ); } -JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1drain(JNIEnv *env, jclass, jobject result_buf) { +JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1drain(JNIEnv *env, jclass, + jobject result_buf) { CHECK_BUF_RET(result, result_buf, duckdb_v2_result_handle, "result", 0); idx_t rows_changed = 0; CALL_V2(duckdb_v2_result_drain(result, &rows_changed, ERR_OUT), 0); @@ -295,7 +321,9 @@ JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1drain // Steps the result once, the status (DUCKDB_V2_RESULT_STEP_STATUS) is written to status_out[0], the returned chunk is // null unless the status is CHUNK -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1step(JNIEnv *env, jclass, jobject result_buf, jintArray status_out) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1step(JNIEnv *env, jclass, + jobject result_buf, + jintArray status_out) { CHECK_BUF_RET(result, result_buf, duckdb_v2_result_handle, "result", nullptr); duckdb_v2_data_chunk_handle chunk = nullptr; DUCKDB_V2_RESULT_STEP_STATUS status = DUCKDB_V2_RESULT_STEP_STATUS_WAITING; @@ -306,7 +334,8 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1ste } // Returns null at the end of the result -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1fetch_1chunk(JNIEnv *env, jclass, jobject result_buf) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1fetch_1chunk(JNIEnv *env, jclass, + jobject result_buf) { CHECK_BUF_RET(result, result_buf, duckdb_v2_result_handle, "result", nullptr); duckdb_v2_data_chunk_handle chunk = nullptr; CALL_V2(duckdb_v2_result_fetch_chunk(result, &chunk, ERR_OUT), nullptr); @@ -316,15 +345,16 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1fet /* --- factory and values --- */ // The factory is borrowed from the connection -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1factory(JNIEnv *env, jclass, jobject conn_buf) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1factory(JNIEnv *env, jclass, + jobject conn_buf) { CHECK_BUF_RET(conn, conn_buf, duckdb_v2_connection_handle, "connection", nullptr); duckdb_v2_factory_handle factory = nullptr; CALL_V2(duckdb_v2_connection_get_factory(conn, &factory, ERR_OUT), nullptr); return make_ptr_buf(env, factory); } -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1factory_1create_1type_1from_1text(JNIEnv *env, jclass, jobject factory_buf, - jbyteArray text_j) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1factory_1create_1type_1from_1text( + JNIEnv *env, jclass, jobject factory_buf, jbyteArray text_j) { CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); auto text = jbyteArray_to_string(env, text_j); if (env->ExceptionCheck()) { @@ -335,33 +365,48 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1factory_1cr return make_logical_type_buf(env, type); } -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1destroy(JNIEnv *env, jclass, jobject value_buf) { +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1destroy(JNIEnv *env, jclass, + jobject value_buf) { CHECK_BUF(value, value_buf, duckdb_v2_value_handle, "value"); duckdb_v2_value_destroy(&value); } -#define VALUE_CREATE_SCALAR(FN, JTYPE, CALL) \ - JNIEXPORT jobject JNICALL FN(JNIEnv *env, jclass, jobject factory_buf, JTYPE in_value) { \ +#define VALUE_CREATE_SCALAR(FN, JTYPE, CALL) \ + JNIEXPORT jobject JNICALL FN(JNIEnv *env, jclass, jobject factory_buf, JTYPE in_value) { \ CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); \ duckdb_v2_value_handle value = nullptr; \ CALL_V2(CALL, nullptr); \ return make_ptr_buf(env, value); \ } -VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1bool, jboolean, duckdb_v2_value_create_bool(factory, in_value == JNI_TRUE, &value, ERR_OUT)) -VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1tinyint, jbyte, duckdb_v2_value_create_tinyint(factory, in_value, &value, ERR_OUT)) -VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1smallint, jshort, duckdb_v2_value_create_smallint(factory, in_value, &value, ERR_OUT)) -VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1int, jint, duckdb_v2_value_create_int(factory, in_value, &value, ERR_OUT)) -VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1bigint, jlong, duckdb_v2_value_create_bigint(factory, in_value, &value, ERR_OUT)) -VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1float, jfloat, duckdb_v2_value_create_float(factory, in_value, &value, ERR_OUT)) -VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1double, jdouble, duckdb_v2_value_create_double(factory, in_value, &value, ERR_OUT)) -VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1date, jint, duckdb_v2_value_create_date(factory, in_value, &value, ERR_OUT)) -VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1time, jlong, duckdb_v2_value_create_time(factory, in_value, &value, ERR_OUT)) -VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp, jlong, duckdb_v2_value_create_timestamp(factory, in_value, &value, ERR_OUT)) -VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp_1ns, jlong, duckdb_v2_value_create_timestamp_ns(factory, in_value, &value, ERR_OUT)) -VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp_1tz, jlong, duckdb_v2_value_create_timestamp_tz(factory, in_value, &value, ERR_OUT)) - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1null(JNIEnv *env, jclass, jobject factory_buf, jobject type_buf) { +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1bool, jboolean, + duckdb_v2_value_create_bool(factory, in_value == JNI_TRUE, &value, ERR_OUT)) +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1tinyint, jbyte, + duckdb_v2_value_create_tinyint(factory, in_value, &value, ERR_OUT)) +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1smallint, jshort, + duckdb_v2_value_create_smallint(factory, in_value, &value, ERR_OUT)) +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1int, jint, + duckdb_v2_value_create_int(factory, in_value, &value, ERR_OUT)) +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1bigint, jlong, + duckdb_v2_value_create_bigint(factory, in_value, &value, ERR_OUT)) +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1float, jfloat, + duckdb_v2_value_create_float(factory, in_value, &value, ERR_OUT)) +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1double, jdouble, + duckdb_v2_value_create_double(factory, in_value, &value, ERR_OUT)) +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1date, jint, + duckdb_v2_value_create_date(factory, in_value, &value, ERR_OUT)) +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1time, jlong, + duckdb_v2_value_create_time(factory, in_value, &value, ERR_OUT)) +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp, jlong, + duckdb_v2_value_create_timestamp(factory, in_value, &value, ERR_OUT)) +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp_1ns, jlong, + duckdb_v2_value_create_timestamp_ns(factory, in_value, &value, ERR_OUT)) +VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp_1tz, jlong, + duckdb_v2_value_create_timestamp_tz(factory, in_value, &value, ERR_OUT)) + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1null(JNIEnv *env, jclass, + jobject factory_buf, + jobject type_buf) { CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); auto type = logical_type_buf_to_logical_type(env, type_buf); if (env->ExceptionCheck()) { @@ -372,8 +417,9 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1crea return make_ptr_buf(env, value); } -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1hugeint(JNIEnv *env, jclass, jobject factory_buf, jlong lower, - jlong upper) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1hugeint(JNIEnv *env, jclass, + jobject factory_buf, + jlong lower, jlong upper) { CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); duckdb_v2_hugeint_t in_value {static_cast(lower), static_cast(upper)}; duckdb_v2_value_handle value = nullptr; @@ -381,8 +427,9 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1crea return make_ptr_buf(env, value); } -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1uuid(JNIEnv *env, jclass, jobject factory_buf, jlong lower, - jlong upper) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1uuid(JNIEnv *env, jclass, + jobject factory_buf, + jlong lower, jlong upper) { CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); duckdb_v2_hugeint_t in_value {static_cast(lower), static_cast(upper)}; duckdb_v2_value_handle value = nullptr; @@ -390,8 +437,10 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1crea return make_ptr_buf(env, value); } -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1decimal(JNIEnv *env, jclass, jobject factory_buf, jlong lower, - jlong upper, jint width, jint scale) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1decimal(JNIEnv *env, jclass, + jobject factory_buf, + jlong lower, jlong upper, + jint width, jint scale) { CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); duckdb_v2_hugeint_t in_value {static_cast(lower), static_cast(upper)}; duckdb_v2_value_handle value = nullptr; @@ -401,8 +450,9 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1crea return make_ptr_buf(env, value); } -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1varchar(JNIEnv *env, jclass, jobject factory_buf, - jbyteArray in_value_j) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1varchar(JNIEnv *env, jclass, + jobject factory_buf, + jbyteArray in_value_j) { CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); auto in_value = jbyteArray_to_string(env, in_value_j); if (env->ExceptionCheck()) { @@ -413,8 +463,9 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1crea return make_ptr_buf(env, value); } -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1blob(JNIEnv *env, jclass, jobject factory_buf, - jbyteArray in_value_j) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1blob(JNIEnv *env, jclass, + jobject factory_buf, + jbyteArray in_value_j) { CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); auto in_value = jbyteArray_to_string(env, in_value_j); if (env->ExceptionCheck()) { @@ -426,8 +477,10 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1crea } // The child values are borrowed for the call -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1list(JNIEnv *env, jclass, jobject factory_buf, jobject type_buf, - jobjectArray children_j) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1list(JNIEnv *env, jclass, + jobject factory_buf, + jobject type_buf, + jobjectArray children_j) { CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); auto type = logical_type_buf_to_logical_type(env, type_buf); if (env->ExceptionCheck()) { @@ -442,8 +495,10 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1crea return make_ptr_buf(env, value); } -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1struct(JNIEnv *env, jclass, jobject factory_buf, - jobjectArray names_j, jobjectArray children_j) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1struct(JNIEnv *env, jclass, + jobject factory_buf, + jobjectArray names_j, + jobjectArray children_j) { CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); std::vector children; if (!read_values(env, children_j, children)) { @@ -470,15 +525,15 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1crea name_lens.push_back(name.size()); } duckdb_v2_value_handle value = nullptr; - CALL_V2(duckdb_v2_value_create_struct(factory, name_ptrs.data(), name_lens.data(), children.data(), - children.size(), &value, ERR_OUT), + CALL_V2(duckdb_v2_value_create_struct(factory, name_ptrs.data(), name_lens.data(), children.data(), children.size(), + &value, ERR_OUT), nullptr); return make_ptr_buf(env, value); } -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1map(JNIEnv *env, jclass, jobject factory_buf, jobject key_type_buf, - jobject value_type_buf, jobjectArray keys_j, - jobjectArray values_j) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1map( + JNIEnv *env, jclass, jobject factory_buf, jobject key_type_buf, jobject value_type_buf, jobjectArray keys_j, + jobjectArray values_j) { CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); auto key_type = logical_type_buf_to_logical_type(env, key_type_buf); if (env->ExceptionCheck()) { @@ -504,7 +559,9 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1crea return make_ptr_buf(env, value); } -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1type(JNIEnv *env, jclass, jobject factory_buf, jobject type_buf) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1type(JNIEnv *env, jclass, + jobject factory_buf, + jobject type_buf) { CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); auto type = logical_type_buf_to_logical_type(env, type_buf); if (env->ExceptionCheck()) { @@ -515,7 +572,8 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1crea return make_ptr_buf(env, value); } -JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1to_1string(JNIEnv *env, jclass, jobject value_buf) { +JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1to_1string(JNIEnv *env, jclass, + jobject value_buf) { CHECK_BUF_RET(value, value_buf, duckdb_v2_value_handle, "value", nullptr); idx_t length = 0; CALL_V2(duckdb_v2_value_to_string(value, nullptr, 0, &length, ERR_OUT), nullptr); @@ -526,13 +584,15 @@ JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1t /* --- vectors --- */ -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1flatten(JNIEnv *env, jclass, jobject vector_buf) { +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1flatten(JNIEnv *env, jclass, + jobject vector_buf) { CHECK_BUF(vector, vector_buf, duckdb_v2_vector_handle, "vector"); CALL_V2(duckdb_v2_vector_flatten(vector, ERR_OUT), ); } // The returned value is owned by the caller -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1value(JNIEnv *env, jclass, jobject vector_buf, jlong row) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1value(JNIEnv *env, jclass, + jobject vector_buf, jlong row) { CHECK_BUF_RET(vector, vector_buf, duckdb_v2_vector_handle, "vector", nullptr); idx_t idx = jlong_to_idx(env, row); if (env->ExceptionCheck()) { @@ -545,7 +605,8 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get /* --- logical type parameters --- */ -JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1get_1param_1count(JNIEnv *env, jclass, jobject type_buf) { +JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1get_1param_1count(JNIEnv *env, jclass, + jobject type_buf) { auto type = logical_type_buf_to_logical_type(env, type_buf); if (env->ExceptionCheck()) { return 0; @@ -556,7 +617,10 @@ JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type } // The returned value is owned by the caller -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1get_1param_1value(JNIEnv *env, jclass, jobject type_buf, jlong index) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1get_1param_1value(JNIEnv *env, + jclass, + jobject type_buf, + jlong index) { auto type = logical_type_buf_to_logical_type(env, type_buf); if (env->ExceptionCheck()) { return nullptr; @@ -573,8 +637,8 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1ty } // Returns null for a positional parameter -JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1get_1param_1name(JNIEnv *env, jclass, jobject type_buf, - jlong index) { +JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1get_1param_1name( + JNIEnv *env, jclass, jobject type_buf, jlong index) { auto type = logical_type_buf_to_logical_type(env, type_buf); if (env->ExceptionCheck()) { return nullptr; @@ -595,7 +659,8 @@ JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_ } // Unwraps the type of a TYPE value, the returned type is owned by the caller -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1get_1type(JNIEnv *env, jclass, jobject value_buf) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1get_1type(JNIEnv *env, jclass, + jobject value_buf) { CHECK_BUF_RET(value, value_buf, duckdb_v2_value_handle, "value", nullptr); duckdb_v2_logical_type_handle type = nullptr; CALL_V2(duckdb_v2_value_get_type(value, &type, ERR_OUT), nullptr); @@ -605,7 +670,8 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1get_ /* --- configuration --- */ // The returned config is borrowed from the connection -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1config(JNIEnv *env, jclass, jobject conn_buf) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1config(JNIEnv *env, jclass, + jobject conn_buf) { CHECK_BUF_RET(conn, conn_buf, duckdb_v2_connection_handle, "connection", nullptr); duckdb_v2_config_handle config = nullptr; CALL_V2(duckdb_v2_connection_get_config(conn, &config, ERR_OUT), nullptr); @@ -613,8 +679,9 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_ } // The returned value is owned by the caller -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1value(JNIEnv *env, jclass, jobject config_buf, - jbyteArray name_j) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1value(JNIEnv *env, jclass, + jobject config_buf, + jbyteArray name_j) { CHECK_BUF_RET(config, config_buf, duckdb_v2_config_handle, "config", nullptr); auto name = jbyteArray_to_string(env, name_j); if (env->ExceptionCheck()) { @@ -629,7 +696,8 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get /* --- transitional --- */ // Wraps the result into a chunked result of the bindings API, the holder takes the ownership of the result -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1chunked_1result_1create(JNIEnv *env, jclass, jobject result_buf) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1chunked_1result_1create(JNIEnv *env, jclass, + jobject result_buf) { CHECK_BUF_RET(result, result_buf, duckdb_v2_result_handle, "result", nullptr); try { return env->NewDirectByteBuffer(new ChunkedResultHolder(result), 0); @@ -643,7 +711,8 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1chunked_1re /* --- variants --- */ // The returned value is owned by the caller -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1variant_1to_1value(JNIEnv *env, jclass, jobject value_buf) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1variant_1to_1value(JNIEnv *env, jclass, + jobject value_buf) { CHECK_BUF_RET(value, value_buf, duckdb_v2_value_handle, "value", nullptr); duckdb_v2_value_handle out_value = nullptr; CALL_V2(duckdb_v2_value_variant_to_value(value, &out_value, ERR_OUT), nullptr); @@ -651,15 +720,17 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1vari } // The returned type is owned by the caller -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1get_1logical_1type(JNIEnv *env, jclass, jobject value_buf) { +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1get_1logical_1type(JNIEnv *env, jclass, + jobject value_buf) { CHECK_BUF_RET(value, value_buf, duckdb_v2_value_handle, "value", nullptr); duckdb_v2_logical_type_handle type = nullptr; CALL_V2(duckdb_v2_value_get_logical_type(value, &type, ERR_OUT), nullptr); return make_logical_type_buf(env, type); } -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1set_1value(JNIEnv *env, jclass, jobject vector_buf, jlong row, - jobject value_buf) { +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1set_1value(JNIEnv *env, jclass, + jobject vector_buf, jlong row, + jobject value_buf) { CHECK_BUF(vector, vector_buf, duckdb_v2_vector_handle, "vector"); CHECK_BUF(value, value_buf, duckdb_v2_value_handle, "value"); idx_t idx = jlong_to_idx(env, row); @@ -669,7 +740,8 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1set_1v CALL_V2(duckdb_v2_vector_set_value(vector, idx, value, ERR_OUT), ); } -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1set_1size(JNIEnv *env, jclass, jobject vector_buf, jlong size) { +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1set_1size(JNIEnv *env, jclass, + jobject vector_buf, jlong size) { CHECK_BUF(vector, vector_buf, duckdb_v2_vector_handle, "vector"); idx_t sz = jlong_to_idx(env, size); if (env->ExceptionCheck()) { diff --git a/src/jni/duckdb_java.cpp b/src/jni/duckdb_java.cpp index 4cf0f2c83..609190f59 100644 --- a/src/jni/duckdb_java.cpp +++ b/src/jni/duckdb_java.cpp @@ -180,33 +180,6 @@ jboolean _duckdb_jdbc_get_auto_commit(JNIEnv *env, jclass, jobject conn_ref_buf) return conn_ref->IsAutoCommit(); } -void _duckdb_jdbc_interrupt(JNIEnv *env, jclass, jobject conn_ref_buf) { - auto conn_ref = get_connection(env, conn_ref_buf); - if (!conn_ref) { - return; - } - conn_ref->Interrupt(); -} - -jobject _duckdb_jdbc_query_progress(JNIEnv *env, jclass, jobject conn_ref_buf) { - auto conn_ref = get_connection(env, conn_ref_buf); - if (!conn_ref) { - return nullptr; - } - auto conn_holder = get_connection_ref(env, conn_ref_buf); - auto conn = duckdb::capiv2::Convert(conn_holder->connection.get()); - double percentage = -1; - uint64_t rows_processed = 0; - uint64_t total_rows_to_process = 0; - v2_error err; - if (duckdb_v2_connection_progress_get(conn, &percentage, &rows_processed, &total_rows_to_process, err.out()) != - DUCKDB_V2_ERROR_NONE) { - throw InvalidInputException(err.message()); - } - return env->NewObject(J_QueryProgress, J_QueryProgress_init, static_cast(percentage), - uint64_to_jlong(rows_processed), uint64_to_jlong(total_rows_to_process)); -} - void _duckdb_jdbc_disconnect(JNIEnv *env, jclass, jobject conn_ref_buf) { if (nullptr == conn_ref_buf) { return; @@ -219,767 +192,6 @@ void _duckdb_jdbc_disconnect(JNIEnv *env, jclass, jobject conn_ref_buf) { #include "utf8proc_wrapper.hpp" -jobject _duckdb_jdbc_prepare(JNIEnv *env, jclass, jobject conn_ref_buf, jbyteArray query_j) { - auto conn_ref = get_connection(env, conn_ref_buf); - if (!conn_ref) { - return nullptr; - } - - auto query = jbyteArray_to_string(env, query_j); - - auto statements = conn_ref->ExtractStatements(query.c_str()); - if (statements.empty()) { - throw InvalidInputException("No statements to execute."); - } - - // preparing must not have side effects, so multiple statements are rejected instead of - // executing all statements besides the last one - if (statements.size() > 1) { - throw InvalidInputException("Cannot prepare multiple statements at once, statements count: " + - std::to_string(statements.size())); - } - - auto stmt_ref = make_uniq(); - stmt_ref->stmt = conn_ref->Prepare(std::move(statements.back())); - if (stmt_ref->stmt->HasError()) { - string error_msg = string(stmt_ref->stmt->GetError()); - stmt_ref->stmt = nullptr; - ThrowJNI(env, error_msg.c_str()); - return nullptr; - } - return env->NewDirectByteBuffer(stmt_ref.release(), 0); -} - -jobject _duckdb_jdbc_pending_query(JNIEnv *env, jclass, jobject conn_ref_buf, jbyteArray query_j) { - auto conn_ref = get_connection(env, conn_ref_buf); - if (!conn_ref) { - return nullptr; - } - - auto query = jbyteArray_to_string(env, query_j); - - auto statements = conn_ref->ExtractStatements(query.c_str()); - if (statements.empty()) { - throw InvalidInputException("No statements to execute."); - } - - // if there are multiple statements, we directly execute the statements besides the last one - // we only return the result of the last statement to the user, unless one of the previous statements fails - for (idx_t i = 0; i + 1 < statements.size(); i++) { - auto res = conn_ref->Query(std::move(statements[i])); - if (res->HasError()) { - res->ThrowError(); - } - } - - Value result; - bool stream_results = - conn_ref->context->TryGetCurrentSetting("jdbc_stream_results", result) ? result.GetValue() : false; - - auto pending_ref = make_uniq(); - pending_ref->pending = conn_ref->Submit(std::move(statements.back())); - pending_ref->streaming = stream_results; - - return env->NewDirectByteBuffer(pending_ref.release(), 0); -} - -template -static void throw_execution_java_error(JNIEnv *env, T *res) { - std::string error_msg = std::string(res->GetError()); - duckdb::ExceptionType error_type = res->GetErrorType(); - jclass exc_type = duckdb::ExceptionType::INTERRUPT == error_type ? J_SQLTimeoutException : J_SQLException; - env->ThrowNew(exc_type, error_msg.c_str()); -} - -static duckdb::unique_ptr execute_prepared_statement(JNIEnv *env, jobject stmt_ref_buf, - jobjectArray params, bool stream_results) { - auto stmt_ref = reinterpret_cast(env->GetDirectBufferAddress(stmt_ref_buf)); - if (!stmt_ref || !stmt_ref->stmt) { - throw InvalidInputException("Invalid statement"); - } - - duckdb::vector duckdb_params; - - idx_t param_len = env->GetArrayLength(params); - - if (param_len != stmt_ref->stmt->GetParameterCount()) { - throw InvalidInputException("Parameter count mismatch"); - } - - auto context = stmt_ref->stmt->TryGetContext(); - if (!context) { - throw InvalidInputException("Attempting to execute a prepared statement after its connection was closed!"); - } - - if (param_len > 0) { - for (idx_t i = 0; i < param_len; i++) { - auto param = env->GetObjectArrayElement(params, i); - duckdb::Value val = to_duckdb_value(env, param, *context); - env->DeleteLocalRef(param); - duckdb_params.push_back(std::move(val)); - } - } - - duckdb::unique_ptr res; - if (stream_results) { - res = stmt_ref->stmt->Submit(duckdb_params); - } else { - res = stmt_ref->stmt->Execute(duckdb_params); - } - - if (res->HasError()) { - throw_execution_java_error(env, res.get()); - return nullptr; - } - - return res; -} - -duckdb::unique_ptr> complete_query_streaming(JNIEnv *env, duckdb::unique_ptr pending) { - auto stream = make_uniq>(std::move(pending)); - while (!duckdb::IsObservable(stream->ExecuteTask())) { - } - if (stream->HasError()) { - throw_execution_java_error(env, stream.get()); - return nullptr; - } - return stream; -} - -duckdb::unique_ptr complete_query_materialized(JNIEnv *env, duckdb::unique_ptr pending) { - pending->Complete(); - if (pending->HasError()) { - throw_execution_java_error(env, pending.get()); - return nullptr; - } - return pending; -} - -jobject _duckdb_jdbc_execute(JNIEnv *env, jclass, jobject stmt_ref_buf, jobjectArray params) { - auto stmt_ref = reinterpret_cast(env->GetDirectBufferAddress(stmt_ref_buf)); - if (!stmt_ref || !stmt_ref->stmt) { - throw InvalidInputException("Invalid statement"); - } - auto context = stmt_ref->stmt->TryGetContext(); - if (!context) { - throw InvalidInputException("Attempting to execute a prepared statement after its connection was closed!"); - } - Value result; - bool stream_results_user = - context->TryGetCurrentSetting("jdbc_stream_results", result) ? result.GetValue() : false; - - auto pending = execute_prepared_statement(env, stmt_ref_buf, params, stream_results_user); - if (pending == nullptr) { - return nullptr; - } - - bool stream_results_stmt = StreamsByDefault(stmt_ref->stmt->GetStatementType(), *pending); - bool stream_results = stream_results_user && stream_results_stmt; - - auto res_ref = make_uniq(); - - if (stream_results) { - auto stream = complete_query_streaming(env, std::move(pending)); - if (!stream) { - return nullptr; - } - res_ref->stream = std::move(stream); - } else { - auto res = complete_query_materialized(env, std::move(pending)); - if (!res) { - return nullptr; - } - res_ref->res = std::move(res); - } - - return env->NewDirectByteBuffer(res_ref.release(), 0); -} - -jobject _duckdb_jdbc_execute_capi(JNIEnv *env, jclass, jobject stmt_ref_buf, jobjectArray params) { - auto stmt_ref = reinterpret_cast(env->GetDirectBufferAddress(stmt_ref_buf)); - if (!stmt_ref || !stmt_ref->stmt) { - throw InvalidInputException("Invalid statement"); - } - - auto pending = execute_prepared_statement(env, stmt_ref_buf, params, true); - if (!pending) { - return nullptr; - } - - bool stream_results = StreamsByDefault(stmt_ref->stmt->GetStatementType(), *pending); - - // The completed result is adopted into the result state machine of the C API v2 (in the same state - // it gets into when it is ready to be consumed) and is read through the C API v2. There is no way to - // construct a C API v2 result from an engine result using C API v2. - auto wrapper = make_uniq(); - wrapper->context = stmt_ref->stmt->TryGetContext(); - wrapper->statement_type = stmt_ref->stmt->GetStatementType(); - if (stream_results) { - auto stream = complete_query_streaming(env, std::move(pending)); - if (!stream) { - return nullptr; - } - wrapper->types = stream->GetTypes(); - wrapper->names = stream->GetNames(); - wrapper->properties = stream->GetStatementProperties(); - wrapper->stream = std::move(stream); - wrapper->stream_when_ready = true; - } else { - auto res = complete_query_materialized(env, std::move(pending)); - if (!res) { - return nullptr; - } - wrapper->types = res->GetTypes(); - wrapper->names = res->GetNames(); - wrapper->properties = res->GetStatementProperties(); - wrapper->handle = std::move(res); - wrapper->stream_when_ready = false; - } - wrapper->metadata_available = true; - wrapper->state = duckdb::capiv2::ResultWrapperV2::State::STREAMING; - - auto out = make_uniq(duckdb::capiv2::Convert(wrapper.release())); - - return env->NewDirectByteBuffer(out.release(), 0); -} - -jobject _duckdb_jdbc_execute_pending(JNIEnv *env, jclass, jobject pending_ref_buf) { - auto pending_ref = reinterpret_cast(env->GetDirectBufferAddress(pending_ref_buf)); - if (!pending_ref || !pending_ref->pending) { - throw InvalidInputException("Invalid pending query"); - } - - if (pending_ref->pending->HasError()) { - throw_execution_java_error(env, pending_ref->pending.get()); - pending_ref->pending = nullptr; - return nullptr; - } - - // the pending result was submitted from the SQL statement as written, so its type is the written type - bool stream_results = StreamsByDefault(pending_ref->pending->GetStatementType(), *pending_ref->pending); - auto res_ref = make_uniq(); - - if (pending_ref->streaming && stream_results) { - auto stream = complete_query_streaming(env, std::move(pending_ref->pending)); - if (!stream) { - return nullptr; - } - res_ref->stream = std::move(stream); - } else { - auto res = complete_query_materialized(env, std::move(pending_ref->pending)); - if (!res) { - return nullptr; - } - res_ref->res = std::move(res); - } - - return env->NewDirectByteBuffer(res_ref.release(), 0); -} - -void _duckdb_jdbc_release(JNIEnv *env, jclass, jobject stmt_ref_buf) { - if (nullptr == stmt_ref_buf) { - return; - } - auto stmt_ref = reinterpret_cast(env->GetDirectBufferAddress(stmt_ref_buf)); - if (stmt_ref) { - delete stmt_ref; - } -} - -void _duckdb_jdbc_release_pending(JNIEnv *env, jclass, jobject pending_ref_buf) { - if (nullptr == pending_ref_buf) { - return; - } - auto pending_ref = reinterpret_cast(env->GetDirectBufferAddress(pending_ref_buf)); - if (pending_ref) { - delete pending_ref; - } -} - -void _duckdb_jdbc_free_result(JNIEnv *env, jclass, jobject res_ref_buf) { - if (nullptr == res_ref_buf) { - return; - } - auto res_ref = reinterpret_cast(env->GetDirectBufferAddress(res_ref_buf)); - if (res_ref) { - delete res_ref; - } -} - -static jobject build_meta(JNIEnv *env, size_t column_count, size_t n_param, const duckdb::vector &names, - const duckdb::vector &types, StatementProperties properties, - const duckdb::vector ¶m_types) { - auto name_array = env->NewObjectArray(column_count, J_String, nullptr); - auto type_array = env->NewObjectArray(column_count, J_String, nullptr); - auto type_detail_array = env->NewObjectArray(column_count, J_String, nullptr); - - for (idx_t col_idx = 0; col_idx < column_count; col_idx++) { - std::string col_name; - if (types[col_idx].id() == LogicalTypeId::ENUM) { - col_name = "ENUM"; - } else { - col_name = types[col_idx].ToString(); - } - - const std::string &sname = names[col_idx].GetIdentifierName(); - jstring jname = decode_charbuffer_to_jstring(env, sname.c_str(), sname.length()); - env->SetObjectArrayElement(name_array, col_idx, jname); - env->DeleteLocalRef(jname); - jstring jcolname = env->NewStringUTF(col_name.c_str()); - env->SetObjectArrayElement(type_array, col_idx, jcolname); - env->DeleteLocalRef(jcolname); - jstring jtype = env->NewStringUTF(type_to_jduckdb_type(types[col_idx]).c_str()); - env->SetObjectArrayElement(type_detail_array, col_idx, jtype); - env->DeleteLocalRef(jtype); - } - - jobjectArray param_type_array = env->NewObjectArray(n_param, J_String, nullptr); - jobjectArray param_type_detail_array = env->NewObjectArray(n_param, J_String, nullptr); - - for (idx_t param_idx = 0; param_idx < n_param; param_idx++) { - std::string param_name; - if (param_types[param_idx].id() == LogicalTypeId::ENUM) { - param_name = "ENUM"; - } else { - param_name = param_types[param_idx].ToString(); - } - - jstring jname = env->NewStringUTF(param_name.c_str()); - env->SetObjectArrayElement(param_type_array, param_idx, jname); - env->DeleteLocalRef(jname); - jstring jdetail = env->NewStringUTF(type_to_jduckdb_type(param_types[param_idx]).c_str()); - env->SetObjectArrayElement(param_type_detail_array, param_idx, jdetail); - env->DeleteLocalRef(jdetail); - } - - jstring return_type = env->NewStringUTF(StatementReturnTypeToString(properties.return_type).c_str()); - - jobject res = env->NewObject(J_DuckResultSetMeta, J_DuckResultSetMeta_init, n_param, column_count, name_array, - type_array, type_detail_array, return_type, param_type_array, param_type_detail_array); - env->DeleteLocalRef(return_type); - env->DeleteLocalRef(param_type_detail_array); - env->DeleteLocalRef(param_type_array); - env->DeleteLocalRef(type_detail_array); - env->DeleteLocalRef(type_array); - env->DeleteLocalRef(name_array); - return res; -} - -jobject _duckdb_jdbc_query_result_meta(JNIEnv *env, jclass, jobject res_ref_buf) { - auto res_ref = (ResultHolder *)env->GetDirectBufferAddress(res_ref_buf); - if (!res_ref || (!res_ref->res && !res_ref->stream) || (res_ref->res && res_ref->res->HasError()) || - (res_ref->stream && res_ref->stream->HasError())) { - throw InvalidInputException("Invalid result set"); - } - auto n_param = 0; // no params now - duckdb::vector param_types(n_param); - - if (res_ref->res) { - auto &res = res_ref->res; - return build_meta(env, res->ColumnCount(), n_param, res->GetNames(), res->GetTypes(), - res->GetStatementProperties(), param_types); - } else if (res_ref->stream) { - auto &res = res_ref->stream; - return build_meta(env, res->ColumnCount(), n_param, res->GetNames(), res->GetTypes(), - res->GetStatementProperties(), param_types); - } else { - throw InvalidInputException("Invalid result set"); - } -} - -jobject _duckdb_jdbc_prepared_statement_meta(JNIEnv *env, jclass, jobject stmt_ref_buf) { - - auto stmt_ref = reinterpret_cast(env->GetDirectBufferAddress(stmt_ref_buf)); - if (!stmt_ref || !stmt_ref->stmt || stmt_ref->stmt->HasError()) { - throw InvalidInputException("Invalid statement"); - } - - auto &stmt = stmt_ref->stmt; - auto n_param = stmt->GetParameterCount(); - duckdb::vector param_types(n_param); - if (n_param > 0) { - for (auto &it : stmt->GetNamedParameterMap()) { - LogicalType type; - if (stmt->TryGetParameterType(it.first, type)) { - param_types[it.second - 1] = type; - } - } - } - - return build_meta(env, stmt->ColumnCount(), n_param, stmt->GetNames(), stmt->GetTypes(), - stmt->GetStatementProperties(), param_types); -} - -jobject ProcessVector(JNIEnv *env, Connection *conn_ref, Vector &vec, idx_t row_count); - -jobjectArray _duckdb_jdbc_fetch(JNIEnv *env, jclass, jobject res_ref_buf, jobject conn_ref_buf) { - auto res_ref = reinterpret_cast(env->GetDirectBufferAddress(res_ref_buf)); - if (!res_ref || (!res_ref->res && !res_ref->stream) || (res_ref->res && res_ref->res->HasError()) || - (res_ref->stream && res_ref->stream->HasError())) { - throw InvalidInputException("Invalid result set"); - } - - auto conn_ref = get_connection(env, conn_ref_buf); - if (conn_ref == nullptr) { - return nullptr; - } - - if (res_ref->res) { - res_ref->chunk = res_ref->res->Fetch(); - if (res_ref->res->HasError()) { - throw_execution_java_error(env, res_ref->res.get()); - return nullptr; - } - } else if (res_ref->stream) { - res_ref->chunk = res_ref->stream->Fetch(); - if (res_ref->stream->HasError()) { - throw_execution_java_error(env, res_ref->stream.get()); - return nullptr; - } - } else { - throw InvalidInputException("Invalid result set"); - } - - if (!res_ref->chunk) { - res_ref->chunk = make_uniq(); - } - auto row_count = res_ref->chunk->size(); - jobjectArray vec_array = - reinterpret_cast(env->NewObjectArray(res_ref->chunk->ColumnCount(), J_DuckVector, nullptr)); - - for (idx_t col_idx = 0; col_idx < res_ref->chunk->ColumnCount(); col_idx++) { - auto &vec = res_ref->chunk->data[col_idx]; - - jobject jvec = ProcessVector(env, conn_ref, vec, row_count); - - env->SetObjectArrayElement(vec_array, col_idx, jvec); - env->DeleteLocalRef(jvec); - } - - return vec_array; -} - -jobjectArray _duckdb_jdbc_cast_result_to_strings(JNIEnv *env, jclass, jobject res_ref_buf, jobject conn_ref_buf, - jlong col_idx) { - auto res_ref = reinterpret_cast(env->GetDirectBufferAddress(res_ref_buf)); - if (!res_ref || (!res_ref->res && !res_ref->stream) || (res_ref->res && res_ref->res->HasError()) || - (res_ref->stream && res_ref->stream->HasError())) { - throw InvalidInputException("Invalid result set"); - } - - if (!res_ref->chunk) { - return nullptr; - } - - auto conn_ref = get_connection(env, conn_ref_buf); - if (conn_ref == nullptr) { - return nullptr; - } - - auto row_count = res_ref->chunk->size(); - auto &complex_vec = res_ref->chunk->data[col_idx]; - Vector vec(LogicalType::VARCHAR); - VectorOperations::Cast(*conn_ref->context, complex_vec, vec, row_count); - - jobjectArray string_data = env->NewObjectArray(row_count, J_String, nullptr); - for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { - if (FlatVector::IsNull(vec, row_idx)) { - continue; - } - const string_t *vec_data = FlatVector::GetData(vec); - auto d_str = vec_data[row_idx]; - auto j_str = decode_charbuffer_to_jstring(env, d_str.GetData(), d_str.GetSize()); - env->SetObjectArrayElement(string_data, row_idx, j_str); - } - - return string_data; -} - -template -static jobject make_vec_data_buf(JNIEnv *env, Vector &vec, idx_t row_count) { - T *vec_data = FlatVector::GetDataMutable(vec); - idx_t len = row_count * sizeof(T); - return make_data_buf(env, vec_data, len); -} - -jobject ProcessVector(JNIEnv *env, Connection *conn_ref, Vector &vec, idx_t row_count) { - if (vec.GetVectorType() != VectorType::FLAT_VECTOR) { - vec.Flatten(); - } - jstring type_str = env->NewStringUTF(type_to_jduckdb_type(vec.GetType()).c_str()); - // construct nullmask - jbooleanArray null_array = env->NewBooleanArray(row_count); - jboolean *null_unique_array = env->GetBooleanArrayElements(null_array, nullptr); - for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { - null_unique_array[row_idx] = FlatVector::IsNull(vec, row_idx); - } - env->ReleaseBooleanArrayElements(null_array, null_unique_array, 0); - - jobject jvec = env->NewObject(J_DuckVector, J_DuckVector_init, type_str, static_cast(row_count), null_array); - - jobject constlen_data = nullptr; - jobjectArray varlen_data = nullptr; - Vector *string_vec = &vec; - duckdb::unique_ptr cast_vec; - - switch (vec.GetType().id()) { - case LogicalTypeId::BOOLEAN: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - case LogicalTypeId::TINYINT: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - case LogicalTypeId::SMALLINT: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - case LogicalTypeId::INTEGER: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - case LogicalTypeId::BIGINT: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - case LogicalTypeId::UTINYINT: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - case LogicalTypeId::USMALLINT: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - case LogicalTypeId::UINTEGER: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - case LogicalTypeId::UBIGINT: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - case LogicalTypeId::HUGEINT: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - case LogicalTypeId::UHUGEINT: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - case LogicalTypeId::FLOAT: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - case LogicalTypeId::DECIMAL: { - auto physical_type = vec.GetType().InternalType(); - - switch (physical_type) { - case PhysicalType::INT16: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - case PhysicalType::INT32: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - case PhysicalType::INT64: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - case PhysicalType::INT128: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - default: - throw InternalException("Unimplemented physical type for decimal"); - } - break; - } - case LogicalTypeId::DOUBLE: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - case LogicalTypeId::DATE: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - case LogicalTypeId::TIME: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - case LogicalTypeId::TIME_NS: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - case LogicalTypeId::TIME_TZ: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - case LogicalTypeId::TIMESTAMP_SEC: - case LogicalTypeId::TIMESTAMP_MS: - case LogicalTypeId::TIMESTAMP: - case LogicalTypeId::TIMESTAMP_NS: - case LogicalTypeId::TIMESTAMP_TZ: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - case LogicalTypeId::ENUM: - varlen_data = env->NewObjectArray(row_count, J_String, nullptr); - for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { - if (FlatVector::IsNull(vec, row_idx)) { - continue; - } - auto dstr = vec.GetValue(row_idx).ToString(); - jstring jstr = env->NewStringUTF(dstr.c_str()); - env->SetObjectArrayElement(varlen_data, row_idx, jstr); - env->DeleteLocalRef(jstr); - } - break; - case LogicalTypeId::UNION: - case LogicalTypeId::STRUCT: - case LogicalTypeId::TUPLE: { - varlen_data = env->NewObjectArray(row_count, J_DuckStruct, nullptr); - - auto &entries = StructVector::GetEntries(vec); - auto columns = env->NewObjectArray(entries.size(), J_DuckVector, nullptr); - auto names = env->NewObjectArray(entries.size(), J_String, nullptr); - - for (idx_t entry_i = 0; entry_i < entries.size(); entry_i++) { - jobject j_vec = ProcessVector(env, conn_ref, entries[entry_i], row_count); - env->SetObjectArrayElement(columns, entry_i, j_vec); - env->DeleteLocalRef(j_vec); - // TUPLE members are unnamed, use the positional names synthesized by DuckDB: "element1", "element2", ... - auto &child_name = StructType::GetChildName(vec.GetType(), entry_i); - std::string name = child_name.empty() ? TupleType::GetChildName(entry_i) : child_name.GetIdentifierName(); - jstring jstr = env->NewStringUTF(name.c_str()); - env->SetObjectArrayElement(names, entry_i, jstr); - env->DeleteLocalRef(jstr); - } - for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { - jstring jstr = env->NewStringUTF(vec.GetType().ToString().c_str()); - jobject jstruct = env->NewObject(J_DuckStruct, J_DuckStruct_init, names, columns, row_idx, jstr); - env->SetObjectArrayElement(varlen_data, row_idx, jstruct); - env->DeleteLocalRef(jstruct); - env->DeleteLocalRef(jstr); - } - env->DeleteLocalRef(names); - env->DeleteLocalRef(columns); - - break; - } - case LogicalTypeId::BLOB: - case LogicalTypeId::GEOMETRY: - varlen_data = env->NewObjectArray(row_count, J_ByteArray, nullptr); - - for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { - if (FlatVector::IsNull(vec, row_idx)) { - continue; - } - - const string_t *vec_data = FlatVector::GetData(vec); - const string_t d_str = vec_data[row_idx]; - - auto j_arr = env->NewByteArray(d_str.GetSize()); - auto j_arr_el = env->GetByteArrayElements(j_arr, nullptr); - memcpy(j_arr_el, d_str.GetData(), d_str.GetSize()); - env->ReleaseByteArrayElements(j_arr, j_arr_el, 0); - - env->SetObjectArrayElement(varlen_data, row_idx, j_arr); - env->DeleteLocalRef(j_arr); - } - break; - case LogicalTypeId::UUID: - constlen_data = make_vec_data_buf(env, vec, row_count); - break; - case LogicalTypeId::ARRAY: { - varlen_data = env->NewObjectArray(row_count, J_DuckArray, nullptr); - auto &array_vector = ArrayVector::GetChildMutable(vec); - auto total_size = row_count * ArrayType::GetSize(vec.GetType()); - jobject j_vec = ProcessVector(env, conn_ref, array_vector, total_size); - - auto limit = ArrayType::GetSize(vec.GetType()); - - for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { - if (FlatVector::IsNull(vec, row_idx)) { - continue; - } - - auto offset = row_idx * limit; - - auto j_obj = env->NewObject(J_DuckArray, J_DuckArray_init, j_vec, offset, limit); - - env->SetObjectArrayElement(varlen_data, row_idx, j_obj); - env->DeleteLocalRef(j_obj); - } - env->DeleteLocalRef(j_vec); - break; - } - case LogicalTypeId::MAP: - case LogicalTypeId::LIST: { - varlen_data = env->NewObjectArray(row_count, J_DuckArray, nullptr); - - auto list_entries = FlatVector::GetData(vec); - - auto list_size = ListVector::GetListSize(vec); - auto &list_vector = ListVector::GetChildMutable(vec); - auto j_vec = ProcessVector(env, conn_ref, list_vector, list_size); - - for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { - if (FlatVector::IsNull(vec, row_idx)) { - continue; - } - - auto offset = list_entries[row_idx].offset; - auto limit = list_entries[row_idx].length; - - auto j_obj = env->NewObject(J_DuckArray, J_DuckArray_init, j_vec, offset, limit); - - env->SetObjectArrayElement(varlen_data, row_idx, j_obj); - env->DeleteLocalRef(j_obj); - } - env->DeleteLocalRef(j_vec); - break; - } - case LogicalTypeId::VARIANT: { - RecursiveUnifiedVectorFormat format; - Vector::RecursiveToUnifiedFormat(vec, format); - UnifiedVariantVectorData vector_data(format); - varlen_data = env->NewObjectArray(row_count, J_Object, nullptr); - for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { - auto variant_val = VariantUtils::ConvertVariantToValue(vector_data, row_idx, 0); - if (variant_val.IsNull()) { - continue; - } - Vector variant_vec(variant_val.type()); - variant_vec.SetValue(0, variant_val); - jobject variant_j_vec = ProcessVector(env, conn_ref, variant_vec, 1); - env->CallVoidMethod(variant_j_vec, J_DuckVector_retainConstlenData); - check_java_exception_and_rethrow(env); - env->SetObjectArrayElement(varlen_data, row_idx, variant_j_vec); - env->DeleteLocalRef(variant_j_vec); - } - break; - } - default: { - // the source vector must not be modified, it is a part of the result chunk that can be cast again - // in getString() (with this vector as a child of a nested type) - cast_vec = make_uniq(LogicalType::VARCHAR); - VectorOperations::Cast(*conn_ref->context, vec, *cast_vec, row_count); - if (cast_vec->GetVectorType() != VectorType::FLAT_VECTOR) { - cast_vec->Flatten(); - } - string_vec = cast_vec.get(); - // fall through on purpose - } - case LogicalTypeId::VARCHAR: - varlen_data = env->NewObjectArray(row_count, J_String, nullptr); - for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { - if (FlatVector::IsNull(*string_vec, row_idx)) { - continue; - } - const string_t *vec_data = FlatVector::GetData(*string_vec); - const string_t d_str = vec_data[row_idx]; - auto j_str = decode_charbuffer_to_jstring(env, d_str.GetData(), d_str.GetSize()); - env->SetObjectArrayElement(varlen_data, row_idx, j_str); - env->DeleteLocalRef(j_str); - } - break; - } - - env->SetObjectField(jvec, J_DuckVector_constlen, constlen_data); - if (constlen_data != nullptr) { - env->DeleteLocalRef(constlen_data); - } - env->SetObjectField(jvec, J_DuckVector_varlen, varlen_data); - if (varlen_data != nullptr) { - env->DeleteLocalRef(varlen_data); - } - - env->DeleteLocalRef(null_array); - env->DeleteLocalRef(type_str); - - return jvec; -} - jint _duckdb_jdbc_fetch_size(JNIEnv *, jclass) { return STANDARD_VECTOR_SIZE; } @@ -1085,27 +297,6 @@ void _duckdb_jdbc_appender_append_null(JNIEnv *env, jclass, jobject appender_ref get_appender(env, appender_ref_buf)->Append(nullptr); } -jlong _duckdb_jdbc_arrow_stream(JNIEnv *env, jclass, jobject res_ref_buf, jobject conn_ref_buf, jlong batch_size) { - if (!res_ref_buf) { - throw InvalidInputException("Invalid result set"); - } - auto res_ref = reinterpret_cast(env->GetDirectBufferAddress(res_ref_buf)); - if (!res_ref || (!res_ref->res && !res_ref->stream) || (res_ref->res && res_ref->res->HasError()) || - (res_ref->stream && res_ref->stream->HasError())) { - throw InvalidInputException("Invalid result set"); - } - if (batch_size <= 0) { - throw InvalidInputException("Arrow batch size must be greater than 0"); - } - auto conn_holder = get_connection_ref(env, conn_ref_buf); - - auto state = make_shared_ptr(std::move(res_ref->res), std::move(res_ref->stream), - static_cast(batch_size)); - res_ref->chunk = nullptr; - conn_holder->track_arrow_stream(state); - return reinterpret_cast(JavaResultArrowStream::Export(std::move(state))); -} - class JavaArrowScanFactory : public ArrowScanFactory { public: explicit JavaArrowScanFactory(duckdb::shared_ptr state_p) : state(std::move(state_p)) { diff --git a/src/jni/functions.cpp b/src/jni/functions.cpp index 564f6c252..6f9aa4a88 100644 --- a/src/jni/functions.cpp +++ b/src/jni/functions.cpp @@ -131,135 +131,6 @@ JNIEXPORT jstring JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1catalo } } -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1prepare(JNIEnv * env, jclass param0, jobject param1, jbyteArray param2) { - try { - return _duckdb_jdbc_prepare(env, param0, param1, param2); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - return nullptr; - } -} - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1pending_1query(JNIEnv * env, jclass param0, jobject param1, jbyteArray param2) { - try { - return _duckdb_jdbc_pending_query(env, param0, param1, param2); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - return nullptr; - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1release(JNIEnv * env, jclass param0, jobject param1) { - try { - return _duckdb_jdbc_release(env, param0, param1); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1release_1pending(JNIEnv * env, jclass param0, jobject param1) { - try { - _duckdb_jdbc_release_pending(env, param0, param1); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1query_1result_1meta(JNIEnv * env, jclass param0, jobject param1) { - try { - return _duckdb_jdbc_query_result_meta(env, param0, param1); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - return nullptr; - } -} - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1prepared_1statement_1meta(JNIEnv * env, jclass param0, jobject param1) { - try { - return _duckdb_jdbc_prepared_statement_meta(env, param0, param1); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - return nullptr; - } -} - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1execute(JNIEnv * env, jclass param0, jobject param1, jobjectArray param2) { - try { - return _duckdb_jdbc_execute(env, param0, param1, param2); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - return nullptr; - } -} - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1execute_1capi(JNIEnv * env, jclass param0, jobject param1, jobjectArray param2) { - try { - return _duckdb_jdbc_execute_capi(env, param0, param1, param2); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - return nullptr; - } -} - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1execute_1pending(JNIEnv * env, jclass param0, jobject param1) { - try { - return _duckdb_jdbc_execute_pending(env, param0, param1); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - return nullptr; - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1free_1result(JNIEnv * env, jclass param0, jobject param1) { - try { - return _duckdb_jdbc_free_result(env, param0, param1); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT jobjectArray JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1fetch(JNIEnv * env, jclass param0, jobject param1, jobject param2) { - try { - return _duckdb_jdbc_fetch(env, param0, param1, param2); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - return nullptr; - } -} - -JNIEXPORT jobjectArray JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1cast_1result_1to_1strings(JNIEnv * env, jclass param0, jobject param1, jobject param2, jlong param3) { - try { - return _duckdb_jdbc_cast_result_to_strings(env, param0, param1, param2, param3); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - return nullptr; - } -} - JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1fetch_1size(JNIEnv * env, jclass param0) { try { return _duckdb_jdbc_fetch_size(env, param0); @@ -271,17 +142,6 @@ JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1fetch_1size(JN } } -JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1stream(JNIEnv * env, jclass param0, jobject param1, jobject param2, jlong param3) { - try { - return _duckdb_jdbc_arrow_stream(env, param0, param1, param2, param3); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - return -1; - } -} - JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1register(JNIEnv * env, jclass param0, jobject param1, jlong param2, jbyteArray param3) { try { return _duckdb_jdbc_arrow_register(env, param0, param1, param2, param3); @@ -343,26 +203,6 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1flus } } -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1interrupt(JNIEnv * env, jclass param0, jobject param1) { - try { - return _duckdb_jdbc_interrupt(env, param0, param1); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1query_1progress(JNIEnv * env, jclass param0, jobject param1) { - try { - return _duckdb_jdbc_query_progress(env, param0, param1); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - return nullptr; - } -} - JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1close(JNIEnv * env, jclass param0, jobject param1) { try { return _duckdb_jdbc_appender_close(env, param0, param1); diff --git a/src/jni/functions.hpp b/src/jni/functions.hpp index c7f72177b..15a96e1fd 100644 --- a/src/jni/functions.hpp +++ b/src/jni/functions.hpp @@ -57,62 +57,10 @@ jstring _duckdb_jdbc_get_catalog(JNIEnv * env, jclass param0, jobject param1); JNIEXPORT jstring JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1catalog(JNIEnv * env, jclass param0, jobject param1); -jobject _duckdb_jdbc_prepare(JNIEnv * env, jclass param0, jobject param1, jbyteArray param2); - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1prepare(JNIEnv * env, jclass param0, jobject param1, jbyteArray param2); - -jobject _duckdb_jdbc_pending_query(JNIEnv * env, jclass param0, jobject param1, jbyteArray param2); - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1pending_1query(JNIEnv * env, jclass param0, jobject param1, jbyteArray param2); - -void _duckdb_jdbc_release(JNIEnv * env, jclass param0, jobject param1); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1release(JNIEnv * env, jclass param0, jobject param1); - -void _duckdb_jdbc_release_pending(JNIEnv * env, jclass param0, jobject param1); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1release_1pending(JNIEnv * env, jclass param0, jobject param1); - -jobject _duckdb_jdbc_query_result_meta(JNIEnv * env, jclass param0, jobject param1); - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1query_1result_1meta(JNIEnv * env, jclass param0, jobject param1); - -jobject _duckdb_jdbc_prepared_statement_meta(JNIEnv * env, jclass param0, jobject param1); - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1prepared_1statement_1meta(JNIEnv * env, jclass param0, jobject param1); - -jobject _duckdb_jdbc_execute(JNIEnv * env, jclass param0, jobject param1, jobjectArray param2); - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1execute(JNIEnv * env, jclass param0, jobject param1, jobjectArray param2); - -jobject _duckdb_jdbc_execute_capi(JNIEnv * env, jclass param0, jobject param1, jobjectArray param2); - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1execute_1capi(JNIEnv * env, jclass param0, jobject param1, jobjectArray param2); - -jobject _duckdb_jdbc_execute_pending(JNIEnv * env, jclass param0, jobject param1); - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1execute_1pending(JNIEnv * env, jclass param0, jobject param1); - -void _duckdb_jdbc_free_result(JNIEnv * env, jclass param0, jobject param1); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1free_1result(JNIEnv * env, jclass param0, jobject param1); - -jobjectArray _duckdb_jdbc_fetch(JNIEnv * env, jclass param0, jobject param1, jobject param2); - -JNIEXPORT jobjectArray JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1fetch(JNIEnv * env, jclass param0, jobject param1, jobject param2); - -jobjectArray _duckdb_jdbc_cast_result_to_strings(JNIEnv * env, jclass param0, jobject param1, jobject param2, jlong param3); - -JNIEXPORT jobjectArray JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1cast_1result_1to_1strings(JNIEnv * env, jclass param0, jobject param1, jobject param2, jlong param3); - jint _duckdb_jdbc_fetch_size(JNIEnv * env, jclass param0); JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1fetch_1size(JNIEnv * env, jclass param0); -jlong _duckdb_jdbc_arrow_stream(JNIEnv * env, jclass param0, jobject param1, jobject param2, jlong param3); - -JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1stream(JNIEnv * env, jclass param0, jobject param1, jobject param2, jlong param3); - void _duckdb_jdbc_arrow_register(JNIEnv * env, jclass param0, jobject param1, jlong param2, jbyteArray param3); JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1register(JNIEnv * env, jclass param0, jobject param1, jlong param2, jbyteArray param3); @@ -137,14 +85,6 @@ void _duckdb_jdbc_appender_flush(JNIEnv * env, jclass param0, jobject param1); JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1flush(JNIEnv * env, jclass param0, jobject param1); -void _duckdb_jdbc_interrupt(JNIEnv * env, jclass param0, jobject param1); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1interrupt(JNIEnv * env, jclass param0, jobject param1); - -jobject _duckdb_jdbc_query_progress(JNIEnv * env, jclass param0, jobject param1); - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1query_1progress(JNIEnv * env, jclass param0, jobject param1); - void _duckdb_jdbc_appender_close(JNIEnv * env, jclass param0, jobject param1); JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1close(JNIEnv * env, jclass param0, jobject param1); diff --git a/src/main/java/org/duckdb/DuckDBConnection.java b/src/main/java/org/duckdb/DuckDBConnection.java index 2934c609f..8f88b2261 100644 --- a/src/main/java/org/duckdb/DuckDBConnection.java +++ b/src/main/java/org/duckdb/DuckDBConnection.java @@ -24,6 +24,7 @@ import java.sql.Struct; import java.util.*; import java.util.concurrent.Executor; +import java.util.concurrent.Semaphore; import java.util.concurrent.locks.ReentrantLock; import org.duckdb.user.DuckDBMap; import org.duckdb.user.DuckDBUserArray; @@ -38,6 +39,8 @@ public final class DuckDBConnection implements java.sql.Connection { final ReentrantLock connRefLock = new ReentrantLock(); final LinkedHashSet pendingQueries = new LinkedHashSet<>(); final LinkedHashSet preparedStatements = new LinkedHashSet<>(); + // The connection has one live result at a time, the queries are run one by one + final Semaphore queryGate = new Semaphore(1); final LinkedHashSet appenders = new LinkedHashSet<>(); volatile boolean closing; diff --git a/src/main/java/org/duckdb/DuckDBCore.java b/src/main/java/org/duckdb/DuckDBCore.java new file mode 100644 index 000000000..446517988 --- /dev/null +++ b/src/main/java/org/duckdb/DuckDBCore.java @@ -0,0 +1,1121 @@ +package org.duckdb; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.duckdb.DuckDBBindings.*; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.sql.SQLException; +import java.sql.Struct; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.duckdb.user.DuckDBMap; + +/** + * The logic of the driver that works on top of the C API v2 entry points of {@link DuckDBBindings}: preparing, + * executing, reading the results and converting the parameters. + */ +final class DuckDBCore { + private DuckDBCore() { + } + + private static final ByteOrder NATIVE_ORDER = ByteOrder.nativeOrder(); + + // type IDs of the C API + private static final int TYPE_BOOLEAN = 1; + private static final int TYPE_TINYINT = 2; + private static final int TYPE_SMALLINT = 3; + private static final int TYPE_INTEGER = 4; + private static final int TYPE_BIGINT = 5; + private static final int TYPE_UTINYINT = 6; + private static final int TYPE_USMALLINT = 7; + private static final int TYPE_UINTEGER = 8; + private static final int TYPE_UBIGINT = 9; + private static final int TYPE_FLOAT = 10; + private static final int TYPE_DOUBLE = 11; + private static final int TYPE_TIMESTAMP = 12; + private static final int TYPE_DATE = 13; + private static final int TYPE_TIME = 14; + private static final int TYPE_INTERVAL = 15; + private static final int TYPE_HUGEINT = 16; + private static final int TYPE_VARCHAR = 17; + private static final int TYPE_BLOB = 18; + private static final int TYPE_DECIMAL = 19; + private static final int TYPE_TIMESTAMP_S = 20; + private static final int TYPE_TIMESTAMP_MS = 21; + private static final int TYPE_TIMESTAMP_NS = 22; + private static final int TYPE_ENUM = 23; + private static final int TYPE_LIST = 24; + private static final int TYPE_STRUCT = 25; + private static final int TYPE_MAP = 26; + private static final int TYPE_UUID = 27; + private static final int TYPE_UNION = 28; + private static final int TYPE_BIT = 29; + private static final int TYPE_TIME_TZ = 30; + private static final int TYPE_TIMESTAMP_TZ = 31; + private static final int TYPE_UHUGEINT = 32; + private static final int TYPE_ARRAY = 33; + private static final int TYPE_TIME_NS = 39; + private static final int TYPE_GEOMETRY = 40; + private static final int TYPE_VARIANT = 41; + + // DUCKDB_V2_STATEMENT_TYPE + private static final int STATEMENT_SELECT = 1; + private static final int STATEMENT_INSERT = 2; + private static final int STATEMENT_UPDATE = 3; + private static final int STATEMENT_DELETE = 5; + private static final int STATEMENT_COPY = 10; + private static final int STATEMENT_MERGE_INTO = 30; + + private static final byte[] STREAM_RESULTS_OPTION = "jdbc_stream_results".getBytes(UTF_8); + + /** A prepared statement. */ + static final class StatementRef { + final DuckDBConnection conn; + final int statementType; + final long parameterCount; + ByteBuffer prepared; + ByteBuffer outputSchema; + ByteBuffer parametersSchema; + + StatementRef(DuckDBConnection conn, int statementType, ByteBuffer prepared, ByteBuffer outputSchema, + ByteBuffer parametersSchema, long parameterCount) { + this.conn = conn; + this.statementType = statementType; + this.prepared = prepared; + this.outputSchema = outputSchema; + this.parametersSchema = parametersSchema; + this.parameterCount = parameterCount; + } + } + + /** A query that is submitted but is not completed yet. */ + static final class PendingRef { + final DuckDBConnection conn; + final int statementType; + final boolean streaming; + ByteBuffer result; + + PendingRef(DuckDBConnection conn, int statementType, boolean streaming, ByteBuffer result) { + this.conn = conn; + this.statementType = statementType; + this.streaming = streaming; + this.result = result; + } + } + + /** + * A query result, that is either streamed from the query or is read into the memory when the query is + * completed. + */ + static final class ResultRef { + final ByteBuffer connRef; + final int resultType; + final String[] names; + // the result that is streamed, null if the result is in the memory + ByteBuffer streamResult; + // the chunks that are read but are not consumed yet + final ArrayDeque chunks = new ArrayDeque<>(); + // the chunk that is being consumed, it keeps the memory of the vectors of the fetched DuckDBVector-s + ByteBuffer currentChunk; + ByteBuffer schema; + + ResultRef(ByteBuffer connRef, ByteBuffer streamResult, ByteBuffer schema, int resultType, String[] names) { + this.connRef = connRef; + this.streamResult = streamResult; + this.schema = schema; + this.resultType = resultType; + this.names = names; + } + } + + private static SQLException invalid(String message) { + return new SQLException("Invalid Input Error: " + message); + } + + private static ByteBuffer conn(ByteBuffer connRef) throws SQLException { + if (connRef == null) { + throw invalid("Invalid connection"); + } + return duckdb_v2_connection_from_ref(connRef); + } + + private static long fieldCount(ByteBuffer schema) throws SQLException { + return schema == null ? 0 : duckdb_v2_schema_get_count(schema); + } + + private static boolean streamResultsOption(ByteBuffer conn) { + try { + ByteBuffer config = duckdb_v2_connection_get_config(conn); + ByteBuffer value = duckdb_v2_config_get_option_value(config, STREAM_RESULTS_OPTION); + try { + return duckdb_get_bool(value); + } finally { + duckdb_v2_value_destroy(value); + } + } catch (SQLException e) { + return false; + } + } + + // --------------------------------------------------------------------------------------------------------- + // Statements + // --------------------------------------------------------------------------------------------------------- + + private static void destroyStatements(List statements) { + for (ByteBuffer statement : statements) { + try { + duckdb_v2_sql_statement_destroy(statement); + } catch (SQLException e) { + // ignore + } + } + } + + private static List parse(ByteBuffer conn, byte[] query) throws SQLException { + ByteBuffer iterator = duckdb_v2_parse_sql(conn, query); + List statements = new ArrayList<>(); + try { + while (true) { + ByteBuffer statement = duckdb_v2_statement_iterator_next(iterator); + if (statement == null) { + break; + } + statements.add(statement); + } + } catch (SQLException e) { + destroyStatements(statements); + throw e; + } finally { + duckdb_v2_statement_iterator_destroy(iterator); + } + return statements; + } + + /** + * Parses the query and returns its last statement, the other statements are destroyed. The statements before + * the last one are executed unless the query is prepared: preparing must not have side effects, so a query with + * multiple statements is rejected then. + */ + private static ByteBuffer extractLastStatement(ByteBuffer conn, byte[] query, boolean isPrepare) + throws SQLException { + List statements = parse(conn, query); + try { + if (statements.isEmpty()) { + throw invalid("No statements to execute."); + } + if (isPrepare && statements.size() > 1) { + throw invalid("Cannot prepare multiple statements at once, statements count: " + statements.size()); + } + // if there are multiple statements, we directly execute the statements besides the last one, + // we only return the result of the last statement to the user, unless one of the previous statements fails + for (int i = 0; i + 1 < statements.size(); i++) { + ByteBuffer result = duckdb_v2_statement_execute(conn, statements.get(i), null); + try { + duckdb_v2_result_drain(result); + } finally { + duckdb_v2_result_destroy(result); + } + } + return statements.remove(statements.size() - 1); + } finally { + destroyStatements(statements); + } + } + + static StatementRef prepare(DuckDBConnection connection, byte[] query) throws SQLException { + connection.queryGate.acquireUninterruptibly(); + try { + return prepareLocked(connection, query); + } finally { + connection.queryGate.release(); + } + } + + private static StatementRef prepareLocked(DuckDBConnection connection, byte[] query) throws SQLException { + ByteBuffer conn = conn(connection.connRef); + ByteBuffer statement = extractLastStatement(conn, query, true); + ByteBuffer prepared = null; + ByteBuffer[] schemas = null; + try { + int statementType = duckdb_v2_sql_statement_get_type(statement); + prepared = duckdb_v2_prepared_statement_create(conn, statement, false); + schemas = duckdb_v2_statement_bind(conn, statement); + long parameterCount = fieldCount(schemas[1]); + StatementRef ref = + new StatementRef(connection, statementType, prepared, schemas[0], schemas[1], parameterCount); + prepared = null; + schemas = null; + return ref; + } finally { + if (prepared != null) { + duckdb_v2_prepared_statement_destroy(prepared); + } + if (schemas != null) { + duckdb_v2_schema_destroy(schemas[0]); + if (schemas[1] != null) { + duckdb_v2_schema_destroy(schemas[1]); + } + } + duckdb_v2_sql_statement_destroy(statement); + } + } + + static void release(StatementRef ref) throws SQLException { + if (ref == null || ref.prepared == null) { + return; + } + ByteBuffer prepared = ref.prepared; + ref.prepared = null; + try { + duckdb_v2_prepared_statement_destroy(prepared); + } finally { + if (ref.outputSchema != null) { + duckdb_v2_schema_destroy(ref.outputSchema); + ref.outputSchema = null; + } + if (ref.parametersSchema != null) { + duckdb_v2_schema_destroy(ref.parametersSchema); + ref.parametersSchema = null; + } + } + } + + // The query gate of the connection is held until the pending query is executed or released + static PendingRef pendingQuery(DuckDBConnection connection, byte[] query) throws SQLException { + connection.queryGate.acquireUninterruptibly(); + boolean ok = false; + try { + ByteBuffer conn = conn(connection.connRef); + ByteBuffer statement = extractLastStatement(conn, query, false); + try { + int statementType = duckdb_v2_sql_statement_get_type(statement); + boolean streaming = streamResultsOption(conn); + ByteBuffer result = duckdb_v2_statement_execute(conn, statement, null); + PendingRef ref = new PendingRef(connection, statementType, streaming, result); + ok = true; + return ref; + } finally { + duckdb_v2_sql_statement_destroy(statement); + } + } finally { + if (!ok) { + connection.queryGate.release(); + } + } + } + + static void releasePending(PendingRef ref) throws SQLException { + if (ref == null || ref.result == null) { + return; + } + ByteBuffer result = ref.result; + ref.result = null; + try { + duckdb_v2_result_destroy(result); + } finally { + ref.conn.queryGate.release(); + } + } + + static ResultRef executePending(PendingRef ref) throws SQLException { + if (ref == null || ref.result == null) { + throw invalid("Invalid pending query"); + } + ByteBuffer result = ref.result; + ref.result = null; + try { + // the pending result was submitted from the SQL statement as written, so its type is the written type + return completeResult(ref.conn.connRef, result, ref.statementType, ref.streaming); + } finally { + ref.conn.queryGate.release(); + } + } + + // --------------------------------------------------------------------------------------------------------- + // Execution + // --------------------------------------------------------------------------------------------------------- + + private static StatementRef checkStatement(StatementRef ref) throws SQLException { + if (ref == null || ref.prepared == null) { + throw invalid("Invalid statement"); + } + return ref; + } + + private static ByteBuffer executePrepared(StatementRef ref, Object[] params) throws SQLException { + checkStatement(ref); + ByteBuffer conn = conn(ref.conn.connRef); + int paramLen = params == null ? 0 : params.length; + if (paramLen != ref.parameterCount) { + throw invalid("Parameter count mismatch"); + } + ByteBuffer factory = duckdb_v2_connection_get_factory(conn); + ByteBuffer[] values = new ByteBuffer[paramLen]; + try { + for (int i = 0; i < paramLen; i++) { + values[i] = toValue(factory, params[i]); + } + return duckdb_v2_prepared_statement_execute(ref.prepared, values); + } finally { + for (ByteBuffer value : values) { + if (value != null) { + duckdb_v2_value_destroy(value); + } + } + } + } + + static ResultRef execute(StatementRef ref, Object[] params) throws SQLException { + checkStatement(ref); + ref.conn.queryGate.acquireUninterruptibly(); + try { + boolean streamResults = streamResultsOption(conn(ref.conn.connRef)); + ByteBuffer result = executePrepared(ref, params); + return completeResult(ref.conn.connRef, result, ref.statementType, streamResults); + } finally { + ref.conn.queryGate.release(); + } + } + + static ByteBuffer executeChunked(StatementRef ref, Object[] params) throws SQLException { + checkStatement(ref); + ref.conn.queryGate.acquireUninterruptibly(); + try { + ByteBuffer result = executePrepared(ref, params); + return duckdb_v2_chunked_result_create(result); + } finally { + ref.conn.queryGate.release(); + } + } + + // Streaming is only used for the SELECT statements + private static boolean streamsByDefault(int writtenType, int resultType) { + return writtenType == STATEMENT_SELECT && resultType == RESULT_TYPE_QUERY_RESULT; + } + + /** + * Completes the execution of the result: the rows are read into the memory, or the result is kept to be streamed. + * The result is owned by the returned reference (or is destroyed on failure). + */ + private static ResultRef completeResult(ByteBuffer connRef, ByteBuffer result, int writtenType, + boolean streamResultsUser) throws SQLException { + ByteBuffer firstChunk = null; + ByteBuffer schema = null; + ResultRef ref = null; + try { + // the first chunk is read to find out if the query is running without errors + firstChunk = duckdb_v2_result_fetch_chunk(result); + schema = duckdb_v2_result_get_schema(result); + int resultType = duckdb_v2_result_get_result_type(result); + long count = fieldCount(schema); + String[] names = new String[(int) count]; + for (int i = 0; i < count; i++) { + names[i] = new String(duckdb_v2_schema_get_field_name(schema, i), UTF_8); + } + boolean stream = streamResultsUser && streamsByDefault(writtenType, resultType); + ref = new ResultRef(connRef, stream ? result : null, schema, resultType, names); + // the reference owns the schema and the streamed result now + schema = null; + ByteBuffer ownedResult = result; + if (stream) { + result = null; + } + if (firstChunk != null) { + ref.chunks.add(firstChunk); + firstChunk = null; + } + if (!stream) { + ByteBuffer chunk; + while ((chunk = duckdb_v2_result_fetch_chunk(ownedResult)) != null) { + ref.chunks.add(chunk); + } + } + ResultRef res = ref; + ref = null; + return res; + } finally { + if (ref != null) { + freeResult(ref); + } + if (firstChunk != null) { + duckdb_destroy_data_chunk(firstChunk); + } + if (schema != null) { + duckdb_v2_schema_destroy(schema); + } + if (result != null) { + duckdb_v2_result_destroy(result); + } + } + } + + static void freeResult(ResultRef ref) throws SQLException { + if (ref == null) { + return; + } + if (ref.currentChunk != null) { + duckdb_destroy_data_chunk(ref.currentChunk); + ref.currentChunk = null; + } + ByteBuffer chunk; + while ((chunk = ref.chunks.poll()) != null) { + duckdb_destroy_data_chunk(chunk); + } + if (ref.streamResult != null) { + ByteBuffer result = ref.streamResult; + ref.streamResult = null; + duckdb_v2_result_destroy(result); + } + if (ref.schema != null) { + ByteBuffer schema = ref.schema; + ref.schema = null; + duckdb_v2_schema_destroy(schema); + } + } + + // --------------------------------------------------------------------------------------------------------- + // Metadata + // --------------------------------------------------------------------------------------------------------- + + private static String returnTypeName(int resultType) { + switch (resultType) { + case RESULT_TYPE_QUERY_RESULT: + return "QUERY_RESULT"; + case RESULT_TYPE_CHANGED_ROWS: + return "CHANGED_ROWS"; + default: + return "NOTHING"; + } + } + + // The return type of a prepared statement is not known before it is executed, it is derived from its columns + private static String preparedReturnType(StatementRef ref) throws SQLException { + long count = fieldCount(ref.outputSchema); + if (count == 0) { + return "NOTHING"; + } + if (count == 1 && "Count".equals(new String(duckdb_v2_schema_get_field_name(ref.outputSchema, 0), UTF_8)) && + duckdb_get_type_id(duckdb_v2_schema_get_field_type(ref.outputSchema, 0)) == TYPE_BIGINT) { + switch (ref.statementType) { + case STATEMENT_INSERT: + case STATEMENT_UPDATE: + case STATEMENT_DELETE: + case STATEMENT_COPY: + case STATEMENT_MERGE_INTO: + return "CHANGED_ROWS"; + default: + break; + } + } + return "QUERY_RESULT"; + } + + // The text of the type, the same as the one the SQL shows + private static String typeText(ByteBuffer factory, ByteBuffer type) throws SQLException { + if (duckdb_get_type_id(type) == TYPE_ENUM) { + return "ENUM"; + } + ByteBuffer value = duckdb_v2_value_create_type(factory, type); + try { + return new String(duckdb_v2_value_to_string(value), UTF_8); + } finally { + duckdb_v2_value_destroy(value); + } + } + + // The name of the type for the Java side, DECIMAL types also have the width and the scale + private static String typeDetail(ByteBuffer factory, ByteBuffer type) throws SQLException { + int id = duckdb_get_type_id(type); + switch (id) { + case TYPE_DECIMAL: { + String physical; + switch (duckdb_decimal_internal_type(type)) { + case TYPE_SMALLINT: + physical = "DECIMAL16"; + break; + case TYPE_INTEGER: + physical = "DECIMAL32"; + break; + case TYPE_BIGINT: + physical = "DECIMAL64"; + break; + default: + physical = "DECIMAL128"; + break; + } + return physical + ";" + duckdb_decimal_width(type) + ";" + duckdb_decimal_scale(type); + } + case TYPE_BOOLEAN: + return "BOOLEAN"; + case TYPE_TINYINT: + return "TINYINT"; + case TYPE_SMALLINT: + return "SMALLINT"; + case TYPE_INTEGER: + return "INTEGER"; + case TYPE_BIGINT: + return "BIGINT"; + case TYPE_UTINYINT: + return "UTINYINT"; + case TYPE_USMALLINT: + return "USMALLINT"; + case TYPE_UINTEGER: + return "UINTEGER"; + case TYPE_UBIGINT: + return "UBIGINT"; + case TYPE_HUGEINT: + return "HUGEINT"; + case TYPE_UHUGEINT: + return "UHUGEINT"; + case TYPE_FLOAT: + return "FLOAT"; + case TYPE_DOUBLE: + return "DOUBLE"; + case TYPE_TIMESTAMP: + return "TIMESTAMP"; + case TYPE_TIMESTAMP_S: + return "TIMESTAMP_S"; + case TYPE_TIMESTAMP_MS: + return "TIMESTAMP_MS"; + case TYPE_TIMESTAMP_NS: + return "TIMESTAMP_NS"; + case TYPE_TIMESTAMP_TZ: + return "TIMESTAMP WITH TIME ZONE"; + case TYPE_DATE: + return "DATE"; + case TYPE_TIME: + return "TIME"; + case TYPE_TIME_NS: + return "TIME_NS"; + case TYPE_TIME_TZ: + return "TIME WITH TIME ZONE"; + case TYPE_VARCHAR: + // JSON requires special handling because it is mapped to JsonNode class + return "JSON".equals(typeText(factory, type)) ? "JSON" : "VARCHAR"; + case TYPE_BLOB: + return "BLOB"; + case TYPE_UUID: + return "UUID"; + case TYPE_ENUM: + return "ENUM"; + case TYPE_LIST: + return "LIST"; + case TYPE_STRUCT: + return "STRUCT"; + case TYPE_MAP: + return "MAP"; + case TYPE_UNION: + return "UNION"; + case TYPE_ARRAY: + return "ARRAY"; + case TYPE_GEOMETRY: + return "GEOMETRY"; + case TYPE_VARIANT: + return "VARIANT"; + case TYPE_INTERVAL: + return "INTERVAL"; + case TYPE_BIT: + return "BIT"; + default: + return "UNKNOWN"; + } + } + + private static DuckDBResultSetMetaData buildMeta(ByteBuffer factory, String[] names, ByteBuffer schema, + ByteBuffer parametersSchema, String returnType) + throws SQLException { + int columnCount = names.length; + String[] typeNames = new String[columnCount]; + String[] typeDetails = new String[columnCount]; + for (int i = 0; i < columnCount; i++) { + ByteBuffer type = duckdb_v2_schema_get_field_type(schema, i); + typeNames[i] = typeText(factory, type); + typeDetails[i] = typeDetail(factory, type); + } + int paramCount = (int) fieldCount(parametersSchema); + String[] paramTypeNames = new String[paramCount]; + String[] paramTypeDetails = new String[paramCount]; + for (int i = 0; i < paramCount; i++) { + ByteBuffer type = duckdb_v2_schema_get_field_type(parametersSchema, i); + paramTypeNames[i] = typeText(factory, type); + paramTypeDetails[i] = typeDetail(factory, type); + } + return new DuckDBResultSetMetaData(paramCount, columnCount, names, typeNames, typeDetails, returnType, + paramTypeNames, paramTypeDetails); + } + + static DuckDBResultSetMetaData queryResultMeta(ResultRef ref) throws SQLException { + if (ref == null || ref.schema == null) { + throw invalid("Invalid result set"); + } + ByteBuffer factory = duckdb_v2_connection_get_factory(conn(ref.connRef)); + return buildMeta(factory, ref.names, ref.schema, null, returnTypeName(ref.resultType)); + } + + static DuckDBResultSetMetaData preparedStatementMeta(StatementRef ref) throws SQLException { + checkStatement(ref); + ByteBuffer factory = duckdb_v2_connection_get_factory(conn(ref.conn.connRef)); + int count = (int) fieldCount(ref.outputSchema); + String[] names = new String[count]; + for (int i = 0; i < count; i++) { + names[i] = new String(duckdb_v2_schema_get_field_name(ref.outputSchema, i), UTF_8); + } + return buildMeta(factory, names, ref.outputSchema, ref.parametersSchema, preparedReturnType(ref)); + } + + // --------------------------------------------------------------------------------------------------------- + // Fetching + // --------------------------------------------------------------------------------------------------------- + + static DuckDBVector[] fetch(ResultRef ref) throws SQLException { + if (ref == null || ref.schema == null) { + throw invalid("Invalid result set"); + } + ByteBuffer connHandle = conn(ref.connRef); + if (ref.currentChunk != null) { + duckdb_destroy_data_chunk(ref.currentChunk); + ref.currentChunk = null; + } + ByteBuffer chunk = ref.chunks.poll(); + if (chunk == null && ref.streamResult != null) { + chunk = duckdb_v2_result_fetch_chunk(ref.streamResult); + } + if (chunk == null) { + return new DuckDBVector[0]; + } + ref.currentChunk = chunk; + int rowCount = (int) duckdb_data_chunk_get_size(chunk); + int columnCount = (int) duckdb_data_chunk_get_column_count(chunk); + ByteBuffer factory = duckdb_v2_connection_get_factory(connHandle); + DuckDBVector[] vectors = new DuckDBVector[columnCount]; + for (int col = 0; col < columnCount; col++) { + vectors[col] = processVector(factory, duckdb_data_chunk_get_vector(chunk, col), rowCount); + } + return vectors; + } + + static String[] castResultToStrings(ResultRef ref, long colIdx) throws SQLException { + if (ref == null || ref.schema == null) { + throw invalid("Invalid result set"); + } + if (ref.currentChunk == null) { + return null; + } + int rowCount = (int) duckdb_data_chunk_get_size(ref.currentChunk); + ByteBuffer vec = duckdb_data_chunk_get_vector(ref.currentChunk, colIdx); + String[] res = new String[rowCount]; + for (int row = 0; row < rowCount; row++) { + res[row] = valueToString(vec, row); + } + return res; + } + + // Returns null for a NULL value + private static String valueToString(ByteBuffer vec, int row) throws SQLException { + ByteBuffer value = duckdb_v2_vector_get_value(vec, row); + try { + if (duckdb_is_null_value(value)) { + return null; + } + return new String(duckdb_v2_value_to_string(value), UTF_8); + } finally { + duckdb_v2_value_destroy(value); + } + } + + private static boolean[] nullMask(ByteBuffer vec, int rowCount) { + boolean[] nulls = new boolean[rowCount]; + ByteBuffer validity = duckdb_vector_get_validity(vec, rowCount); + if (validity != null) { + validity.order(NATIVE_ORDER); + for (int row = 0; row < rowCount; row++) { + long mask = validity.getLong((row >> 6) << 3); + nulls[row] = (mask & (1L << (row & 63))) == 0; + } + } + return nulls; + } + + private static int fixedWidth(int typeId, ByteBuffer type) throws SQLException { + switch (typeId) { + case TYPE_BOOLEAN: + case TYPE_TINYINT: + case TYPE_UTINYINT: + return 1; + case TYPE_SMALLINT: + case TYPE_USMALLINT: + return 2; + case TYPE_INTEGER: + case TYPE_UINTEGER: + case TYPE_FLOAT: + case TYPE_DATE: + return 4; + case TYPE_BIGINT: + case TYPE_UBIGINT: + case TYPE_DOUBLE: + case TYPE_TIME: + case TYPE_TIME_NS: + case TYPE_TIME_TZ: + case TYPE_TIMESTAMP: + case TYPE_TIMESTAMP_S: + case TYPE_TIMESTAMP_MS: + case TYPE_TIMESTAMP_NS: + case TYPE_TIMESTAMP_TZ: + return 8; + case TYPE_HUGEINT: + case TYPE_UHUGEINT: + case TYPE_UUID: + return 16; + case TYPE_DECIMAL: + switch (duckdb_decimal_internal_type(type)) { + case TYPE_SMALLINT: + return 2; + case TYPE_INTEGER: + return 4; + case TYPE_BIGINT: + return 8; + case TYPE_HUGEINT: + return 16; + default: + throw new SQLException("Unimplemented physical type for decimal"); + } + default: + return 0; + } + } + + static DuckDBVector processVector(ByteBuffer factory, ByteBuffer vec, int rowCount) throws SQLException { + duckdb_v2_vector_flatten(vec); + ByteBuffer type = duckdb_vector_get_column_type(vec); + try { + int typeId = duckdb_get_type_id(type); + boolean[] nulls = nullMask(vec, rowCount); + DuckDBVector jvec = new DuckDBVector(typeDetail(factory, type), rowCount, nulls); + + int width = fixedWidth(typeId, type); + if (width > 0) { + jvec.constlen_data = duckdb_vector_get_data(vec, (long) rowCount * width); + return jvec; + } + + switch (typeId) { + case TYPE_STRUCT: + case TYPE_UNION: + processStruct(factory, vec, type, jvec, rowCount); + return jvec; + case TYPE_BLOB: + case TYPE_GEOMETRY: { + byte[][] blobs = new byte[rowCount][]; + ByteBuffer data = duckdb_vector_get_data(vec, (long) rowCount * 16); + for (int row = 0; row < rowCount; row++) { + if (!nulls[row]) { + blobs[row] = duckdb_vector_get_string(data, row); + } + } + jvec.varlen_data = blobs; + return jvec; + } + case TYPE_ARRAY: { + int size = (int) duckdb_array_type_array_size(type); + DuckDBVector child = + processVector(factory, duckdb_array_vector_get_child(vec), Math.multiplyExact(rowCount, size)); + DuckDBArray[] arrays = new DuckDBArray[rowCount]; + for (int row = 0; row < rowCount; row++) { + if (!nulls[row]) { + arrays[row] = new DuckDBArray(child, row * size, size); + } + } + jvec.varlen_data = arrays; + return jvec; + } + case TYPE_MAP: + case TYPE_LIST: { + ByteBuffer entries = duckdb_vector_get_data(vec, (long) rowCount * 16).order(NATIVE_ORDER); + int listSize = (int) duckdb_list_vector_get_size(vec); + DuckDBVector child = processVector(factory, duckdb_list_vector_get_child(vec), listSize); + DuckDBArray[] arrays = new DuckDBArray[rowCount]; + for (int row = 0; row < rowCount; row++) { + if (!nulls[row]) { + int offset = (int) entries.getLong(row * 16); + int length = (int) entries.getLong(row * 16 + 8); + arrays[row] = new DuckDBArray(child, offset, length); + } + } + jvec.varlen_data = arrays; + return jvec; + } + case TYPE_VARIANT: { + Object[] variants = new Object[rowCount]; + for (int row = 0; row < rowCount; row++) { + if (!nulls[row]) { + variants[row] = variantToVector(factory, vec, row); + } + } + jvec.varlen_data = variants; + return jvec; + } + case TYPE_VARCHAR: { + String[] strings = new String[rowCount]; + ByteBuffer data = duckdb_vector_get_data(vec, (long) rowCount * 16); + for (int row = 0; row < rowCount; row++) { + if (!nulls[row]) { + strings[row] = new String(duckdb_vector_get_string(data, row), UTF_8); + } + } + jvec.varlen_data = strings; + return jvec; + } + default: { + // ENUM and the types that have no special representation are read as strings + String[] strings = new String[rowCount]; + for (int row = 0; row < rowCount; row++) { + if (!nulls[row]) { + strings[row] = valueToString(vec, row); + } + } + jvec.varlen_data = strings; + return jvec; + } + } + } finally { + duckdb_destroy_logical_type(type); + } + } + + private static void processStruct(ByteBuffer factory, ByteBuffer vec, ByteBuffer type, DuckDBVector jvec, + int rowCount) throws SQLException { + int childCount = (int) duckdb_struct_type_child_count(type); + DuckDBVector[] columns = new DuckDBVector[childCount]; + String[] names = new String[childCount]; + for (int i = 0; i < childCount; i++) { + columns[i] = processVector(factory, duckdb_struct_vector_get_child(vec, i), rowCount); + byte[] name = duckdb_struct_type_child_name(type, i); + // the members of a TUPLE are unnamed, use the positional names: "element1", "element2", ... + names[i] = name == null || name.length == 0 ? "element" + (i + 1) : new String(name, UTF_8); + } + String typeName = typeText(factory, type); + DuckDBStruct[] structs = new DuckDBStruct[rowCount]; + for (int row = 0; row < rowCount; row++) { + structs[row] = new DuckDBStruct(names, columns, row, typeName); + } + jvec.varlen_data = structs; + } + + // The value of a VARIANT is read as a vector of one row of the type of the value + private static DuckDBVector variantToVector(ByteBuffer factory, ByteBuffer vec, int row) throws SQLException { + ByteBuffer variant = duckdb_v2_vector_get_value(vec, row); + ByteBuffer value = null; + ByteBuffer type = null; + ByteBuffer single = null; + try { + value = duckdb_v2_value_variant_to_value(variant); + if (duckdb_is_null_value(value)) { + return null; + } + type = duckdb_v2_value_get_logical_type(value); + single = duckdb_create_vector(type); + duckdb_v2_vector_set_size(single, 1); + duckdb_v2_vector_set_value(single, 0, value); + DuckDBVector res = processVector(factory, single, 1); + res.retainConstlenData(); + return res; + } finally { + if (single != null) { + duckdb_destroy_vector(single); + } + if (type != null) { + duckdb_destroy_logical_type(type); + } + if (value != null) { + duckdb_v2_value_destroy(value); + } + duckdb_v2_value_destroy(variant); + } + } + + // --------------------------------------------------------------------------------------------------------- + // Parameters + // --------------------------------------------------------------------------------------------------------- + + private static ByteBuffer parseType(ByteBuffer factory, String text) throws SQLException { + return duckdb_v2_factory_create_type_from_text(factory, text.getBytes(UTF_8)); + } + + private static ByteBuffer nullValue(ByteBuffer factory) throws SQLException { + ByteBuffer type = parseType(factory, "NULL"); + try { + return duckdb_v2_value_create_null(factory, type); + } finally { + duckdb_destroy_logical_type(type); + } + } + + private static void destroyValues(List values) { + for (ByteBuffer value : values) { + try { + duckdb_v2_value_destroy(value); + } catch (SQLException e) { + // ignore + } + } + } + + private static ByteBuffer decimalValue(ByteBuffer factory, BigDecimal decimal) throws SQLException { + int precision = decimal.precision(); + int scale = decimal.scale(); + // Java BigDecimal type can have scale that exceeds the precision + // Which our DECIMAL type does not support (assert(width >= scale)) + if (scale > precision) { + precision = scale; + } + // DECIMAL scale is unsigned, so negative values are not supported + if (scale < 0) { + throw invalid("Converting from a BigDecimal with negative scale is not supported"); + } + if (precision > 38) { + return nullValue(factory); + } + BigInteger unscaled = decimal.unscaledValue(); + return duckdb_v2_value_create_decimal(factory, unscaled.longValue(), unscaled.shiftRight(64).longValue(), + precision, scale); + } + + static ByteBuffer toValue(ByteBuffer factory, Object param) throws SQLException { + param = DuckDBTimestamp.valueOf(param); + if (param == null) { + return nullValue(factory); + } else if (param instanceof Boolean) { + return duckdb_v2_value_create_bool(factory, (Boolean) param); + } else if (param instanceof Byte) { + return duckdb_v2_value_create_tinyint(factory, (Byte) param); + } else if (param instanceof Short) { + return duckdb_v2_value_create_smallint(factory, (Short) param); + } else if (param instanceof Integer) { + return duckdb_v2_value_create_int(factory, (Integer) param); + } else if (param instanceof Long) { + return duckdb_v2_value_create_bigint(factory, (Long) param); + } else if (param instanceof DuckDBHugeInt) { + DuckDBHugeInt hugeInt = (DuckDBHugeInt) param; + return duckdb_v2_value_create_hugeint(factory, hugeInt.lower(), hugeInt.upper()); + } else if (param instanceof DuckDBTimestampTZ) { // Check for subclass before superclass! + return duckdb_v2_value_create_timestamp_tz(factory, ((DuckDBTimestampTZ) param).getMicrosEpoch()); + } else if (param instanceof DuckDBDate) { + return duckdb_v2_value_create_date(factory, (int) ((DuckDBDate) param).getDaysSinceEpoch()); + } else if (param instanceof DuckDBTime) { + return duckdb_v2_value_create_time(factory, ((DuckDBTime) param).getMicrosEpoch()); + } else if (param instanceof DuckDBTimestampNS) { // Check for subclass before superclass! + return duckdb_v2_value_create_timestamp_ns(factory, ((DuckDBTimestampNS) param).getNanosEpoch()); + } else if (param instanceof DuckDBTimestamp) { + return duckdb_v2_value_create_timestamp(factory, ((DuckDBTimestamp) param).getMicrosEpoch()); + } else if (param instanceof Float) { + return duckdb_v2_value_create_float(factory, (Float) param); + } else if (param instanceof Double) { + return duckdb_v2_value_create_double(factory, (Double) param); + } else if (param instanceof BigDecimal) { + return decimalValue(factory, (BigDecimal) param); + } else if (param instanceof String) { + return duckdb_v2_value_create_varchar(factory, ((String) param).getBytes(UTF_8)); + } else if (param instanceof byte[]) { + return duckdb_v2_value_create_blob(factory, (byte[]) param); + } else if (param instanceof UUID) { + UUID uuid = (UUID) param; + // Account for the following logic in UUID::FromString: + // Flip the first bit to make `order by uuid` same as `order by uuid::varchar` + long upper = uuid.getMostSignificantBits() ^ Long.MIN_VALUE; + return duckdb_v2_value_create_uuid(factory, uuid.getLeastSignificantBits(), upper); + } else if (param instanceof DuckDBMap) { + return mapValue(factory, (DuckDBMap) param); + } else if (param instanceof Struct) { + return structValue(factory, (Struct) param); + } else if (param instanceof java.sql.Array) { + return arrayValue(factory, (java.sql.Array) param); + } + throw invalid("Unsupported parameter type"); + } + + private static ByteBuffer typeParam(ByteBuffer type, long index) throws SQLException { + ByteBuffer value = duckdb_v2_logical_type_get_param_value(type, index); + try { + return duckdb_v2_value_get_type(value); + } finally { + duckdb_v2_value_destroy(value); + } + } + + private static ByteBuffer mapValue(ByteBuffer factory, DuckDBMap map) throws SQLException { + ByteBuffer mapType = parseType(factory, map.getSQLTypeName()); + ByteBuffer keyType = null; + ByteBuffer valueType = null; + List keys = new ArrayList<>(); + List values = new ArrayList<>(); + try { + if (duckdb_v2_logical_type_get_param_count(mapType) >= 2) { + keyType = typeParam(mapType, 0); + valueType = typeParam(mapType, 1); + } else { + // the map type has one parameter, the type of the entries + ByteBuffer entryType = typeParam(mapType, 0); + try { + keyType = typeParam(entryType, 0); + valueType = typeParam(entryType, 1); + } finally { + duckdb_destroy_logical_type(entryType); + } + } + for (Map.Entry entry : map.entrySet()) { + keys.add(toValue(factory, entry.getKey())); + values.add(toValue(factory, entry.getValue())); + } + return duckdb_v2_value_create_map(factory, keyType, valueType, keys.toArray(new ByteBuffer[0]), + values.toArray(new ByteBuffer[0])); + } finally { + destroyValues(keys); + destroyValues(values); + if (keyType != null) { + duckdb_destroy_logical_type(keyType); + } + if (valueType != null) { + duckdb_destroy_logical_type(valueType); + } + duckdb_destroy_logical_type(mapType); + } + } + + private static ByteBuffer structValue(ByteBuffer factory, Struct struct) throws SQLException { + ByteBuffer type = parseType(factory, struct.getSQLTypeName()); + List children = new ArrayList<>(); + try { + Object[] attributes = struct.getAttributes(); + byte[][] names = new byte[attributes.length][]; + for (int i = 0; i < attributes.length; i++) { + names[i] = duckdb_struct_type_child_name(type, i); + children.add(toValue(factory, attributes[i])); + } + return duckdb_v2_value_create_struct(factory, names, children.toArray(new ByteBuffer[0])); + } finally { + destroyValues(children); + duckdb_destroy_logical_type(type); + } + } + + private static ByteBuffer arrayValue(ByteBuffer factory, java.sql.Array array) throws SQLException { + ByteBuffer type = parseType(factory, array.getBaseTypeName()); + List children = new ArrayList<>(); + try { + Object[] elements = (Object[]) array.getArray(); + for (Object element : elements) { + children.add(toValue(factory, element)); + } + return duckdb_v2_value_create_list(factory, type, children.toArray(new ByteBuffer[0])); + } finally { + destroyValues(children); + duckdb_destroy_logical_type(type); + } + } +} diff --git a/src/main/java/org/duckdb/DuckDBNative.java b/src/main/java/org/duckdb/DuckDBNative.java index 92ce9d14c..71519f549 100644 --- a/src/main/java/org/duckdb/DuckDBNative.java +++ b/src/main/java/org/duckdb/DuckDBNative.java @@ -159,36 +159,77 @@ static native ByteBuffer duckdb_jdbc_startup(byte[] path, boolean read_only, Pro static native String duckdb_jdbc_get_catalog(ByteBuffer conn_ref); + // The statements, queries and results are implemented in Java on top of the C API v2 entry points of + // DuckDBBindings, see DuckDBCore + // returns stmt_ref result reference object - static native ByteBuffer duckdb_jdbc_prepare(ByteBuffer conn_ref, byte[] query) throws SQLException; + static DuckDBCore.StatementRef duckdb_jdbc_prepare(DuckDBConnection conn, byte[] query) throws SQLException { + return DuckDBCore.prepare(conn, query); + } - static native void duckdb_jdbc_release(ByteBuffer stmt_ref); + static void duckdb_jdbc_release(DuckDBCore.StatementRef stmt_ref) { + try { + DuckDBCore.release(stmt_ref); + } catch (SQLException e) { + // the statement is released, nothing else can be done + } + } - static native DuckDBResultSetMetaData duckdb_jdbc_query_result_meta(ByteBuffer result_ref) throws SQLException; + static DuckDBResultSetMetaData duckdb_jdbc_query_result_meta(DuckDBCore.ResultRef result_ref) throws SQLException { + return DuckDBCore.queryResultMeta(result_ref); + } - static native DuckDBResultSetMetaData duckdb_jdbc_prepared_statement_meta(ByteBuffer stmt_ref) throws SQLException; + static DuckDBResultSetMetaData duckdb_jdbc_prepared_statement_meta(DuckDBCore.StatementRef stmt_ref) + throws SQLException { + return DuckDBCore.preparedStatementMeta(stmt_ref); + } // returns res_ref result reference object - static native ByteBuffer duckdb_jdbc_execute(ByteBuffer stmt_ref, Object[] params) throws SQLException; + static DuckDBCore.ResultRef duckdb_jdbc_execute(DuckDBCore.StatementRef stmt_ref, Object[] params) + throws SQLException { + return DuckDBCore.execute(stmt_ref, params); + } - static native ByteBuffer duckdb_jdbc_execute_capi(ByteBuffer stmt_ref, Object[] params) throws SQLException; + static ByteBuffer duckdb_jdbc_execute_capi(DuckDBCore.StatementRef stmt_ref, Object[] params) throws SQLException { + return DuckDBCore.executeChunked(stmt_ref, params); + } - static native ByteBuffer duckdb_jdbc_pending_query(ByteBuffer conn_ref, byte[] query) throws SQLException; + static DuckDBCore.PendingRef duckdb_jdbc_pending_query(DuckDBConnection conn, byte[] query) throws SQLException { + return DuckDBCore.pendingQuery(conn, query); + } - static native ByteBuffer duckdb_jdbc_execute_pending(ByteBuffer pending_ref) throws SQLException; + static DuckDBCore.ResultRef duckdb_jdbc_execute_pending(DuckDBCore.PendingRef pending_ref) throws SQLException { + return DuckDBCore.executePending(pending_ref); + } - static native void duckdb_jdbc_release_pending(ByteBuffer pending_ref) throws SQLException; + static void duckdb_jdbc_release_pending(DuckDBCore.PendingRef pending_ref) throws SQLException { + DuckDBCore.releasePending(pending_ref); + } - static native void duckdb_jdbc_free_result(ByteBuffer res_ref); + static void duckdb_jdbc_free_result(DuckDBCore.ResultRef res_ref) { + try { + DuckDBCore.freeResult(res_ref); + } catch (SQLException e) { + // the result is freed, nothing else can be done + } + } - static native DuckDBVector[] duckdb_jdbc_fetch(ByteBuffer res_ref, ByteBuffer conn_ref) throws SQLException; + static DuckDBVector[] duckdb_jdbc_fetch(DuckDBCore.ResultRef res_ref, ByteBuffer conn_ref) throws SQLException { + return DuckDBCore.fetch(res_ref); + } - static native String[] duckdb_jdbc_cast_result_to_strings(ByteBuffer res_ref, ByteBuffer conn_ref, long col_idx) - throws SQLException; + static String[] duckdb_jdbc_cast_result_to_strings(DuckDBCore.ResultRef res_ref, ByteBuffer conn_ref, long col_idx) + throws SQLException { + return DuckDBCore.castResultToStrings(res_ref, col_idx); + } static native int duckdb_jdbc_fetch_size(); - static native long duckdb_jdbc_arrow_stream(ByteBuffer res_ref, ByteBuffer conn_ref, long batch_size); + // TODO: the Arrow export is not ported to the C API v2 yet + static long duckdb_jdbc_arrow_stream(DuckDBCore.ResultRef res_ref, ByteBuffer conn_ref, long batch_size) + throws SQLException { + throw new java.sql.SQLFeatureNotSupportedException("Arrow export is not supported yet"); + } static native void duckdb_jdbc_arrow_register(ByteBuffer conn_ref, long arrow_array_stream_pointer, byte[] name); @@ -203,9 +244,13 @@ static native ByteBuffer duckdb_jdbc_create_appender(ByteBuffer conn_ref, byte[] static native void duckdb_jdbc_appender_flush(ByteBuffer appender_ref) throws SQLException; - static native void duckdb_jdbc_interrupt(ByteBuffer conn_ref); + static void duckdb_jdbc_interrupt(ByteBuffer conn_ref) throws SQLException { + DuckDBBindings.duckdb_v2_connection_interrupt(DuckDBBindings.duckdb_v2_connection_from_ref(conn_ref)); + } - static native QueryProgress duckdb_jdbc_query_progress(ByteBuffer conn_ref); + static QueryProgress duckdb_jdbc_query_progress(ByteBuffer conn_ref) throws SQLException { + return DuckDBBindings.duckdb_v2_connection_progress_get(DuckDBBindings.duckdb_v2_connection_from_ref(conn_ref)); + } static native void duckdb_jdbc_appender_close(ByteBuffer appender_ref) throws SQLException; diff --git a/src/main/java/org/duckdb/DuckDBPendingQuery.java b/src/main/java/org/duckdb/DuckDBPendingQuery.java index 146754b69..8cfb0cafd 100644 --- a/src/main/java/org/duckdb/DuckDBPendingQuery.java +++ b/src/main/java/org/duckdb/DuckDBPendingQuery.java @@ -1,15 +1,14 @@ package org.duckdb; -import java.nio.ByteBuffer; import java.sql.SQLException; import java.util.concurrent.locks.ReentrantLock; class DuckDBPendingQuery { private DuckDBConnection conn; - ByteBuffer pendingRef = null; + DuckDBCore.PendingRef pendingRef = null; final ReentrantLock pendingRefLock = new ReentrantLock(); - DuckDBPendingQuery(DuckDBConnection conn, ByteBuffer pendingRef) { + DuckDBPendingQuery(DuckDBConnection conn, DuckDBCore.PendingRef pendingRef) { this.conn = conn; this.pendingRef = pendingRef; this.conn.connRefLock.lock(); diff --git a/src/main/java/org/duckdb/DuckDBPreparedStatement.java b/src/main/java/org/duckdb/DuckDBPreparedStatement.java index 422791b1c..de562d49f 100644 --- a/src/main/java/org/duckdb/DuckDBPreparedStatement.java +++ b/src/main/java/org/duckdb/DuckDBPreparedStatement.java @@ -50,7 +50,7 @@ public class DuckDBPreparedStatement implements PreparedStatement { private DuckDBConnection conn; - private ByteBuffer stmtRef = null; + private DuckDBCore.StatementRef stmtRef = null; private final ReentrantLock stmtRefLock = new ReentrantLock(); private String query = null; volatile boolean closeOnCompletion = false; @@ -170,7 +170,7 @@ private void prepare(String sql) throws SQLException { startTransaction(); } - stmtRef = DuckDBNative.duckdb_jdbc_prepare(conn.connRef, preparedSql.getBytes(UTF_8)); + stmtRef = DuckDBNative.duckdb_jdbc_prepare(conn, preparedSql.getBytes(UTF_8)); // Track prepared statement inside the parent connection conn.preparedStatements.add(this); } finally { @@ -193,7 +193,7 @@ private DirectQueryResult executeDirect() throws SQLException { conn.connRefLock.lock(); try { conn.checkOpen(); - ByteBuffer pendingRef = DuckDBNative.duckdb_jdbc_pending_query(conn.connRef, query.getBytes(UTF_8)); + DuckDBCore.PendingRef pendingRef = DuckDBNative.duckdb_jdbc_pending_query(conn, query.getBytes(UTF_8)); pending = new DuckDBPendingQuery(conn, pendingRef); // need to track the statement too to release the results conn.preparedStatements.add(this); @@ -206,7 +206,7 @@ private DirectQueryResult executeDirect() throws SQLException { if (pending.pendingRef == null) { throw createSQLException("Connection was closed", ErrorCode.PREPARED_CONN_CLOSED); } - ByteBuffer resultRef = DuckDBNative.duckdb_jdbc_execute_pending(pending.pendingRef); + DuckDBCore.ResultRef resultRef = DuckDBNative.duckdb_jdbc_execute_pending(pending.pendingRef); return new DirectQueryResult(resultRef, pending); } finally { pending.pendingRefLock.unlock(); @@ -223,7 +223,7 @@ public boolean execute() throws SQLException { connLock.lock(); connLock.unlock(); - ByteBuffer resultRef = null; + DuckDBCore.ResultRef resultRef = null; DuckDBPendingQuery pendingQuery = null; boolean queryFailed = false; @@ -1598,10 +1598,10 @@ public void run() { } private static class DirectQueryResult { - final ByteBuffer resultRef; + final DuckDBCore.ResultRef resultRef; final DuckDBPendingQuery pendingQuery; - private DirectQueryResult(ByteBuffer resultRef, DuckDBPendingQuery pendingQuery) { + private DirectQueryResult(DuckDBCore.ResultRef resultRef, DuckDBPendingQuery pendingQuery) { this.resultRef = resultRef; this.pendingQuery = pendingQuery; } diff --git a/src/main/java/org/duckdb/DuckDBResultSet.java b/src/main/java/org/duckdb/DuckDBResultSet.java index 3e9560ea8..0568b4ea3 100644 --- a/src/main/java/org/duckdb/DuckDBResultSet.java +++ b/src/main/java/org/duckdb/DuckDBResultSet.java @@ -42,7 +42,7 @@ public class DuckDBResultSet implements ResultSet { /** * {@code null} if this result set is closed. */ - private ByteBuffer resultRef; + private DuckDBCore.ResultRef resultRef; private final Lock resultRefLock = new ReentrantLock(); private DuckDBVector[] currentChunk = {}; @@ -51,7 +51,7 @@ public class DuckDBResultSet implements ResultSet { private boolean wasNull; public DuckDBResultSet(DuckDBConnection conn, DuckDBPreparedStatement stmt, DuckDBResultSetMetaData meta, - ByteBuffer resultRef) throws SQLException { + DuckDBCore.ResultRef resultRef) throws SQLException { try { this.conn = Objects.requireNonNull(conn); this.stmt = Objects.requireNonNull(stmt); From a24bd96d4cf843ee12bfdc899858cfde0f026d19 Mon Sep 17 00:00:00 2001 From: Robinho-MR Date: Fri, 27 Nov 2026 14:25:25 +0000 Subject: [PATCH 05/21] Implement the appenders in Java on top of the C API v2 --- CMakeLists.txt | 1 - CMakeLists.txt.in | 1 - duckdb_java.def | 36 +-- duckdb_java.exp | 36 +-- duckdb_java.map | 36 +-- src/jni/bindings_appender.cpp | 266 ----------------- src/jni/bindings_v2.cpp | 117 ++++++++ src/jni/duckdb_java.cpp | 102 ------- src/jni/functions.cpp | 171 ----------- src/jni/functions.hpp | 68 ----- src/main/java/org/duckdb/DuckDBAppender.java | 37 +-- src/main/java/org/duckdb/DuckDBBindings.java | 50 ++-- src/main/java/org/duckdb/DuckDBCore.java | 90 +++++- src/main/java/org/duckdb/DuckDBNative.java | 36 --- .../org/duckdb/DuckDBSingleValueAppender.java | 182 +++++++++--- .../java/org/duckdb/DuckDBV2Appender.java | 274 ++++++++++++++++++ src/test/java/org/duckdb/TestBindings.java | 55 ++-- 17 files changed, 727 insertions(+), 831 deletions(-) delete mode 100644 src/jni/bindings_appender.cpp create mode 100644 src/main/java/org/duckdb/DuckDBV2Appender.java diff --git a/CMakeLists.txt b/CMakeLists.txt index a655e3d0f..2a295f8fe 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -660,7 +660,6 @@ endif() add_library(duckdb_java SHARED src/jni/arrow.cpp - src/jni/bindings_appender.cpp src/jni/bindings_common.cpp src/jni/bindings_data_chunk.cpp src/jni/bindings_logical_type.cpp diff --git a/CMakeLists.txt.in b/CMakeLists.txt.in index a5221e688..a9c9a7a76 100644 --- a/CMakeLists.txt.in +++ b/CMakeLists.txt.in @@ -139,7 +139,6 @@ endif() add_library(duckdb_java SHARED src/jni/arrow.cpp - src/jni/bindings_appender.cpp src/jni/bindings_common.cpp src/jni/bindings_data_chunk.cpp src/jni/bindings_logical_type.cpp diff --git a/duckdb_java.def b/duckdb_java.def index d252d9cc1..4fb0bdec7 100644 --- a/duckdb_java.def +++ b/duckdb_java.def @@ -4,26 +4,9 @@ EXPORTS JNI_OnLoad JNI_OnUnload -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1boolean -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1byte -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1bytes -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1decimal -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1double -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1float -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1int -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1long -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1null -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1short -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1string -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1timestamp -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1begin_1row -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1close -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1end_1row -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1flush Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1close_1streams Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1register Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1connect -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1create_1appender Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1create_1db_1ref Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1destroy_1db_1ref Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1db_1address @@ -93,15 +76,6 @@ Java_org_duckdb_DuckDBBindings_duckdb_1data_1chunk_1get_1column_1count Java_org_duckdb_DuckDBBindings_duckdb_1data_1chunk_1get_1vector Java_org_duckdb_DuckDBBindings_duckdb_1data_1chunk_1get_1size Java_org_duckdb_DuckDBBindings_duckdb_1data_1chunk_1set_1size -Java_org_duckdb_DuckDBBindings_duckdb_1appender_1create_1ext -Java_org_duckdb_DuckDBBindings_duckdb_1appender_1error -Java_org_duckdb_DuckDBBindings_duckdb_1appender_1flush -Java_org_duckdb_DuckDBBindings_duckdb_1appender_1close -Java_org_duckdb_DuckDBBindings_duckdb_1appender_1destroy -Java_org_duckdb_DuckDBBindings_duckdb_1appender_1column_1count -Java_org_duckdb_DuckDBBindings_duckdb_1appender_1column_1type -Java_org_duckdb_DuckDBBindings_duckdb_1append_1data_1chunk -Java_org_duckdb_DuckDBBindings_duckdb_1append_1default_1to_1chunk Java_org_duckdb_DuckDBBindings_duckdb_1bind_1add_1result_1column Java_org_duckdb_DuckDBBindings_duckdb_1bind_1get_1parameter_1count @@ -235,6 +209,16 @@ Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp_1ns Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp_1tz Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1tinyint +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1append +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1append_1state_1create +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1append_1state_1destroy +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1clear +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1create +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1destroy +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1row_1count +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1copy +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1add_1collection +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1size ; ADBC entry point duckdb_adbc_init diff --git a/duckdb_java.exp b/duckdb_java.exp index cc9213587..e568398af 100644 --- a/duckdb_java.exp +++ b/duckdb_java.exp @@ -1,26 +1,9 @@ _JNI_OnLoad _JNI_OnUnload -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1boolean -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1byte -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1bytes -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1decimal -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1double -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1float -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1int -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1long -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1null -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1short -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1string -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1timestamp -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1begin_1row -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1close -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1end_1row -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1flush _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1close_1streams _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1register _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1connect -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1create_1appender _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1create_1db_1ref _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1destroy_1db_1ref _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1db_1address @@ -90,15 +73,6 @@ _Java_org_duckdb_DuckDBBindings_duckdb_1data_1chunk_1get_1column_1count _Java_org_duckdb_DuckDBBindings_duckdb_1data_1chunk_1get_1vector _Java_org_duckdb_DuckDBBindings_duckdb_1data_1chunk_1get_1size _Java_org_duckdb_DuckDBBindings_duckdb_1data_1chunk_1set_1size -_Java_org_duckdb_DuckDBBindings_duckdb_1appender_1create_1ext -_Java_org_duckdb_DuckDBBindings_duckdb_1appender_1error -_Java_org_duckdb_DuckDBBindings_duckdb_1appender_1flush -_Java_org_duckdb_DuckDBBindings_duckdb_1appender_1close -_Java_org_duckdb_DuckDBBindings_duckdb_1appender_1destroy -_Java_org_duckdb_DuckDBBindings_duckdb_1appender_1column_1count -_Java_org_duckdb_DuckDBBindings_duckdb_1appender_1column_1type -_Java_org_duckdb_DuckDBBindings_duckdb_1append_1data_1chunk -_Java_org_duckdb_DuckDBBindings_duckdb_1append_1default_1to_1chunk _Java_org_duckdb_DuckDBBindings_duckdb_1bind_1add_1result_1column _Java_org_duckdb_DuckDBBindings_duckdb_1bind_1get_1parameter_1count @@ -232,6 +206,16 @@ _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp_1ns _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp_1tz _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1tinyint +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1append +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1append_1state_1create +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1append_1state_1destroy +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1clear +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1create +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1destroy +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1row_1count +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1copy +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1add_1collection +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1size # ADBC entry point _duckdb_adbc_init diff --git a/duckdb_java.map b/duckdb_java.map index e4f25c288..4e8044395 100644 --- a/duckdb_java.map +++ b/duckdb_java.map @@ -3,26 +3,9 @@ DUCKDB_JAVA { JNI_OnLoad; JNI_OnUnload; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1boolean; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1byte; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1bytes; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1decimal; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1double; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1float; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1int; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1long; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1null; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1short; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1string; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1timestamp; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1begin_1row; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1close; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1end_1row; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1flush; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1close_1streams; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1register; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1connect; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1create_1appender; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1create_1db_1ref; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1destroy_1db_1ref; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1db_1address; @@ -92,15 +75,6 @@ DUCKDB_JAVA { Java_org_duckdb_DuckDBBindings_duckdb_1data_1chunk_1get_1vector; Java_org_duckdb_DuckDBBindings_duckdb_1data_1chunk_1get_1size; Java_org_duckdb_DuckDBBindings_duckdb_1data_1chunk_1set_1size; - Java_org_duckdb_DuckDBBindings_duckdb_1appender_1create_1ext; - Java_org_duckdb_DuckDBBindings_duckdb_1appender_1error; - Java_org_duckdb_DuckDBBindings_duckdb_1appender_1flush; - Java_org_duckdb_DuckDBBindings_duckdb_1appender_1close; - Java_org_duckdb_DuckDBBindings_duckdb_1appender_1destroy; - Java_org_duckdb_DuckDBBindings_duckdb_1appender_1column_1count; - Java_org_duckdb_DuckDBBindings_duckdb_1appender_1column_1type; - Java_org_duckdb_DuckDBBindings_duckdb_1append_1data_1chunk; - Java_org_duckdb_DuckDBBindings_duckdb_1append_1default_1to_1chunk; Java_org_duckdb_DuckDBBindings_duckdb_1bind_1add_1result_1column; Java_org_duckdb_DuckDBBindings_duckdb_1bind_1get_1parameter_1count; @@ -234,6 +208,16 @@ DUCKDB_JAVA { Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp_1ns; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp_1tz; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1tinyint; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1append; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1append_1state_1create; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1append_1state_1destroy; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1clear; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1create; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1destroy; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1row_1count; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1copy; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1add_1collection; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1size; /* ADBC entry point */ duckdb_adbc_init; diff --git a/src/jni/bindings_appender.cpp b/src/jni/bindings_appender.cpp deleted file mode 100644 index 671f829d5..000000000 --- a/src/jni/bindings_appender.cpp +++ /dev/null @@ -1,266 +0,0 @@ -#include "bindings.hpp" -#include "holders.hpp" -#include "util.hpp" - -/* - * The C API v2 does not have an appender, the appender of the C API v1 is used. The connection, data chunks and - * logical types are passed between Java and JNI as C API v2 handles, they are converted to and from C API v1 handles - * here. In both APIs these handles point to the same engine objects, except logical types that are copied. - */ -extern "C" { -#include "duckdb.h" -} - -static duckdb_data_chunk v2_chunk_to_v1_chunk(duckdb_v2_data_chunk_handle chunk) { - duckdb::DataChunk *engine_chunk = duckdb::capiv2::Convert(chunk); - return reinterpret_cast(engine_chunk); -} - -static duckdb_v2_logical_type_handle v1_logical_type_to_v2_logical_type(duckdb_logical_type logical_type) { - if (logical_type == nullptr) { - return nullptr; - } - auto engine_type = reinterpret_cast(logical_type); - auto res = duckdb::capiv2::Convert(engine_type->Copy()); - duckdb_destroy_logical_type(&logical_type); - return res; -} - -static duckdb_appender appender_buf_to_appender(JNIEnv *env, jobject appender_buf) { - - if (appender_buf == nullptr) { - env->ThrowNew(J_SQLException, "Invalid appender buffer"); - return nullptr; - } - - duckdb_appender appender = reinterpret_cast(env->GetDirectBufferAddress(appender_buf)); - if (appender == nullptr) { - env->ThrowNew(J_SQLException, "Invalid appender"); - return nullptr; - } - - return appender; -} - -/* - * Class: org_duckdb_DuckDBBindings - * Method: duckdb_appender_create_ext - * Signature: (Ljava/nio/ByteBuffer;[B[B[B[Ljava/nio/ByteBuffer;)I - */ -JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1create_1ext(JNIEnv *env, jclass, - jobject connection, - jbyteArray catalog, - jbyteArray schema, jbyteArray table, - jobjectArray out_appender) { - - duckdb::Connection *engine_conn = conn_ref_buf_to_engine_conn(env, connection); - if (env->ExceptionCheck()) { - return -1; - } - auto conn = reinterpret_cast(engine_conn); - - std::string catalog_str = jbyteArray_to_string(env, catalog); - if (env->ExceptionCheck()) { - return -1; - } - const char *catalog_ptr = nullptr != catalog ? catalog_str.c_str() : nullptr; - - std::string schema_str = jbyteArray_to_string(env, schema); - if (env->ExceptionCheck()) { - return -1; - } - const char *schema_ptr = nullptr != schema ? schema_str.c_str() : nullptr; - - std::string table_str = jbyteArray_to_string(env, table); - if (env->ExceptionCheck()) { - return -1; - } - const char *table_ptr = nullptr != table ? table_str.c_str() : nullptr; - - check_out_param(env, out_appender); - if (env->ExceptionCheck()) { - return -1; - } - - duckdb_appender appender = nullptr; - - duckdb_state state = duckdb_appender_create_ext(conn, catalog_ptr, schema_ptr, table_ptr, &appender); - - if (state == DuckDBSuccess) { - jobject appender_ref_buf = env->NewDirectByteBuffer(appender, 0); - set_out_param(env, out_appender, appender_ref_buf); - } - - return static_cast(state); -} - -/* - * Class: org_duckdb_DuckDBBindings - * Method: duckdb_appender_error - * Signature: (Ljava/nio/ByteBuffer;)[B - */ -JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1error(JNIEnv *env, jclass, - jobject appender) { - - duckdb_appender app = appender_buf_to_appender(env, appender); - if (env->ExceptionCheck()) { - return nullptr; - } - - const char *error_msg = duckdb_appender_error(app); - if (error_msg == nullptr) { - return nullptr; - } - - idx_t len = static_cast(std::strlen(error_msg)); - - return make_jbyteArray(env, error_msg, len); -} - -/* - * Class: org_duckdb_DuckDBBindings - * Method: duckdb_appender_flush - * Signature: (Ljava/nio/ByteBuffer;)I - */ -JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1flush(JNIEnv *env, jclass, jobject appender) { - - duckdb_appender app = appender_buf_to_appender(env, appender); - if (env->ExceptionCheck()) { - return -1; - } - - duckdb_state state = duckdb_appender_flush(app); - - return static_cast(state); -} - -/* - * Class: org_duckdb_DuckDBBindings - * Method: duckdb_appender_close - * Signature: (Ljava/nio/ByteBuffer;)I - */ -JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1close(JNIEnv *env, jclass, jobject appender) { - - duckdb_appender app = appender_buf_to_appender(env, appender); - if (env->ExceptionCheck()) { - return -1; - } - - duckdb_state state = duckdb_appender_close(app); - - return static_cast(state); -} - -/* - * Class: org_duckdb_DuckDBBindings - * Method: duckdb_appender_destroy - * Signature: (Ljava/nio/ByteBuffer;)I - */ -JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1destroy(JNIEnv *env, jclass, jobject appender) { - - duckdb_appender app = appender_buf_to_appender(env, appender); - if (env->ExceptionCheck()) { - return -1; - } - - duckdb_state state = duckdb_appender_destroy(&app); - - return static_cast(state); -} - -/* - * Class: org_duckdb_DuckDBBindings - * Method: duckdb_appender_column_count - * Signature: (Ljava/nio/ByteBuffer;)J - */ -JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1column_1count(JNIEnv *env, jclass, - jobject appender) { - - duckdb_appender app = appender_buf_to_appender(env, appender); - if (env->ExceptionCheck()) { - return -1; - } - - idx_t count = duckdb_appender_column_count(app); - - return static_cast(count); -} - -/* - * Class: org_duckdb_DuckDBBindings - * Method: duckdb_appender_column_type - * Signature: (Ljava/nio/ByteBuffer;J)Ljava/nio/ByteBuffer; - */ -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1column_1type(JNIEnv *env, jclass, - jobject appender, - jlong col_idx) { - - duckdb_appender app = appender_buf_to_appender(env, appender); - if (env->ExceptionCheck()) { - return nullptr; - } - - idx_t idx = jlong_to_idx(env, col_idx); - if (env->ExceptionCheck()) { - return nullptr; - } - - duckdb_logical_type logical_type = duckdb_appender_column_type(app, idx); - - return make_logical_type_buf(env, v1_logical_type_to_v2_logical_type(logical_type)); -} - -/* - * Class: org_duckdb_DuckDBBindings - * Method: duckdb_append_data_chunk - * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)I - */ -JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1append_1data_1chunk(JNIEnv *env, jclass, jobject appender, - jobject chunk) { - - duckdb_appender app = appender_buf_to_appender(env, appender); - if (env->ExceptionCheck()) { - return -1; - } - - duckdb_data_chunk dc = v2_chunk_to_v1_chunk(chunk_buf_to_chunk(env, chunk)); - if (env->ExceptionCheck()) { - return -1; - } - - duckdb_state state = duckdb_append_data_chunk(app, dc); - - return static_cast(state); -} - -/* - * Class: org_duckdb_DuckDBBindings - * Method: duckdb_append_default_to_chunk - * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;JJ)I - */ -JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1append_1default_1to_1chunk(JNIEnv *env, jclass, - jobject appender, - jobject chunk, jlong col, - jlong row) { - - duckdb_appender app = appender_buf_to_appender(env, appender); - if (env->ExceptionCheck()) { - return -1; - } - duckdb_data_chunk dc = v2_chunk_to_v1_chunk(chunk_buf_to_chunk(env, chunk)); - if (env->ExceptionCheck()) { - return -1; - } - idx_t col_idx = jlong_to_idx(env, col); - if (env->ExceptionCheck()) { - return -1; - } - idx_t row_idx = jlong_to_idx(env, row); - if (env->ExceptionCheck()) { - return -1; - } - - duckdb_state state = duckdb_append_default_to_chunk(app, dc, col_idx, row_idx); - - return static_cast(state); -} diff --git a/src/jni/bindings_v2.cpp b/src/jni/bindings_v2.cpp index 604c53cfd..3e3a77423 100644 --- a/src/jni/bindings_v2.cpp +++ b/src/jni/bindings_v2.cpp @@ -749,3 +749,120 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1set_1s } CALL_V2(duckdb_v2_vector_set_size(vector, sz, ERR_OUT), ); } + +/* --- appending --- */ + +// The returned type is owned by the caller +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1copy(JNIEnv *env, jclass, + jobject type_buf) { + auto type = logical_type_buf_to_logical_type(env, type_buf); + if (env->ExceptionCheck()) { + return nullptr; + } + duckdb_v2_logical_type_handle copy = nullptr; + CALL_V2(duckdb_v2_logical_type_copy(type, ©, ERR_OUT), nullptr); + return make_logical_type_buf(env, copy); +} + +JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1size(JNIEnv *env, jclass, + jobject vector_buf) { + CHECK_BUF_RET(vector, vector_buf, duckdb_v2_vector_handle, "vector", 0); + idx_t size = 0; + CALL_V2(duckdb_v2_vector_get_size(vector, &size, ERR_OUT), 0); + return uint64_to_jlong(size); +} + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1create( + JNIEnv *env, jclass, jobject factory_buf, jobjectArray types_j) { + CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); + std::vector types; + jsize count = types_j == nullptr ? 0 : env->GetArrayLength(types_j); + for (jsize i = 0; i < count; i++) { + jobject type_buf = env->GetObjectArrayElement(types_j, i); + auto type = logical_type_buf_to_logical_type(env, type_buf); + env->DeleteLocalRef(type_buf); + if (env->ExceptionCheck()) { + return nullptr; + } + types.push_back(type); + } + duckdb_v2_column_data_collection_handle collection = nullptr; + CALL_V2(duckdb_v2_column_data_collection_create(factory, types.data(), types.size(), &collection, ERR_OUT), + nullptr); + return make_ptr_buf(env, collection); +} + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1destroy( + JNIEnv *env, jclass, jobject collection_buf) { + CHECK_BUF(collection, collection_buf, duckdb_v2_column_data_collection_handle, "collection"); + duckdb_v2_column_data_collection_destroy(&collection); +} + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1clear( + JNIEnv *env, jclass, jobject collection_buf) { + CHECK_BUF(collection, collection_buf, duckdb_v2_column_data_collection_handle, "collection"); + CALL_V2(duckdb_v2_column_data_collection_clear(collection, ERR_OUT), ); +} + +JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1row_1count( + JNIEnv *env, jclass, jobject collection_buf) { + CHECK_BUF_RET(collection, collection_buf, duckdb_v2_column_data_collection_handle, "collection", 0); + idx_t count = 0; + CALL_V2(duckdb_v2_column_data_collection_row_count(collection, &count, ERR_OUT), 0); + return uint64_to_jlong(count); +} + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1append_1state_1create( + JNIEnv *env, jclass, jobject collection_buf) { + CHECK_BUF_RET(collection, collection_buf, duckdb_v2_column_data_collection_handle, "collection", nullptr); + duckdb_v2_column_data_collection_append_state_handle state = nullptr; + CALL_V2(duckdb_v2_column_data_collection_append_state_create(collection, &state, ERR_OUT), nullptr); + return make_ptr_buf(env, state); +} + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1append_1state_1destroy( + JNIEnv *env, jclass, jobject state_buf) { + CHECK_BUF(state, state_buf, duckdb_v2_column_data_collection_append_state_handle, "append state"); + duckdb_v2_column_data_collection_append_state_destroy(&state); +} + +// The chunk is borrowed for the call +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1append( + JNIEnv *env, jclass, jobject collection_buf, jobject state_buf, jobject chunk_buf) { + CHECK_BUF(collection, collection_buf, duckdb_v2_column_data_collection_handle, "collection"); + CHECK_BUF(state, state_buf, duckdb_v2_column_data_collection_append_state_handle, "append state"); + auto chunk = chunk_buf_to_chunk(env, chunk_buf); + if (env->ExceptionCheck()) { + return; + } + CALL_V2(duckdb_v2_column_data_collection_append(collection, state, chunk, ERR_OUT), ); +} + +// Binds the collection to the statement under the name, the collection must outlive the statement executions +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1add_1collection( + JNIEnv *env, jclass, jobject st_buf, jbyteArray name_j, jobject collection_buf, jobjectArray names_j) { + CHECK_BUF(st, st_buf, duckdb_v2_sql_statement_handle, "statement"); + CHECK_BUF(collection, collection_buf, duckdb_v2_column_data_collection_handle, "collection"); + auto name = jbyteArray_to_string(env, name_j); + if (env->ExceptionCheck()) { + return; + } + std::vector names; + jsize count = names_j == nullptr ? 0 : env->GetArrayLength(names_j); + for (jsize i = 0; i < count; i++) { + auto name_arr = reinterpret_cast(env->GetObjectArrayElement(names_j, i)); + names.push_back(jbyteArray_to_string(env, name_arr)); + env->DeleteLocalRef(name_arr); + if (env->ExceptionCheck()) { + return; + } + } + std::vector name_ptrs; + std::vector name_lens; + for (auto &column_name : names) { + name_ptrs.push_back(column_name.data()); + name_lens.push_back(column_name.size()); + } + CALL_V2(duckdb_v2_statement_add_collection(st, name.data(), name.size(), collection, name_ptrs.data(), + name_lens.data(), names.size(), ERR_OUT), ); +} diff --git a/src/jni/duckdb_java.cpp b/src/jni/duckdb_java.cpp index 609190f59..8c3c608bf 100644 --- a/src/jni/duckdb_java.cpp +++ b/src/jni/duckdb_java.cpp @@ -9,7 +9,6 @@ #include "duckdb/common/vector/struct_vector.hpp" #include "duckdb/function/scalar/variant_utils.hpp" #include "duckdb/function/table/arrow.hpp" -#include "duckdb/main/appender.hpp" #include "duckdb/main/capi_v2/capi_v2_internal.hpp" #include "duckdb/main/capi_v2/capi_v2_result_internal.hpp" #include "duckdb/main/client_context.hpp" @@ -196,107 +195,6 @@ jint _duckdb_jdbc_fetch_size(JNIEnv *, jclass) { return STANDARD_VECTOR_SIZE; } -jobject _duckdb_jdbc_create_appender(JNIEnv *env, jclass, jobject conn_ref_buf, jbyteArray schema_name_j, - jbyteArray table_name_j) { - - auto conn_ref = get_connection(env, conn_ref_buf); - if (!conn_ref) { - return nullptr; - } - auto schema_name = jbyteArray_to_string(env, schema_name_j); - auto table_name = jbyteArray_to_string(env, table_name_j); - auto appender = new Appender(*conn_ref, Identifier(schema_name), Identifier(table_name)); - return env->NewDirectByteBuffer(appender, 0); -} - -static Appender *get_appender(JNIEnv *env, jobject appender_ref_buf) { - auto appender_ref = (Appender *)env->GetDirectBufferAddress(appender_ref_buf); - if (!appender_ref) { - throw InvalidInputException("Invalid appender"); - } - return appender_ref; -} - -void _duckdb_jdbc_appender_begin_row(JNIEnv *env, jclass, jobject appender_ref_buf) { - get_appender(env, appender_ref_buf)->BeginRow(); -} - -void _duckdb_jdbc_appender_end_row(JNIEnv *env, jclass, jobject appender_ref_buf) { - get_appender(env, appender_ref_buf)->EndRow(); -} - -void _duckdb_jdbc_appender_flush(JNIEnv *env, jclass, jobject appender_ref_buf) { - get_appender(env, appender_ref_buf)->Flush(); -} - -void _duckdb_jdbc_appender_close(JNIEnv *env, jclass, jobject appender_ref_buf) { - auto appender = get_appender(env, appender_ref_buf); - appender->Close(); - delete appender; -} - -void _duckdb_jdbc_appender_append_boolean(JNIEnv *env, jclass, jobject appender_ref_buf, jboolean value) { - get_appender(env, appender_ref_buf)->Append((bool)value); -} - -void _duckdb_jdbc_appender_append_byte(JNIEnv *env, jclass, jobject appender_ref_buf, jbyte value) { - get_appender(env, appender_ref_buf)->Append((int8_t)value); -} - -void _duckdb_jdbc_appender_append_short(JNIEnv *env, jclass, jobject appender_ref_buf, jshort value) { - get_appender(env, appender_ref_buf)->Append((int16_t)value); -} - -void _duckdb_jdbc_appender_append_int(JNIEnv *env, jclass, jobject appender_ref_buf, jint value) { - get_appender(env, appender_ref_buf)->Append((int32_t)value); -} - -void _duckdb_jdbc_appender_append_long(JNIEnv *env, jclass, jobject appender_ref_buf, jlong value) { - get_appender(env, appender_ref_buf)->Append((int64_t)value); -} - -void _duckdb_jdbc_appender_append_float(JNIEnv *env, jclass, jobject appender_ref_buf, jfloat value) { - get_appender(env, appender_ref_buf)->Append((float)value); -} - -void _duckdb_jdbc_appender_append_double(JNIEnv *env, jclass, jobject appender_ref_buf, jdouble value) { - get_appender(env, appender_ref_buf)->Append((double)value); -} - -void _duckdb_jdbc_appender_append_timestamp(JNIEnv *env, jclass, jobject appender_ref_buf, jlong value) { - timestamp_t timestamp = timestamp_t((int64_t)value); - get_appender(env, appender_ref_buf)->Append(Value::TIMESTAMP(timestamp)); -} - -void _duckdb_jdbc_appender_append_decimal(JNIEnv *env, jclass, jobject appender_ref_buf, jobject value) { - Value val = create_value_from_bigdecimal(env, value); - get_appender(env, appender_ref_buf)->Append(val); -} - -void _duckdb_jdbc_appender_append_string(JNIEnv *env, jclass, jobject appender_ref_buf, jbyteArray value) { - if (env->IsSameObject(value, NULL)) { - get_appender(env, appender_ref_buf)->Append(nullptr); - return; - } - - auto string_value = jbyteArray_to_string(env, value); - get_appender(env, appender_ref_buf)->Append(string_value.c_str()); -} - -void _duckdb_jdbc_appender_append_bytes(JNIEnv *env, jclass, jobject appender_ref_buf, jbyteArray value) { - if (env->IsSameObject(value, NULL)) { - get_appender(env, appender_ref_buf)->Append(nullptr); - return; - } - - auto string_value = jbyteArray_to_string(env, value); - get_appender(env, appender_ref_buf)->Append(Value::BLOB_RAW(string_value)); -} - -void _duckdb_jdbc_appender_append_null(JNIEnv *env, jclass, jobject appender_ref_buf) { - get_appender(env, appender_ref_buf)->Append(nullptr); -} - class JavaArrowScanFactory : public ArrowScanFactory { public: explicit JavaArrowScanFactory(duckdb::shared_ptr state_p) : state(std::move(state_p)) { diff --git a/src/jni/functions.cpp b/src/jni/functions.cpp index 6f9aa4a88..d50aa7d97 100644 --- a/src/jni/functions.cpp +++ b/src/jni/functions.cpp @@ -162,177 +162,6 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1close_1 } } -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1create_1appender(JNIEnv * env, jclass param0, jobject param1, jbyteArray param2, jbyteArray param3) { - try { - return _duckdb_jdbc_create_appender(env, param0, param1, param2, param3); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - return nullptr; - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1begin_1row(JNIEnv * env, jclass param0, jobject param1) { - try { - return _duckdb_jdbc_appender_begin_row(env, param0, param1); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1end_1row(JNIEnv * env, jclass param0, jobject param1) { - try { - return _duckdb_jdbc_appender_end_row(env, param0, param1); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1flush(JNIEnv * env, jclass param0, jobject param1) { - try { - return _duckdb_jdbc_appender_flush(env, param0, param1); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1close(JNIEnv * env, jclass param0, jobject param1) { - try { - return _duckdb_jdbc_appender_close(env, param0, param1); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1boolean(JNIEnv * env, jclass param0, jobject param1, jboolean param2) { - try { - return _duckdb_jdbc_appender_append_boolean(env, param0, param1, param2); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1byte(JNIEnv * env, jclass param0, jobject param1, jbyte param2) { - try { - return _duckdb_jdbc_appender_append_byte(env, param0, param1, param2); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1short(JNIEnv * env, jclass param0, jobject param1, jshort param2) { - try { - return _duckdb_jdbc_appender_append_short(env, param0, param1, param2); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1int(JNIEnv * env, jclass param0, jobject param1, jint param2) { - try { - return _duckdb_jdbc_appender_append_int(env, param0, param1, param2); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1long(JNIEnv * env, jclass param0, jobject param1, jlong param2) { - try { - return _duckdb_jdbc_appender_append_long(env, param0, param1, param2); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1float(JNIEnv * env, jclass param0, jobject param1, jfloat param2) { - try { - return _duckdb_jdbc_appender_append_float(env, param0, param1, param2); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1double(JNIEnv * env, jclass param0, jobject param1, jdouble param2) { - try { - return _duckdb_jdbc_appender_append_double(env, param0, param1, param2); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1string(JNIEnv * env, jclass param0, jobject param1, jbyteArray param2) { - try { - return _duckdb_jdbc_appender_append_string(env, param0, param1, param2); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1bytes(JNIEnv * env, jclass param0, jobject param1, jbyteArray param2) { - try { - return _duckdb_jdbc_appender_append_bytes(env, param0, param1, param2); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1timestamp(JNIEnv * env, jclass param0, jobject param1, jlong param2) { - try { - return _duckdb_jdbc_appender_append_timestamp(env, param0, param1, param2); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1decimal(JNIEnv * env, jclass param0, jobject param1, jobject param2) { - try { - return _duckdb_jdbc_appender_append_decimal(env, param0, param1, param2); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1null(JNIEnv * env, jclass param0, jobject param1) { - try { - return _duckdb_jdbc_appender_append_null(env, param0, param1); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - JNIEXPORT jstring JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1profiling_1information(JNIEnv * env, jclass param0, jobject param1, jobject param2) { try { return _duckdb_jdbc_get_profiling_information(env, param0, param1, param2); diff --git a/src/jni/functions.hpp b/src/jni/functions.hpp index 15a96e1fd..a358709a5 100644 --- a/src/jni/functions.hpp +++ b/src/jni/functions.hpp @@ -69,74 +69,6 @@ void _duckdb_jdbc_arrow_close_streams(JNIEnv * env, jclass param0, jobject param JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1close_1streams(JNIEnv * env, jclass param0, jobject param1); -jobject _duckdb_jdbc_create_appender(JNIEnv * env, jclass param0, jobject param1, jbyteArray param2, jbyteArray param3); - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1create_1appender(JNIEnv * env, jclass param0, jobject param1, jbyteArray param2, jbyteArray param3); - -void _duckdb_jdbc_appender_begin_row(JNIEnv * env, jclass param0, jobject param1); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1begin_1row(JNIEnv * env, jclass param0, jobject param1); - -void _duckdb_jdbc_appender_end_row(JNIEnv * env, jclass param0, jobject param1); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1end_1row(JNIEnv * env, jclass param0, jobject param1); - -void _duckdb_jdbc_appender_flush(JNIEnv * env, jclass param0, jobject param1); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1flush(JNIEnv * env, jclass param0, jobject param1); - -void _duckdb_jdbc_appender_close(JNIEnv * env, jclass param0, jobject param1); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1close(JNIEnv * env, jclass param0, jobject param1); - -void _duckdb_jdbc_appender_append_boolean(JNIEnv * env, jclass param0, jobject param1, jboolean param2); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1boolean(JNIEnv * env, jclass param0, jobject param1, jboolean param2); - -void _duckdb_jdbc_appender_append_byte(JNIEnv * env, jclass param0, jobject param1, jbyte param2); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1byte(JNIEnv * env, jclass param0, jobject param1, jbyte param2); - -void _duckdb_jdbc_appender_append_short(JNIEnv * env, jclass param0, jobject param1, jshort param2); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1short(JNIEnv * env, jclass param0, jobject param1, jshort param2); - -void _duckdb_jdbc_appender_append_int(JNIEnv * env, jclass param0, jobject param1, jint param2); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1int(JNIEnv * env, jclass param0, jobject param1, jint param2); - -void _duckdb_jdbc_appender_append_long(JNIEnv * env, jclass param0, jobject param1, jlong param2); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1long(JNIEnv * env, jclass param0, jobject param1, jlong param2); - -void _duckdb_jdbc_appender_append_float(JNIEnv * env, jclass param0, jobject param1, jfloat param2); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1float(JNIEnv * env, jclass param0, jobject param1, jfloat param2); - -void _duckdb_jdbc_appender_append_double(JNIEnv * env, jclass param0, jobject param1, jdouble param2); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1double(JNIEnv * env, jclass param0, jobject param1, jdouble param2); - -void _duckdb_jdbc_appender_append_string(JNIEnv * env, jclass param0, jobject param1, jbyteArray param2); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1string(JNIEnv * env, jclass param0, jobject param1, jbyteArray param2); - -void _duckdb_jdbc_appender_append_bytes(JNIEnv * env, jclass param0, jobject param1, jbyteArray param2); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1bytes(JNIEnv * env, jclass param0, jobject param1, jbyteArray param2); - -void _duckdb_jdbc_appender_append_timestamp(JNIEnv * env, jclass param0, jobject param1, jlong param2); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1timestamp(JNIEnv * env, jclass param0, jobject param1, jlong param2); - -void _duckdb_jdbc_appender_append_decimal(JNIEnv * env, jclass param0, jobject param1, jobject param2); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1decimal(JNIEnv * env, jclass param0, jobject param1, jobject param2); - -void _duckdb_jdbc_appender_append_null(JNIEnv * env, jclass param0, jobject param1); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1appender_1append_1null(JNIEnv * env, jclass param0, jobject param1); - jstring _duckdb_jdbc_get_profiling_information(JNIEnv * env, jclass param0, jobject param1, jobject param2); JNIEXPORT jstring JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1profiling_1information(JNIEnv * env, jclass param0, jobject param1, jobject param2); diff --git a/src/main/java/org/duckdb/DuckDBAppender.java b/src/main/java/org/duckdb/DuckDBAppender.java index 745604d09..a4a25a826 100644 --- a/src/main/java/org/duckdb/DuckDBAppender.java +++ b/src/main/java/org/duckdb/DuckDBAppender.java @@ -89,7 +89,7 @@ public class DuckDBAppender implements AutoCloseable { private final String schema; private final String table; - private ByteBuffer appenderRef; + private DuckDBV2Appender appenderRef; private final Lock appenderRefLock = new ReentrantLock(); private final ByteBuffer chunkRef; @@ -110,7 +110,7 @@ public class DuckDBAppender implements AutoCloseable { this.schema = schema; this.table = table; - ByteBuffer appenderRef = null; + DuckDBV2Appender appenderRef = null; ByteBuffer[] colTypes = null; ByteBuffer chunkRef = null; List cols = null; @@ -131,7 +131,7 @@ public class DuckDBAppender implements AutoCloseable { } } if (null != appenderRef) { - duckdb_appender_destroy(appenderRef); + appenderRef.destroy(); } throw createAppenderException(e.getMessage(), ErrorCode.APPENDER_CONVERSION, e); } @@ -258,16 +258,16 @@ public long flush() throws SQLException { duckdb_data_chunk_set_size(chunkRef, rowIdx); - int appendState = duckdb_append_data_chunk(appenderRef, chunkRef); + int appendState = appenderRef.appendChunk(chunkRef); if (0 != appendState) { - byte[] errorUTF8 = duckdb_appender_error(appenderRef); + byte[] errorUTF8 = appenderRef.error(); String error = strFromUTF8(errorUTF8); throw createSQLException(error, null); } - int flushState = duckdb_appender_flush(appenderRef); + int flushState = appenderRef.flush(); if (0 != flushState) { - byte[] errorUTF8 = duckdb_appender_error(appenderRef); + byte[] errorUTF8 = appenderRef.error(); String error = strFromUTF8(errorUTF8); throw createSQLException(error, null); } @@ -310,8 +310,8 @@ public void close() throws SQLException { col.destroy(); } duckdb_destroy_data_chunk(chunkRef); - duckdb_appender_close(appenderRef); - duckdb_appender_destroy(appenderRef); + appenderRef.close(); + appenderRef.destroy(); // Untrack the appender from parent connection, // if 'closing' flag is set it means that the parent connection itself @@ -964,7 +964,9 @@ public DuckDBAppender appendDefault() throws SQLException { appenderRefLock.lock(); try { checkOpen(); - duckdb_append_default_to_chunk(appenderRef, chunkRef, col.idx, rowIdx); + if (0 != appenderRef.appendDefaultToChunk(chunkRef, col.idx, rowIdx)) { + throw createSQLException(strFromUTF8(appenderRef.error()), null); + } } finally { appenderRefLock.unlock(); } @@ -2262,25 +2264,24 @@ private static String strFromUTF8(byte[] utf8) { // static methods - private static ByteBuffer createAppender(DuckDBConnection conn, String catalog, String schema, String table) + private static DuckDBV2Appender createAppender(DuckDBConnection conn, String catalog, String schema, String table) throws SQLException { conn.checkOpen(); Lock connRefLock = conn.connRefLock; connRefLock.lock(); try { - ByteBuffer[] out = new ByteBuffer[1]; - int state = duckdb_appender_create_ext(conn.connRef, utf8(catalog), utf8(schema), utf8(table), out); - if (0 != state) { + try { + return DuckDBV2Appender.create(conn, catalog, schema, table); + } catch (SQLException e) { throw createSQLException("duckdb_appender_create_ext error", ErrorCode.APPENDER_RAW_ERROR); } - return out[0]; } finally { connRefLock.unlock(); } } - private static ByteBuffer[] readTableTypes(ByteBuffer appenderRef) throws SQLException { - long colCountLong = duckdb_appender_column_count(appenderRef); + private static ByteBuffer[] readTableTypes(DuckDBV2Appender appenderRef) throws SQLException { + long colCountLong = appenderRef.columnCount(); if (colCountLong > Integer.MAX_VALUE || colCountLong < 0) { throw createSQLException("invalid columns count: " + colCountLong, ErrorCode.APPENDER_PARAM); } @@ -2289,7 +2290,7 @@ private static ByteBuffer[] readTableTypes(ByteBuffer appenderRef) throws SQLExc ByteBuffer[] res = new ByteBuffer[colCount]; for (int i = 0; i < colCount; i++) { - ByteBuffer colType = duckdb_appender_column_type(appenderRef, i); + ByteBuffer colType = appenderRef.columnType(i); if (null == colType) { throw createSQLException("cannot get logical type for column: " + i, ErrorCode.APPENDER_CHUNK); } diff --git a/src/main/java/org/duckdb/DuckDBBindings.java b/src/main/java/org/duckdb/DuckDBBindings.java index 10d28475c..57fc799de 100644 --- a/src/main/java/org/duckdb/DuckDBBindings.java +++ b/src/main/java/org/duckdb/DuckDBBindings.java @@ -204,27 +204,6 @@ static native void duckdb_vector_assign_string_elements(ByteBuffer vector, long static native void duckdb_data_chunk_set_size(ByteBuffer chunk, long size); - // appender - - static native int duckdb_appender_create_ext(ByteBuffer connection, byte[] catalog, byte[] schema, byte[] table, - ByteBuffer[] out_appender); - - static native byte[] duckdb_appender_error(ByteBuffer appender); - - static native int duckdb_appender_flush(ByteBuffer appender); - - static native int duckdb_appender_close(ByteBuffer appender); - - static native int duckdb_appender_destroy(ByteBuffer appender); - - static native long duckdb_appender_column_count(ByteBuffer appender); - - static native ByteBuffer duckdb_appender_column_type(ByteBuffer appender, long col_idx); - - static native int duckdb_append_data_chunk(ByteBuffer appender, ByteBuffer chunk); - - static native int duckdb_append_default_to_chunk(ByteBuffer appender, ByteBuffer chunk, long col, long row); - // value static native boolean duckdb_is_null_value(ByteBuffer value); @@ -468,6 +447,35 @@ static native ByteBuffer duckdb_v2_value_create_map(ByteBuffer factory, ByteBuff static native void duckdb_v2_vector_set_size(ByteBuffer vector, long size) throws SQLException; + // appending + + // the returned type is owned by the caller + static native ByteBuffer duckdb_v2_logical_type_copy(ByteBuffer type) throws SQLException; + + static native long duckdb_v2_vector_get_size(ByteBuffer vector) throws SQLException; + + static native ByteBuffer duckdb_v2_column_data_collection_create(ByteBuffer factory, ByteBuffer[] types) + throws SQLException; + + static native void duckdb_v2_column_data_collection_destroy(ByteBuffer collection) throws SQLException; + + static native void duckdb_v2_column_data_collection_clear(ByteBuffer collection) throws SQLException; + + static native long duckdb_v2_column_data_collection_row_count(ByteBuffer collection) throws SQLException; + + static native ByteBuffer duckdb_v2_column_data_collection_append_state_create(ByteBuffer collection) + throws SQLException; + + static native void duckdb_v2_column_data_collection_append_state_destroy(ByteBuffer state) throws SQLException; + + // the chunk is borrowed for the call + static native void duckdb_v2_column_data_collection_append(ByteBuffer collection, ByteBuffer state, + ByteBuffer chunk) throws SQLException; + + // binds the collection to the statement under the name, the collection must outlive the statement executions + static native void duckdb_v2_statement_add_collection(ByteBuffer statement, byte[] name, ByteBuffer collection, + byte[][] column_names) throws SQLException; + // DUCKDB_V2_RESULT_STEP_STATUS static final int RESULT_STEP_WAITING = 0; static final int RESULT_STEP_CHUNK = 1; diff --git a/src/main/java/org/duckdb/DuckDBCore.java b/src/main/java/org/duckdb/DuckDBCore.java index 446517988..cd0f8a74c 100644 --- a/src/main/java/org/duckdb/DuckDBCore.java +++ b/src/main/java/org/duckdb/DuckDBCore.java @@ -337,6 +337,94 @@ static ResultRef executePending(PendingRef ref) throws SQLException { } } + // --------------------------------------------------------------------------------------------------------- + // Internal queries + // --------------------------------------------------------------------------------------------------------- + + /** Parses exactly one statement, the statement is owned by the caller. */ + static ByteBuffer parseSingleStatement(ByteBuffer conn, String sql) throws SQLException { + List statements = parse(conn, sql.getBytes(UTF_8)); + if (statements.size() != 1) { + destroyStatements(statements); + throw invalid("The query must contain exactly one statement"); + } + return statements.get(0); + } + + /** Runs the query and returns the first column of the result as strings, NULL values are null. */ + static List queryStrings(DuckDBConnection connection, String sql) throws SQLException { + connection.queryGate.acquireUninterruptibly(); + try { + ByteBuffer conn = conn(connection.connRef); + ByteBuffer statement = parseSingleStatement(conn, sql); + ByteBuffer result; + try { + result = duckdb_v2_statement_execute(conn, statement, null); + } finally { + duckdb_v2_sql_statement_destroy(statement); + } + try { + List res = new ArrayList<>(); + ByteBuffer chunk; + while ((chunk = duckdb_v2_result_fetch_chunk(result)) != null) { + try { + int rowCount = (int) duckdb_data_chunk_get_size(chunk); + ByteBuffer vec = duckdb_data_chunk_get_vector(chunk, 0); + for (int row = 0; row < rowCount; row++) { + res.add(valueToString(vec, row)); + } + } finally { + duckdb_destroy_data_chunk(chunk); + } + } + return res; + } finally { + duckdb_v2_result_destroy(result); + } + } finally { + connection.queryGate.release(); + } + } + + /** Runs the query and returns the first value of its result, that is owned by the caller. */ + static ByteBuffer queryValue(DuckDBConnection connection, String sql) throws SQLException { + connection.queryGate.acquireUninterruptibly(); + try { + ByteBuffer conn = conn(connection.connRef); + ByteBuffer statement = parseSingleStatement(conn, sql); + ByteBuffer result; + try { + result = duckdb_v2_statement_execute(conn, statement, null); + } finally { + duckdb_v2_sql_statement_destroy(statement); + } + try { + ByteBuffer chunk = duckdb_v2_result_fetch_chunk(result); + if (chunk == null) { + throw invalid("Unable to evaluate the query: " + sql); + } + try { + if (duckdb_data_chunk_get_size(chunk) == 0) { + throw invalid("Unable to evaluate the query: " + sql); + } + ByteBuffer value = duckdb_v2_vector_get_value(duckdb_data_chunk_get_vector(chunk, 0), 0); + // the rest of the result is read to complete the query + ByteBuffer rest; + while ((rest = duckdb_v2_result_fetch_chunk(result)) != null) { + duckdb_destroy_data_chunk(rest); + } + return value; + } finally { + duckdb_destroy_data_chunk(chunk); + } + } finally { + duckdb_v2_result_destroy(result); + } + } finally { + connection.queryGate.release(); + } + } + // --------------------------------------------------------------------------------------------------------- // Execution // --------------------------------------------------------------------------------------------------------- @@ -947,7 +1035,7 @@ private static ByteBuffer parseType(ByteBuffer factory, String text) throws SQLE return duckdb_v2_factory_create_type_from_text(factory, text.getBytes(UTF_8)); } - private static ByteBuffer nullValue(ByteBuffer factory) throws SQLException { + static ByteBuffer nullValue(ByteBuffer factory) throws SQLException { ByteBuffer type = parseType(factory, "NULL"); try { return duckdb_v2_value_create_null(factory, type); diff --git a/src/main/java/org/duckdb/DuckDBNative.java b/src/main/java/org/duckdb/DuckDBNative.java index 71519f549..5ba9b33a0 100644 --- a/src/main/java/org/duckdb/DuckDBNative.java +++ b/src/main/java/org/duckdb/DuckDBNative.java @@ -235,15 +235,6 @@ static long duckdb_jdbc_arrow_stream(DuckDBCore.ResultRef res_ref, ByteBuffer co static native void duckdb_jdbc_arrow_close_streams(ByteBuffer conn_ref); - static native ByteBuffer duckdb_jdbc_create_appender(ByteBuffer conn_ref, byte[] schema_name, byte[] table_name) - throws SQLException; - - static native void duckdb_jdbc_appender_begin_row(ByteBuffer appender_ref) throws SQLException; - - static native void duckdb_jdbc_appender_end_row(ByteBuffer appender_ref) throws SQLException; - - static native void duckdb_jdbc_appender_flush(ByteBuffer appender_ref) throws SQLException; - static void duckdb_jdbc_interrupt(ByteBuffer conn_ref) throws SQLException { DuckDBBindings.duckdb_v2_connection_interrupt(DuckDBBindings.duckdb_v2_connection_from_ref(conn_ref)); } @@ -252,33 +243,6 @@ static QueryProgress duckdb_jdbc_query_progress(ByteBuffer conn_ref) throws SQLE return DuckDBBindings.duckdb_v2_connection_progress_get(DuckDBBindings.duckdb_v2_connection_from_ref(conn_ref)); } - static native void duckdb_jdbc_appender_close(ByteBuffer appender_ref) throws SQLException; - - static native void duckdb_jdbc_appender_append_boolean(ByteBuffer appender_ref, boolean value) throws SQLException; - - static native void duckdb_jdbc_appender_append_byte(ByteBuffer appender_ref, byte value) throws SQLException; - - static native void duckdb_jdbc_appender_append_short(ByteBuffer appender_ref, short value) throws SQLException; - - static native void duckdb_jdbc_appender_append_int(ByteBuffer appender_ref, int value) throws SQLException; - - static native void duckdb_jdbc_appender_append_long(ByteBuffer appender_ref, long value) throws SQLException; - - static native void duckdb_jdbc_appender_append_float(ByteBuffer appender_ref, float value) throws SQLException; - - static native void duckdb_jdbc_appender_append_double(ByteBuffer appender_ref, double value) throws SQLException; - - static native void duckdb_jdbc_appender_append_string(ByteBuffer appender_ref, byte[] value) throws SQLException; - - static native void duckdb_jdbc_appender_append_bytes(ByteBuffer appender_ref, byte[] value) throws SQLException; - - static native void duckdb_jdbc_appender_append_timestamp(ByteBuffer appender_ref, long value) throws SQLException; - - static native void duckdb_jdbc_appender_append_decimal(ByteBuffer appender_ref, BigDecimal value) - throws SQLException; - - static native void duckdb_jdbc_appender_append_null(ByteBuffer appender_ref) throws SQLException; - protected static native String duckdb_jdbc_get_profiling_information(ByteBuffer conn_ref, ProfilerPrintFormat format) throws SQLException; diff --git a/src/main/java/org/duckdb/DuckDBSingleValueAppender.java b/src/main/java/org/duckdb/DuckDBSingleValueAppender.java index 8f25f2867..c1f4ca210 100644 --- a/src/main/java/org/duckdb/DuckDBSingleValueAppender.java +++ b/src/main/java/org/duckdb/DuckDBSingleValueAppender.java @@ -1,104 +1,218 @@ package org.duckdb; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.duckdb.DuckDBBindings.*; import static org.duckdb.JdbcUtils.createSQLException; import java.math.BigDecimal; import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; import java.sql.SQLException; import java.time.LocalDateTime; +/** + * An appender of the rows that are appended one value at a time. The values are collected into a data chunk that is + * appended to the table when it is full or the appender is flushed. + */ @Deprecated public class DuckDBSingleValueAppender implements AutoCloseable { - protected ByteBuffer appender_ref = null; + private final DuckDBConnection conn; + private DuckDBV2Appender appender; + private ByteBuffer chunk; + private ByteBuffer[] vectors; + private long capacity; + // the index of the row that is being appended, and of the column to append to + private long row = 0; + private int column = 0; public DuckDBSingleValueAppender(DuckDBConnection con, String schemaName, String tableName) throws SQLException { if (con == null) { throw createSQLException("Invalid connection", ErrorCode.SINGLE_VALUE_BAD_CONNECTION); } - appender_ref = DuckDBNative.duckdb_jdbc_create_appender( - con.connRef, schemaName.getBytes(StandardCharsets.UTF_8), tableName.getBytes(StandardCharsets.UTF_8)); + this.conn = con; + String schema = schemaName == null || schemaName.isEmpty() ? null : schemaName; + appender = DuckDBV2Appender.create(con, null, schema, tableName); + + int columnCount = (int) appender.columnCount(); + ByteBuffer[] types = new ByteBuffer[columnCount]; + try { + for (int i = 0; i < columnCount; i++) { + types[i] = appender.columnType(i); + } + chunk = duckdb_create_data_chunk(types); + } finally { + for (ByteBuffer type : types) { + if (type != null) { + duckdb_destroy_logical_type(type); + } + } + } + vectors = new ByteBuffer[columnCount]; + for (int i = 0; i < columnCount; i++) { + vectors[i] = duckdb_data_chunk_get_vector(chunk, i); + } + capacity = duckdb_vector_size(); + resetChunk(); + } + + private void checkOpen() throws SQLException { + if (appender == null) { + throw new SQLException("Invalid Input Error: Invalid appender"); + } + } + + private void resetChunk() throws SQLException { + duckdb_data_chunk_reset(chunk); + for (ByteBuffer vec : vectors) { + duckdb_v2_vector_set_size(vec, capacity); + } + row = 0; + column = 0; + } + + // Appends the collected rows to the buffer of the appender + private void collect() throws SQLException { + if (row == 0) { + return; + } + for (ByteBuffer vec : vectors) { + duckdb_v2_vector_set_size(vec, row); + } + duckdb_data_chunk_set_size(chunk, row); + int state = appender.appendChunk(chunk); + String error = new String(appender.error(), UTF_8); + resetChunk(); + if (state != 0) { + throw new SQLException(error); + } + } + + private void flushAppender() throws SQLException { + if (appender.flush() != 0) { + throw new SQLException(new String(appender.error(), UTF_8)); + } } public void beginRow() throws SQLException { - DuckDBNative.duckdb_jdbc_appender_begin_row(appender_ref); + // the values are appended to the columns in order, no matter how many times the row is begun + checkOpen(); } public void endRow() throws SQLException { - DuckDBNative.duckdb_jdbc_appender_end_row(appender_ref); + checkOpen(); + if (column != vectors.length) { + // the values of the incomplete row are dropped + column = 0; + throw new SQLException("Invalid Input Error: Call to EndRow before all columns have been appended to"); + } + column = 0; + row++; + if (row == capacity) { + collect(); + } } public void flush() throws SQLException { - DuckDBNative.duckdb_jdbc_appender_flush(appender_ref); + checkOpen(); + collect(); + flushAppender(); + } + + // Appends the value to the column, the value is cast to the type of the column, the value is destroyed + private void appendValue(ByteBuffer value) throws SQLException { + try { + if (column >= vectors.length) { + throw new SQLException("Invalid Input Error: Too many appends for chunk!"); + } + duckdb_v2_vector_set_value(vectors[column], row, value); + column++; + } finally { + duckdb_v2_value_destroy(value); + } + } + + private ByteBuffer factory() throws SQLException { + return duckdb_v2_connection_get_factory(duckdb_v2_connection_from_ref(conn.connRef)); + } + + private void appendObject(Object value) throws SQLException { + checkOpen(); + appendValue(DuckDBCore.toValue(factory(), value)); } public void append(boolean value) throws SQLException { - DuckDBNative.duckdb_jdbc_appender_append_boolean(appender_ref, value); + appendObject(value); } public void append(byte value) throws SQLException { - DuckDBNative.duckdb_jdbc_appender_append_byte(appender_ref, value); + appendObject(value); } public void append(short value) throws SQLException { - DuckDBNative.duckdb_jdbc_appender_append_short(appender_ref, value); + appendObject(value); } public void append(int value) throws SQLException { - DuckDBNative.duckdb_jdbc_appender_append_int(appender_ref, value); + appendObject(value); } public void append(long value) throws SQLException { - DuckDBNative.duckdb_jdbc_appender_append_long(appender_ref, value); + appendObject(value); } // New naming schema for object params to keep compatibility with calling "append(null)" public void appendLocalDateTime(LocalDateTime value) throws SQLException { + checkOpen(); if (value == null) { - DuckDBNative.duckdb_jdbc_appender_append_null(appender_ref); + appendValue(DuckDBCore.nullValue(factory())); } else { long timeInMicros = DuckDBTimestamp.localDateTime2Micros(value); - DuckDBNative.duckdb_jdbc_appender_append_timestamp(appender_ref, timeInMicros); + appendValue(duckdb_v2_value_create_timestamp(factory(), timeInMicros)); } } public void appendBigDecimal(BigDecimal value) throws SQLException { - if (value == null) { - DuckDBNative.duckdb_jdbc_appender_append_null(appender_ref); - } else { - DuckDBNative.duckdb_jdbc_appender_append_decimal(appender_ref, value); - } + appendObject(value); } public void append(float value) throws SQLException { - DuckDBNative.duckdb_jdbc_appender_append_float(appender_ref, value); + appendObject(value); } public void append(double value) throws SQLException { - DuckDBNative.duckdb_jdbc_appender_append_double(appender_ref, value); + appendObject(value); } public void append(String value) throws SQLException { - if (value == null) { - DuckDBNative.duckdb_jdbc_appender_append_null(appender_ref); - } else { - DuckDBNative.duckdb_jdbc_appender_append_string(appender_ref, value.getBytes(StandardCharsets.UTF_8)); - } + appendObject(value); } public void append(byte[] value) throws SQLException { - if (value == null) { - DuckDBNative.duckdb_jdbc_appender_append_null(appender_ref); - } else { - DuckDBNative.duckdb_jdbc_appender_append_bytes(appender_ref, value); - } + appendObject(value); } public synchronized void close() throws SQLException { - if (appender_ref != null) { - DuckDBNative.duckdb_jdbc_appender_close(appender_ref); - appender_ref = null; + if (appender == null) { + return; + } + DuckDBV2Appender closing = appender; + appender = null; + try { + if (row > 0) { + for (ByteBuffer vec : vectors) { + duckdb_v2_vector_set_size(vec, row); + } + duckdb_data_chunk_set_size(chunk, row); + if (closing.appendChunk(chunk) != 0) { + throw new SQLException(new String(closing.error(), UTF_8)); + } + } + if (closing.close() != 0) { + throw new SQLException(new String(closing.error(), UTF_8)); + } + } finally { + duckdb_destroy_data_chunk(chunk); + closing.destroy(); } } } diff --git a/src/main/java/org/duckdb/DuckDBV2Appender.java b/src/main/java/org/duckdb/DuckDBV2Appender.java new file mode 100644 index 000000000..f57beef6f --- /dev/null +++ b/src/main/java/org/duckdb/DuckDBV2Appender.java @@ -0,0 +1,274 @@ +package org.duckdb; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.duckdb.DuckDBBindings.*; + +import java.nio.ByteBuffer; +import java.sql.SQLException; +import java.util.List; + +/** + * Appends the data chunks to a table, using the C API v2 that has no appender: the chunks are collected into a + * column data collection, that is read by a prepared {@code INSERT INTO table SELECT * FROM }. + */ +final class DuckDBV2Appender { + private static final byte[] BUFFER_NAME = "__duckdb_appender_buffer".getBytes(UTF_8); + + private final DuckDBConnection conn; + private final String catalog; + private final String schema; + private final String table; + private final ByteBuffer[] types; + private ByteBuffer statement; + private ByteBuffer collection; + private ByteBuffer appendState; + // the SQL texts of the default values of the columns, they are loaded when the first default is appended + private List defaults; + private String error = ""; + + private DuckDBV2Appender(DuckDBConnection conn, String catalog, String schema, String table, ByteBuffer[] types) { + this.conn = conn; + this.catalog = catalog; + this.schema = schema; + this.table = table; + this.types = types; + } + + static String quoteIdentifier(String name) { + return "\"" + name.replace("\"", "\"\"") + "\""; + } + + static String quoteLiteral(String value) { + return "'" + value.replace("'", "''") + "'"; + } + + private static ByteBuffer parseSingle(ByteBuffer connHandle, String sql) throws SQLException { + return DuckDBCore.parseSingleStatement(connHandle, sql); + } + + /** Creates an appender to the table, the catalog and the schema can be null. */ + static DuckDBV2Appender create(DuckDBConnection conn, String catalog, String schema, String table) + throws SQLException { + StringBuilder qualified = new StringBuilder(); + if (catalog != null) { + qualified.append(quoteIdentifier(catalog)).append('.'); + } + if (schema != null) { + qualified.append(quoteIdentifier(schema)).append('.'); + } + qualified.append(quoteIdentifier(table)); + + ByteBuffer connHandle = duckdb_v2_connection_from_ref(conn.connRef); + ByteBuffer factory = duckdb_v2_connection_get_factory(connHandle); + + // the columns of the table: binding reports them without reading a row + ByteBuffer probe = parseSingle(connHandle, "SELECT * FROM " + qualified); + ByteBuffer[] schemas = null; + ByteBuffer[] types; + String[] names; + try { + schemas = duckdb_v2_statement_bind(connHandle, probe); + int count = (int) duckdb_v2_schema_get_count(schemas[0]); + if (count == 0) { + throw new SQLException("Invalid Input Error: table " + qualified + " has no columns to append to"); + } + types = new ByteBuffer[count]; + names = new String[count]; + try { + for (int i = 0; i < count; i++) { + types[i] = duckdb_v2_logical_type_copy(duckdb_v2_schema_get_field_type(schemas[0], i)); + names[i] = new String(duckdb_v2_schema_get_field_name(schemas[0], i), UTF_8); + } + } catch (SQLException e) { + destroyTypes(types); + throw e; + } + } finally { + if (schemas != null) { + duckdb_v2_schema_destroy(schemas[0]); + if (schemas[1] != null) { + duckdb_v2_schema_destroy(schemas[1]); + } + } + duckdb_v2_sql_statement_destroy(probe); + } + + StringBuilder columns = new StringBuilder(); + for (int i = 0; i < names.length; i++) { + if (i > 0) { + columns.append(", "); + } + columns.append(quoteIdentifier(names[i])); + } + String insert = + "INSERT INTO " + qualified + " (" + columns + ") SELECT * FROM " + new String(BUFFER_NAME, UTF_8); + + DuckDBV2Appender appender = new DuckDBV2Appender(conn, catalog, schema, table, types); + boolean ok = false; + try { + appender.statement = parseSingle(connHandle, insert); + appender.collection = duckdb_v2_column_data_collection_create(factory, types); + appender.appendState = duckdb_v2_column_data_collection_append_state_create(appender.collection); + byte[][] nameBytes = new byte[names.length][]; + for (int i = 0; i < names.length; i++) { + nameBytes[i] = names[i].getBytes(UTF_8); + } + duckdb_v2_statement_add_collection(appender.statement, BUFFER_NAME, appender.collection, nameBytes); + ok = true; + return appender; + } finally { + if (!ok) { + appender.destroy(); + } + } + } + + private static void destroyTypes(ByteBuffer[] types) { + for (ByteBuffer type : types) { + if (type != null) { + duckdb_destroy_logical_type(type); + } + } + } + + long columnCount() { + return types.length; + } + + /** Returns a copy of the type of the column, that is owned by the caller, or null for an invalid column. */ + ByteBuffer columnType(long idx) throws SQLException { + if (idx < 0 || idx >= types.length) { + return null; + } + return duckdb_v2_logical_type_copy(types[(int) idx]); + } + + /** The message of the last failure. */ + byte[] error() { + return error.getBytes(UTF_8); + } + + private int fail(SQLException e) { + error = e.getMessage() == null ? e.toString() : e.getMessage(); + return 1; + } + + /** Appends the chunk (that is borrowed for the call) to the buffer, returns 0 on success. */ + int appendChunk(ByteBuffer chunk) { + try { + duckdb_v2_column_data_collection_append(collection, appendState, chunk); + return 0; + } catch (SQLException e) { + return fail(e); + } + } + + private void resetBuffer() throws SQLException { + // the append state references the segments that are released by the clear + duckdb_v2_column_data_collection_append_state_destroy(appendState); + appendState = null; + duckdb_v2_column_data_collection_clear(collection); + appendState = duckdb_v2_column_data_collection_append_state_create(collection); + } + + /** Appends the buffered rows to the table, returns 0 on success. */ + int flush() { + try { + if (duckdb_v2_column_data_collection_row_count(collection) == 0) { + return 0; + } + conn.queryGate.acquireUninterruptibly(); + try { + ByteBuffer connHandle = duckdb_v2_connection_from_ref(conn.connRef); + ByteBuffer result = duckdb_v2_statement_execute(connHandle, statement, null); + try { + duckdb_v2_result_drain(result); + } finally { + duckdb_v2_result_destroy(result); + } + } finally { + conn.queryGate.release(); + } + resetBuffer(); + return 0; + } catch (SQLException e) { + int state = fail(e); + try { + // a failed flush drops the rows, a retry must not run the same failing statement over them + resetBuffer(); + } catch (SQLException ignored) { + // nothing else can be done + } + return state; + } + } + + int close() { + return flush(); + } + + /** Appends the default value of the column to the row of the chunk, returns 0 on success. */ + int appendDefaultToChunk(ByteBuffer chunk, long col, long row) { + try { + if (defaults == null) { + // the default values of all columns of the table, in the order of the columns + String sql = "SELECT column_default FROM duckdb_columns() WHERE table_name = " + quoteLiteral(table); + if (schema != null) { + sql += " AND schema_name = " + quoteLiteral(schema); + } + if (catalog != null) { + sql += " AND database_name = " + quoteLiteral(catalog); + } + sql += " ORDER BY column_index"; + defaults = DuckDBCore.queryStrings(conn, sql); + } + ByteBuffer vec = duckdb_data_chunk_get_vector(chunk, col); + // the size of the vector is set by the caller when the chunk is complete + if (duckdb_v2_vector_get_size(vec) <= row) { + duckdb_v2_vector_set_size(vec, row + 1); + } + String defaultSql = col < defaults.size() ? defaults.get((int) col) : null; + ByteBuffer value; + if (defaultSql != null) { + // the default value is an expression, that is evaluated every time as it can be volatile + value = DuckDBCore.queryValue(conn, "SELECT " + defaultSql); + } else { + // a column without a default value gets the NULL default + value = + DuckDBCore.nullValue(duckdb_v2_connection_get_factory(duckdb_v2_connection_from_ref(conn.connRef))); + } + try { + duckdb_v2_vector_set_value(vec, row, value); + } finally { + duckdb_v2_value_destroy(value); + } + return 0; + } catch (SQLException e) { + return fail(e); + } + } + + /** Releases the resources of the appender, the buffered rows are not appended. */ + void destroy() { + try { + if (appendState != null) { + duckdb_v2_column_data_collection_append_state_destroy(appendState); + appendState = null; + } + if (statement != null) { + duckdb_v2_sql_statement_destroy(statement); + statement = null; + } + if (collection != null) { + duckdb_v2_column_data_collection_destroy(collection); + collection = null; + } + } catch (SQLException e) { + // nothing else can be done + } + destroyTypes(types); + for (int i = 0; i < types.length; i++) { + types[i] = null; + } + } +} diff --git a/src/test/java/org/duckdb/TestBindings.java b/src/test/java/org/duckdb/TestBindings.java index 56512c00e..d96507e35 100644 --- a/src/test/java/org/duckdb/TestBindings.java +++ b/src/test/java/org/duckdb/TestBindings.java @@ -559,23 +559,18 @@ public static void test_bindings_data_chunk() throws Exception { duckdb_destroy_logical_type(intType); } - public static void test_bindings_appender() throws Exception { + public static void test_v2_appender() throws Exception { try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); Statement stmt = conn.createStatement()) { stmt.execute("CREATE TABLE tab1(col1 INT, col2 VARCHAR)"); - ByteBuffer[] out = new ByteBuffer[1]; - int state = - duckdb_appender_create_ext(conn.connRef, "memory".getBytes(UTF_8), null, "tab1".getBytes(UTF_8), out); - - assertEquals(state, 0); - ByteBuffer appender = out[0]; + DuckDBV2Appender appender = DuckDBV2Appender.create(conn, "memory", null, "tab1"); assertNotNull(appender); - assertEquals(duckdb_appender_column_count(appender), 2L); - ByteBuffer col1Type = duckdb_appender_column_type(appender, 0); + assertEquals(appender.columnCount(), 2L); + ByteBuffer col1Type = appender.columnType(0); assertEquals(duckdb_get_type_id(col1Type), DUCKDB_TYPE_INTEGER.typeId); - ByteBuffer col2Type = duckdb_appender_column_type(appender, 1); + ByteBuffer col2Type = appender.columnType(1); assertEquals(duckdb_get_type_id(col2Type), DUCKDB_TYPE_VARCHAR.typeId); ByteBuffer chunk = duckdb_create_data_chunk(new ByteBuffer[] {col1Type, col2Type}); @@ -585,18 +580,18 @@ public static void test_bindings_appender() throws Exception { ByteBuffer col1Data = duckdb_vector_get_data(col1Vec, duckdb_vector_size() * 4); col1Data.putInt(42); col1Data.putInt(43); - duckdb_append_default_to_chunk(appender, chunk, 0, 2); + assertEquals(appender.appendDefaultToChunk(chunk, 0, 2), 0); ByteBuffer col2Vec = duckdb_data_chunk_get_vector(chunk, 1); duckdb_vector_ensure_validity_writable(col2Vec); duckdb_vector_assign_string_element_len(col2Vec, 0, "foo".getBytes(UTF_8)); duckdb_vector_assign_string_element_len(col2Vec, 1, "bar".getBytes(UTF_8)); - duckdb_append_default_to_chunk(appender, chunk, 1, 2); + assertEquals(appender.appendDefaultToChunk(chunk, 1, 2), 0); duckdb_data_chunk_set_size(chunk, 3); - assertEquals(duckdb_append_data_chunk(appender, chunk), 0); - assertEquals(duckdb_appender_flush(appender), 0); - assertNull(duckdb_appender_error(appender)); + assertEquals(appender.appendChunk(chunk), 0); + assertEquals(appender.flush(), 0); + assertEquals(appender.error().length, 0); try (ResultSet rs = stmt.executeQuery("SELECT * FROM tab1 ORDER BY col1")) { assertTrue(rs.next()); @@ -611,8 +606,8 @@ public static void test_bindings_appender() throws Exception { assertFalse(rs.next()); } - assertEquals(duckdb_appender_close(appender), 0); - assertEquals(duckdb_appender_destroy(appender), 0); + assertEquals(appender.close(), 0); + appender.destroy(); duckdb_destroy_data_chunk(chunk); duckdb_destroy_logical_type(col1Type); duckdb_destroy_logical_type(col2Type); @@ -625,29 +620,25 @@ public static void test_bindings_decimal_type() throws Exception { stmt.execute( "CREATE TABLE tab1(dec2 DECIMAL(3,1), dec4 DECIMAL(7,3), dec8 DECIMAL(15,5), dec16 DECIMAL(30,10))"); - ByteBuffer[] out = new ByteBuffer[1]; - int state = - duckdb_appender_create_ext(conn.connRef, "memory".getBytes(UTF_8), null, "tab1".getBytes(UTF_8), out); - assertEquals(state, 0); - ByteBuffer appender = out[0]; + DuckDBV2Appender appender = DuckDBV2Appender.create(conn, "memory", null, "tab1"); assertNotNull(appender); - ByteBuffer dec2Type = duckdb_appender_column_type(appender, 0); + ByteBuffer dec2Type = appender.columnType(0); assertEquals(duckdb_decimal_width(dec2Type), 3); assertEquals(duckdb_decimal_scale(dec2Type), 1); assertEquals(duckdb_decimal_internal_type(dec2Type), DUCKDB_TYPE_SMALLINT.typeId); - ByteBuffer dec4Type = duckdb_appender_column_type(appender, 1); + ByteBuffer dec4Type = appender.columnType(1); assertEquals(duckdb_decimal_width(dec4Type), 7); assertEquals(duckdb_decimal_scale(dec4Type), 3); assertEquals(duckdb_decimal_internal_type(dec4Type), DUCKDB_TYPE_INTEGER.typeId); - ByteBuffer dec8Type = duckdb_appender_column_type(appender, 2); + ByteBuffer dec8Type = appender.columnType(2); assertEquals(duckdb_decimal_width(dec8Type), 15); assertEquals(duckdb_decimal_scale(dec8Type), 5); assertEquals(duckdb_decimal_internal_type(dec8Type), DUCKDB_TYPE_BIGINT.typeId); - ByteBuffer dec16Type = duckdb_appender_column_type(appender, 3); + ByteBuffer dec16Type = appender.columnType(3); assertEquals(duckdb_decimal_width(dec16Type), 30); assertEquals(duckdb_decimal_scale(dec16Type), 10); assertEquals(duckdb_decimal_internal_type(dec16Type), DUCKDB_TYPE_HUGEINT.typeId); @@ -656,8 +647,8 @@ public static void test_bindings_decimal_type() throws Exception { duckdb_destroy_logical_type(dec8Type); duckdb_destroy_logical_type(dec4Type); duckdb_destroy_logical_type(dec2Type); - assertEquals(duckdb_appender_close(appender), 0); - assertEquals(duckdb_appender_destroy(appender), 0); + assertEquals(appender.close(), 0); + appender.destroy(); } } @@ -675,14 +666,10 @@ public static void test_bindings_enum_type() throws Exception { stmt.execute("CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');"); stmt.execute("CREATE TABLE tab1(col1 mood)"); - ByteBuffer[] out = new ByteBuffer[1]; - int state = - duckdb_appender_create_ext(conn.connRef, "memory".getBytes(UTF_8), null, "tab1".getBytes(UTF_8), out); - assertEquals(state, 0); - ByteBuffer appender = out[0]; + DuckDBV2Appender appender = DuckDBV2Appender.create(conn, "memory", null, "tab1"); assertNotNull(appender); - ByteBuffer enumType = duckdb_appender_column_type(appender, 0); + ByteBuffer enumType = appender.columnType(0); assertEquals(duckdb_enum_internal_type(enumType), DUCKDB_TYPE_UTINYINT.typeId); assertEquals(duckdb_enum_dictionary_size(enumType), 3L); assertEquals(duckdb_enum_dictionary_value(enumType, 0), "sad".getBytes(UTF_8)); From dc721fac4041534a054b3ccec96db4b8e368aecd Mon Sep 17 00:00:00 2001 From: Robinho-MR Date: Fri, 27 Nov 2026 15:24:32 +0000 Subject: [PATCH 06/21] Implement the startup, connections and Arrow in Java on top of the C API v2 --- CMakeLists.txt | 4 +- CMakeLists.txt.in | 4 +- duckdb_java.def | 47 +- duckdb_java.exp | 47 +- duckdb_java.map | 47 +- src/jni/arrow.cpp | 184 ------ src/jni/arrow.hpp | 75 --- src/jni/arrow_export.cpp | 578 ++++++++++++++++++ src/jni/bindings_v2.cpp | 359 ++++++++++- src/jni/config.cpp | 164 ----- src/jni/config.hpp | 8 - src/jni/duckdb_java.cpp | 222 +------ src/jni/functions.cpp | 165 +---- src/jni/functions.hpp | 70 +-- src/jni/holders.cpp | 76 +-- src/jni/holders.hpp | 91 +-- src/jni/types.cpp | 261 -------- src/jni/types.hpp | 11 - src/main/java/org/duckdb/DuckDBBindings.java | 108 +++- .../java/org/duckdb/DuckDBConnection.java | 39 +- src/main/java/org/duckdb/DuckDBCore.java | 154 ++++- src/main/java/org/duckdb/DuckDBDriver.java | 16 +- src/main/java/org/duckdb/DuckDBInstances.java | 347 +++++++++++ src/main/java/org/duckdb/DuckDBNative.java | 50 +- src/main/java/org/duckdb/DuckDBResultSet.java | 4 +- .../org/duckdb/DuckDBSingleValueAppender.java | 2 +- .../java/org/duckdb/DuckDBV2Appender.java | 7 +- src/test/external/TestArrow.java | 10 +- 28 files changed, 1706 insertions(+), 1444 deletions(-) delete mode 100644 src/jni/arrow.cpp delete mode 100644 src/jni/arrow.hpp create mode 100644 src/jni/arrow_export.cpp delete mode 100644 src/jni/config.cpp delete mode 100644 src/jni/config.hpp delete mode 100644 src/jni/types.cpp delete mode 100644 src/jni/types.hpp create mode 100644 src/main/java/org/duckdb/DuckDBInstances.java diff --git a/CMakeLists.txt b/CMakeLists.txt index 2a295f8fe..b49e3eda9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -659,7 +659,6 @@ if(JEMALLOC_ENABLED) endif() add_library(duckdb_java SHARED - src/jni/arrow.cpp src/jni/bindings_common.cpp src/jni/bindings_data_chunk.cpp src/jni/bindings_logical_type.cpp @@ -668,17 +667,16 @@ add_library(duckdb_java SHARED src/jni/bindings_table_function.cpp src/jni/bindings_table_function_bind.cpp src/jni/bindings_table_function_init.cpp + src/jni/arrow_export.cpp src/jni/bindings_v2.cpp src/jni/bindings_validity.cpp src/jni/bindings_vector.cpp src/jni/bindings_value.cpp src/jni/capi_v2.cpp - src/jni/config.cpp src/jni/duckdb_java.cpp src/jni/functions.cpp src/jni/holders.cpp src/jni/refs.cpp - src/jni/types.cpp src/jni/util.cpp ${DUCKDB_SRC_FILES}) diff --git a/CMakeLists.txt.in b/CMakeLists.txt.in index a9c9a7a76..0c812cac5 100644 --- a/CMakeLists.txt.in +++ b/CMakeLists.txt.in @@ -138,7 +138,6 @@ if(JEMALLOC_ENABLED) endif() add_library(duckdb_java SHARED - src/jni/arrow.cpp src/jni/bindings_common.cpp src/jni/bindings_data_chunk.cpp src/jni/bindings_logical_type.cpp @@ -147,17 +146,16 @@ add_library(duckdb_java SHARED src/jni/bindings_table_function.cpp src/jni/bindings_table_function_bind.cpp src/jni/bindings_table_function_init.cpp + src/jni/arrow_export.cpp src/jni/bindings_v2.cpp src/jni/bindings_validity.cpp src/jni/bindings_vector.cpp src/jni/bindings_value.cpp src/jni/capi_v2.cpp - src/jni/config.cpp src/jni/duckdb_java.cpp src/jni/functions.cpp src/jni/holders.cpp src/jni/refs.cpp - src/jni/types.cpp src/jni/util.cpp ${DUCKDB_SRC_FILES}) diff --git a/duckdb_java.def b/duckdb_java.def index 4fb0bdec7..4668b96ce 100644 --- a/duckdb_java.def +++ b/duckdb_java.def @@ -4,22 +4,7 @@ EXPORTS JNI_OnLoad JNI_OnUnload -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1close_1streams -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1register -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1connect -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1create_1db_1ref -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1destroy_1db_1ref -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1db_1address -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1disconnect -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1fetch_1size -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1auto_1commit -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1catalog Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1profiling_1information -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1schema -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1auto_1commit -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1catalog -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1schema -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1startup Java_org_duckdb_DuckDBBindings_duckdb_1vector_1size Java_org_duckdb_DuckDBBindings_duckdb_1create_1scalar_1function @@ -146,7 +131,6 @@ Java_org_duckdb_DuckDBBindings_duckdb_1column_1count Java_org_duckdb_DuckDBBindings_duckdb_1result_1error Java_org_duckdb_DuckDBBindings_duckdb_1v2_1chunked_1result_1create Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1value -Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1from_1ref Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1config Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1factory Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1interrupt @@ -219,6 +203,37 @@ Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1row_1count Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1copy Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1add_1collection Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1size +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1by_1index +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1count +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1value_1scoped +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1set_1option_1text +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1set_1option_1value +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1create +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1destroy +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1register_1custom_1option +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1create +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1destroy +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1default_1scope +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1default_1value +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1description +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1name +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1supports_1scope +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1type +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1environment_1create +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1environment_1destroy +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1attach +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1create_1with_1options +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1destroy +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1get_1config +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1open_1shared +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1option_1destroy +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1option_1get_1name +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1option_1supports_1scope +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1close_1streams +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1export_1stream +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1scan_1function +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1stream +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1release_1stream ; ADBC entry point duckdb_adbc_init diff --git a/duckdb_java.exp b/duckdb_java.exp index e568398af..b2b08a5f2 100644 --- a/duckdb_java.exp +++ b/duckdb_java.exp @@ -1,22 +1,7 @@ _JNI_OnLoad _JNI_OnUnload -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1close_1streams -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1register -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1connect -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1create_1db_1ref -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1destroy_1db_1ref -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1db_1address -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1disconnect -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1fetch_1size -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1auto_1commit -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1catalog _Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1profiling_1information -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1schema -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1auto_1commit -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1catalog -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1schema -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1startup _Java_org_duckdb_DuckDBBindings_duckdb_1vector_1size _Java_org_duckdb_DuckDBBindings_duckdb_1create_1scalar_1function @@ -143,7 +128,6 @@ _Java_org_duckdb_DuckDBBindings_duckdb_1column_1count _Java_org_duckdb_DuckDBBindings_duckdb_1result_1error _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1chunked_1result_1create _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1value -_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1from_1ref _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1config _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1factory _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1interrupt @@ -216,6 +200,37 @@ _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1row_1count _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1copy _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1add_1collection _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1size +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1by_1index +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1count +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1value_1scoped +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1set_1option_1text +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1set_1option_1value +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1create +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1destroy +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1register_1custom_1option +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1create +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1destroy +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1default_1scope +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1default_1value +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1description +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1name +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1supports_1scope +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1type +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1environment_1create +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1environment_1destroy +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1attach +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1create_1with_1options +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1destroy +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1get_1config +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1open_1shared +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1option_1destroy +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1option_1get_1name +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1option_1supports_1scope +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1close_1streams +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1export_1stream +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1scan_1function +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1stream +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1release_1stream # ADBC entry point _duckdb_adbc_init diff --git a/duckdb_java.map b/duckdb_java.map index 4e8044395..9191c9174 100644 --- a/duckdb_java.map +++ b/duckdb_java.map @@ -3,22 +3,7 @@ DUCKDB_JAVA { JNI_OnLoad; JNI_OnUnload; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1close_1streams; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1register; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1connect; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1create_1db_1ref; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1destroy_1db_1ref; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1db_1address; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1disconnect; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1fetch_1size; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1auto_1commit; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1catalog; Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1profiling_1information; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1schema; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1auto_1commit; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1catalog; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1schema; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1startup; Java_org_duckdb_DuckDBBindings_duckdb_1vector_1size; Java_org_duckdb_DuckDBBindings_duckdb_1create_1scalar_1function; @@ -145,7 +130,6 @@ DUCKDB_JAVA { Java_org_duckdb_DuckDBBindings_duckdb_1result_1error; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1chunked_1result_1create; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1value; - Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1from_1ref; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1config; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1factory; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1interrupt; @@ -218,6 +202,37 @@ DUCKDB_JAVA { Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1copy; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1add_1collection; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1size; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1by_1index; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1count; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1value_1scoped; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1set_1option_1text; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1set_1option_1value; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1create; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1destroy; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1register_1custom_1option; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1create; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1destroy; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1default_1scope; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1default_1value; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1description; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1name; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1supports_1scope; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1type; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1environment_1create; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1environment_1destroy; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1attach; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1create_1with_1options; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1destroy; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1get_1config; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1open_1shared; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1option_1destroy; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1option_1get_1name; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1option_1supports_1scope; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1close_1streams; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1export_1stream; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1scan_1function; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1stream; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1release_1stream; /* ADBC entry point */ duckdb_adbc_init; diff --git a/src/jni/arrow.cpp b/src/jni/arrow.cpp deleted file mode 100644 index ce74570b3..000000000 --- a/src/jni/arrow.cpp +++ /dev/null @@ -1,184 +0,0 @@ -#include "arrow.hpp" - -#include "duckdb/common/arrow/arrow_appender.hpp" -#include "duckdb/common/arrow/arrow_converter.hpp" -#include "duckdb/function/table/arrow/arrow_duck_schema.hpp" - -using namespace duckdb; - -JavaResultArrowStream::JavaResultArrowStream(duckdb::unique_ptr res_p, - duckdb::unique_ptr> stream_p, idx_t batch_size_p) - : res(std::move(res_p)), res_stream(std::move(stream_p)), batch_size(batch_size_p) { - if (res) { - types = res->GetTypes(); - names = IdentifiersToStrings(res->GetNames()); - properties = res->client_properties; - } else { - types = res_stream->GetTypes(); - names = IdentifiersToStrings(res_stream->GetNames()); - properties = res_stream->GetClientProperties(); - } - if (properties.client_context) { - extension_types = ArrowTypeExtensionData::GetExtensionTypes(*properties.client_context, types); - } -} - -void JavaResultArrowStream::Close() { - std::lock_guard guard(lock); - closed = true; - chunk = nullptr; - res = nullptr; - res_stream = nullptr; -} - -ArrowArrayStream *JavaResultArrowStream::Export(duckdb::shared_ptr state) { - auto exported = new Exported(); - exported->state = std::move(state); - auto &stream = exported->stream; - stream.private_data = exported; - stream.get_schema = GetSchema; - stream.get_next = GetNext; - stream.get_last_error = GetLastError; - stream.release = Release; - return &stream; -} - -JavaResultArrowStream &JavaResultArrowStream::GetState(ArrowArrayStream *stream) { - return *reinterpret_cast(stream->private_data)->state; -} - -int JavaResultArrowStream::GetSchema(ArrowArrayStream *stream, ArrowSchema *out) { - if (!stream->release) { - return -1; - } - auto &self = GetState(stream); - std::lock_guard guard(self.lock); - out->release = nullptr; - try { - ArrowConverter::ToArrowSchema(out, self.types, self.names, self.properties); - } catch (std::exception &e) { - self.last_error = ErrorData(e); - return -1; - } - return 0; -} - -int JavaResultArrowStream::GetNext(ArrowArrayStream *stream, ArrowArray *out) { - if (!stream->release) { - return -1; - } - auto &self = GetState(stream); - std::lock_guard guard(self.lock); - out->release = nullptr; - if (self.closed) { - self.last_error = ErrorData(ConnectionException("Connection was closed")); - return -1; - } - try { - ArrowAppender appender(self.types, self.batch_size, self.properties, self.extension_types); - idx_t count = 0; - while (count < self.batch_size) { - if (!self.chunk || self.chunk_offset >= self.chunk->size()) { - if (!self.FetchChunk()) { - return -1; - } - if (!self.chunk) { - break; - } - continue; - } - auto &chunk = *self.chunk; - auto to_append = MinValue(self.batch_size - count, chunk.size() - self.chunk_offset); - appender.Append(chunk, self.chunk_offset, self.chunk_offset + to_append, chunk.size()); - self.chunk_offset += to_append; - count += to_append; - } - if (count > 0) { - *out = appender.Finalize(); - } - } catch (std::exception &e) { - self.last_error = ErrorData(e); - return -1; - } - return 0; -} - -const char *JavaResultArrowStream::GetLastError(ArrowArrayStream *stream) { - if (!stream->release) { - return "stream was released"; - } - auto &self = GetState(stream); - std::lock_guard guard(self.lock); - return self.last_error.HasError() ? self.last_error.Message().c_str() : nullptr; -} - -void JavaResultArrowStream::Release(ArrowArrayStream *stream) { - if (!stream || !stream->release) { - return; - } - stream->release = nullptr; - delete reinterpret_cast(stream->private_data); -} - -bool JavaResultArrowStream::FetchChunk() { - chunk_offset = 0; - if (finished) { - chunk = nullptr; - return true; - } - if (res) { - chunk = res->Fetch(); - if (res->HasError()) { - last_error = res->GetErrorObject(); - return false; - } - } else { - chunk = res_stream->Fetch(); - if (res_stream->HasError()) { - last_error = res_stream->GetErrorObject(); - return false; - } - } - if (!chunk) { - finished = true; - } - return true; -} - -JavaRegisteredArrowStream::JavaRegisteredArrowStream(ArrowArrayStream *source) : stream(*source) { - source->release = nullptr; -} - -JavaRegisteredArrowStream::~JavaRegisteredArrowStream() { - Close(); -} - -void JavaRegisteredArrowStream::Close() { - std::lock_guard guard(lock); - if (stream.release) { - stream.release(&stream); - stream.release = nullptr; - } -} - -void JavaRegisteredArrowStream::GetSchema(ArrowSchema &schema) { - std::lock_guard guard(lock); - if (!stream.release) { - throw InvalidInputException("This stream has been released"); - } - if (stream.get_schema(&stream, &schema) != 0) { - auto error = stream.get_last_error(&stream); - throw InvalidInputException(error ? error : "Unknown error getting Arrow stream schema"); - } -} - -duckdb::unique_ptr JavaRegisteredArrowStream::Take() { - std::lock_guard guard(lock); - if (!stream.release) { - throw InvalidInputException("This stream has been released"); - } - auto res = make_uniq(); - res->arrow_array_stream = stream; - stream.release = nullptr; - return res; -} diff --git a/src/jni/arrow.hpp b/src/jni/arrow.hpp deleted file mode 100644 index 4bc1699a3..000000000 --- a/src/jni/arrow.hpp +++ /dev/null @@ -1,75 +0,0 @@ -#pragma once - -#include "duckdb.hpp" -#include "duckdb/common/arrow/arrow_wrapper.hpp" -#include "duckdb/main/query_result_stream.hpp" -#include "holders.hpp" - -#include - -namespace duckdb { -class ArrowTypeExtensionData; -} - -//! Exports the chunks of a JDBC result as an Arrow stream of record batches of at most batch_size rows. -//! The result is moved out of the ResultHolder into this state, that is shared between the exported stream -//! and the connection. Connection closes the state (releasing the result) if it is closed before the stream. -class JavaResultArrowStream : public ArrowStreamState { -public: - JavaResultArrowStream(duckdb::unique_ptr res_p, - duckdb::unique_ptr> stream_p, duckdb::idx_t batch_size_p); - - void Close() override; - - //! Creates a stream that shares the state, the stream is deleted when it is released - static ArrowArrayStream *Export(duckdb::shared_ptr state); - -private: - struct Exported { - ArrowArrayStream stream; - duckdb::shared_ptr state; - }; - - static JavaResultArrowStream &GetState(ArrowArrayStream *stream); - static int GetSchema(ArrowArrayStream *stream, ArrowSchema *out); - static int GetNext(ArrowArrayStream *stream, ArrowArray *out); - static const char *GetLastError(ArrowArrayStream *stream); - static void Release(ArrowArrayStream *stream); - - //! Loads the next chunk, chunk is null at the end of the result - bool FetchChunk(); - - std::mutex lock; - duckdb::unique_ptr res; - duckdb::unique_ptr> res_stream; - duckdb::idx_t batch_size; - duckdb::vector types; - duckdb::vector names; - duckdb::ClientProperties properties; - duckdb::unordered_map> extension_types; - duckdb::unique_ptr chunk; - duckdb::idx_t chunk_offset = 0; - bool finished = false; - bool closed = false; - duckdb::ErrorData last_error; -}; - -//! Arrow stream registered with a connection. The stream is moved out of the Java-owned struct on registration, -//! it is released when it is consumed by a scan, when the view is dropped or when the connection is closed. -class JavaRegisteredArrowStream : public ArrowStreamState { -public: - explicit JavaRegisteredArrowStream(ArrowArrayStream *source); - - ~JavaRegisteredArrowStream() override; - - void Close() override; - - void GetSchema(ArrowSchema &schema); - - //! A stream can only be consumed by a single scan - duckdb::unique_ptr Take(); - -private: - std::mutex lock; - ArrowArrayStream stream; -}; diff --git a/src/jni/arrow_export.cpp b/src/jni/arrow_export.cpp new file mode 100644 index 000000000..fdcabbf5b --- /dev/null +++ b/src/jni/arrow_export.cpp @@ -0,0 +1,578 @@ +// Exports a query result as an Arrow stream, over the C API v2 only. +// +// The rows of the result are bound to a statement (SELECT * FROM the rows) that is executed with the Arrow result +// format, and the result is turned into an ArrowArrayStream. An Arrow stream is a C structure with callbacks, so it +// cannot be implemented in Java. The stream that is handed out owns the statement and the rows, it is released by +// its consumer. When the connection is closed before the consumer, the streams of the connection are closed: the +// reads of the stream fail then. +#include "bindings.hpp" +#include "refs.hpp" +#include "util.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +struct ExportedStream { + //! The stream that is handed out, it must be the first member + ArrowArrayStream stream {}; + //! The stream of the Arrow result + ArrowArrayStream inner {}; + duckdb_v2_sql_statement_handle statement = nullptr; + duckdb_v2_column_data_collection_handle collection = nullptr; + //! The connection of the result that is exported, the stream is closed with it + duckdb_v2_connection_handle connection = nullptr; + //! The connection of its own that the statement runs on, so that the connection of the result stays usable + duckdb_v2_connection_handle helper = nullptr; + std::mutex lock; + std::string last_error; + bool closed = false; + + //! Releases the resources of the stream, the result goes first as it uses the statement and the rows + void Close() { + std::lock_guard guard(lock); + closed = true; + if (inner.release) { + inner.release(&inner); + inner.release = nullptr; + } + if (statement) { + duckdb_v2_sql_statement_destroy(&statement); + statement = nullptr; + } + if (collection) { + duckdb_v2_column_data_collection_destroy(&collection); + collection = nullptr; + } + if (helper) { + duckdb_v2_connection_destroy(&helper); + helper = nullptr; + } + } +}; + +std::mutex registry_lock; +std::unordered_map> registry; + +ExportedStream &get_exported(ArrowArrayStream *stream) { + return *reinterpret_cast(stream->private_data); +} + +template +int forward(ExportedStream &self, FUNCTION call) { + std::lock_guard guard(self.lock); + if (self.closed || !self.inner.release) { + self.last_error = "Connection Error: Connection was closed"; + return EIO; + } + int res = call(); + if (res != 0) { + const char *error = self.inner.get_last_error(&self.inner); + self.last_error = error ? error : "unable to read the result"; + } + return res; +} + +int stream_get_schema(ArrowArrayStream *stream, ArrowSchema *out) { + if (!stream->release) { + return EINVAL; + } + auto &self = get_exported(stream); + out->release = nullptr; + return forward(self, [&]() { return self.inner.get_schema(&self.inner, out); }); +} + +int stream_get_next(ArrowArrayStream *stream, ArrowArray *out) { + if (!stream->release) { + return EINVAL; + } + auto &self = get_exported(stream); + out->release = nullptr; + return forward(self, [&]() { return self.inner.get_next(&self.inner, out); }); +} + +const char *stream_get_last_error(ArrowArrayStream *stream) { + if (!stream->release) { + return nullptr; + } + auto &self = get_exported(stream); + std::lock_guard guard(self.lock); + return self.last_error.empty() ? nullptr : self.last_error.c_str(); +} + +void stream_release(ArrowArrayStream *stream) { + if (!stream->release) { + return; + } + auto self = &get_exported(stream); + stream->release = nullptr; + { + // the connection does not close the stream anymore + std::lock_guard guard(registry_lock); + auto it = registry.find(self->connection); + if (it != registry.end()) { + auto &streams = it->second; + for (size_t i = 0; i < streams.size(); i++) { + if (streams[i] == self) { + streams.erase(streams.begin() + static_cast(i)); + break; + } + } + if (streams.empty()) { + registry.erase(it); + } + } + } + self->Close(); + delete self; +} + +} // namespace + +// Executes the statement (that reads the collection) on the helper connection with the Arrow result format and returns +// the address of the stream of the result. The stream takes the ownership of the helper connection, of the statement +// and of the collection when the call succeeds, conn is the connection that the stream is closed with. +JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1export_1stream( + JNIEnv *env, jclass, jobject conn_buf, jobject helper_buf, jobject st_buf, jobject collection_buf, + jlong batch_size) { + auto conn = reinterpret_cast(env->GetDirectBufferAddress(conn_buf)); + auto helper = reinterpret_cast(env->GetDirectBufferAddress(helper_buf)); + auto statement = reinterpret_cast(env->GetDirectBufferAddress(st_buf)); + auto collection = + reinterpret_cast(env->GetDirectBufferAddress(collection_buf)); + if (!conn || !helper || !statement || !collection) { + env->ThrowNew(J_SQLException, "Invalid Arrow export arguments"); + return 0; + } + idx_t batch = jlong_to_idx(env, batch_size); + if (env->ExceptionCheck()) { + return 0; + } + + v2_error err; + duckdb_v2_arrow_result_handle result = nullptr; + if (duckdb_v2_statement_execute_arrow(helper, statement, nullptr, nullptr, nullptr, 0, batch, &result, err.out()) != + DUCKDB_V2_ERROR_NONE) { + throw_sql_exception(env, err); + return 0; + } + auto exported = new ExportedStream(); + if (duckdb_v2_arrow_result_to_arrow_c_stream(&result, &exported->inner, err.out()) != DUCKDB_V2_ERROR_NONE) { + if (result) { + duckdb_v2_arrow_result_destroy(&result); + } + delete exported; + throw_sql_exception(env, err); + return 0; + } + exported->statement = statement; + exported->collection = collection; + exported->connection = conn; + exported->helper = helper; + exported->stream.private_data = exported; + exported->stream.get_schema = stream_get_schema; + exported->stream.get_next = stream_get_next; + exported->stream.get_last_error = stream_get_last_error; + exported->stream.release = stream_release; + { + std::lock_guard guard(registry_lock); + registry[conn].push_back(exported); + } + return reinterpret_cast(&exported->stream); +} + +namespace { +void close_registered_streams(duckdb_v2_connection_handle conn); +} // namespace + +// Closes the streams of the connection that are not released by their consumers yet +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1close_1streams(JNIEnv *env, jclass, + jobject conn_buf) { + auto conn = reinterpret_cast(env->GetDirectBufferAddress(conn_buf)); + if (!conn) { + return; + } + close_registered_streams(conn); + std::lock_guard guard(registry_lock); + auto it = registry.find(conn); + if (it == registry.end()) { + return; + } + // the last stream that was created is the first one that is closed + for (size_t i = it->second.size(); i > 0; i--) { + it->second[i - 1]->Close(); + } + registry.erase(it); +} + +// --------------------------------------------------------------------------------------------------------------------- +// Registered streams: an Arrow stream of Java is scanned by the table function that a view of the stream selects from +// --------------------------------------------------------------------------------------------------------------------- + +namespace { + +const char *const ARROW_SCAN_FUNCTION = "__jdbc_arrow_stream_scan"; +// The size of the chunks of the engine, that is the capacity of the output chunk of the scan +constexpr idx_t ARROW_SCAN_BATCH_SIZE = 2048; + +/** + * An Arrow stream registered with a connection. The stream is moved out of the Java-owned struct on registration, it + * is released when it is consumed by a scan, when the view is replaced or when the connection is closed. + */ +struct RegisteredStream { + std::mutex lock; + ArrowArrayStream stream {}; + int64_t id = 0; + duckdb_v2_connection_handle connection = nullptr; + + void Release() { + std::lock_guard guard(lock); + if (stream.release) { + stream.release(&stream); + stream.release = nullptr; + } + } + + // Moves the stream out, returns false if it is released already + bool Take(ArrowArrayStream &out) { + std::lock_guard guard(lock); + if (!stream.release) { + return false; + } + out = stream; + stream.release = nullptr; + return true; + } +}; + +struct RegisteredStreams { + std::mutex lock; + int64_t next_id = 1; + std::unordered_map> streams; + + std::shared_ptr Get(int64_t id) { + std::lock_guard guard(lock); + auto it = streams.find(id); + return it == streams.end() ? nullptr : it->second; + } + + std::shared_ptr Remove(int64_t id) { + std::lock_guard guard(lock); + auto it = streams.find(id); + if (it == streams.end()) { + return nullptr; + } + auto res = std::move(it->second); + streams.erase(it); + return res; + } +}; + +RegisteredStreams ®istered_streams() { + static RegisteredStreams registered; + return registered; +} + +// Releases a stream that was taken from a registered one +struct TakenStream { + ArrowArrayStream stream {}; + + TakenStream() = default; + TakenStream(const TakenStream &) = delete; + TakenStream &operator=(const TakenStream &) = delete; + + ~TakenStream() { + if (stream.release) { + stream.release(&stream); + } + } +}; + +struct ScanBindData { + std::shared_ptr state; +}; + +struct ScanGlobalState { + TakenStream taken; + duckdb_v2_arrow_importer_handle importer = nullptr; + bool finished = false; + + ~ScanGlobalState() { + if (importer) { + duckdb_v2_arrow_importer_destroy(&importer); + } + } +}; + +std::string stream_error(ArrowArrayStream &stream, const char *fallback) { + const char *error = stream.get_last_error ? stream.get_last_error(&stream) : nullptr; + return error ? error : fallback; +} + +void scan_bind(duckdb_v2_function_bind_info_handle info, duckdb_v2_table_function_bind_info_handle result, + duckdb_v2_context_handle context, duckdb_v2_error_info_handle *err) { + v2_value id_value; + v2_error call_err; + int64_t id = 0; + if (duckdb_v2_function_bind_get_arg_value(info, 0, id_value.out(), call_err.out()) != DUCKDB_V2_ERROR_NONE || + duckdb_v2_value_get_bigint(id_value.get(), &id, call_err.out()) != DUCKDB_V2_ERROR_NONE) { + set_callback_error(err, call_err.code(), call_err.raw_message()); + return; + } + auto state = registered_streams().Get(id); + if (!state) { + set_callback_error(err, DUCKDB_V2_ERROR_INPUT_INVALID, "This stream has been released"); + return; + } + ArrowSchema schema {}; + { + std::lock_guard guard(state->lock); + if (!state->stream.release) { + set_callback_error(err, DUCKDB_V2_ERROR_INPUT_INVALID, "This stream has been released"); + return; + } + if (state->stream.get_schema(&state->stream, &schema) != 0) { + auto message = stream_error(state->stream, "unable to read the schema"); + set_callback_error(err, DUCKDB_V2_ERROR_INPUT_INVALID, message); + return; + } + } + duckdb_v2_arrow_importer_handle importer = nullptr; + bool ok = duckdb_v2_arrow_importer_create(context, &schema, ARROW_SCAN_BATCH_SIZE, &importer, call_err.out()) == + DUCKDB_V2_ERROR_NONE; + if (schema.release) { + schema.release(&schema); + } + if (!ok) { + set_callback_error(err, call_err.code(), call_err.raw_message()); + return; + } + v2_schema resolved; + ok = duckdb_v2_arrow_importer_get_schema(importer, resolved.out(), call_err.out()) == DUCKDB_V2_ERROR_NONE; + duckdb_v2_arrow_importer_destroy(&importer); + if (!ok) { + set_callback_error(err, call_err.code(), call_err.raw_message()); + return; + } + idx_t count = 0; + duckdb_v2_schema_get_count(resolved.get(), &count, nullptr); + if (count == 0) { + set_callback_error(err, DUCKDB_V2_ERROR_INPUT_INVALID, + "Provided table/dataframe must have at least one column"); + return; + } + for (idx_t i = 0; i < count; i++) { + const char *name = nullptr; + idx_t name_len = 0; + duckdb_v2_logical_type_handle type = nullptr; + if (duckdb_v2_schema_get_field(resolved.get(), i, &name, &name_len, &type, call_err.out()) != + DUCKDB_V2_ERROR_NONE || + duckdb_v2_table_function_bind_add_result_column(result, name, name_len, type, call_err.out()) != + DUCKDB_V2_ERROR_NONE) { + set_callback_error(err, call_err.code(), call_err.raw_message()); + return; + } + } + auto bind_data = new ScanBindData {std::move(state)}; + duckdb_v2_opaque opaque = {bind_data, [](void *data) { delete static_cast(data); }, nullptr}; + if (duckdb_v2_function_bind_set_bind_data(info, &opaque, call_err.out()) != DUCKDB_V2_ERROR_NONE) { + delete bind_data; + set_callback_error(err, call_err.code(), call_err.raw_message()); + } +} + +void scan_init_global(duckdb_v2_table_function_init_global_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err) { + v2_error call_err; + void *bind_ptr = nullptr; + if (duckdb_v2_table_function_init_global_get_bind_data(info, &bind_ptr, call_err.out()) != DUCKDB_V2_ERROR_NONE) { + set_callback_error(err, call_err.code(), call_err.raw_message()); + return; + } + auto &bind_data = *static_cast(bind_ptr); + auto global = std::unique_ptr(new ScanGlobalState()); + // only the stream of the first scan can be read + if (!bind_data.state->Take(global->taken.stream)) { + set_callback_error(err, DUCKDB_V2_ERROR_INPUT_INVALID, "This stream has been released"); + return; + } + ArrowSchema schema {}; + if (global->taken.stream.get_schema(&global->taken.stream, &schema) != 0) { + set_callback_error(err, DUCKDB_V2_ERROR_INPUT_INVALID, + stream_error(global->taken.stream, "unable to read the schema")); + return; + } + bool ok = duckdb_v2_arrow_importer_create(context, &schema, ARROW_SCAN_BATCH_SIZE, &global->importer, + call_err.out()) == DUCKDB_V2_ERROR_NONE; + if (schema.release) { + schema.release(&schema); + } + if (!ok) { + set_callback_error(err, call_err.code(), call_err.raw_message()); + return; + } + duckdb_v2_table_function_init_global_set_max_threads(info, 1, nullptr); + duckdb_v2_opaque opaque = {global.get(), [](void *data) { delete static_cast(data); }, nullptr}; + if (duckdb_v2_table_function_init_global_set_global_state(info, &opaque, call_err.out()) != DUCKDB_V2_ERROR_NONE) { + set_callback_error(err, call_err.code(), call_err.raw_message()); + return; + } + global.release(); +} + +void scan_exec(duckdb_v2_table_function_exec_info_handle info, duckdb_v2_context_handle, + duckdb_v2_error_info_handle *err) { + v2_error call_err; + void *global_ptr = nullptr; + if (duckdb_v2_table_function_exec_get_global_state(info, &global_ptr, call_err.out()) != DUCKDB_V2_ERROR_NONE) { + set_callback_error(err, call_err.code(), call_err.raw_message()); + return; + } + auto &global = *static_cast(global_ptr); + v2_data_chunk chunk; + while (true) { + if (duckdb_v2_arrow_importer_next_chunk(global.importer, chunk.out(), call_err.out()) != DUCKDB_V2_ERROR_NONE) { + set_callback_error(err, call_err.code(), call_err.raw_message()); + return; + } + if (chunk) { + break; + } + if (global.finished) { + // an empty output chunk is the end of the scan + return; + } + ArrowArray array {}; + array.release = nullptr; + if (global.taken.stream.get_next(&global.taken.stream, &array) != 0) { + set_callback_error(err, DUCKDB_V2_ERROR_INPUT_INVALID, + stream_error(global.taken.stream, "unable to read the stream")); + return; + } + bool end = array.release == nullptr; + if (end) { + global.finished = true; + } + if (duckdb_v2_arrow_importer_append(global.importer, end ? nullptr : &array, true, end, call_err.out()) != + DUCKDB_V2_ERROR_NONE) { + if (!end && array.release) { + array.release(&array); + } + set_callback_error(err, call_err.code(), call_err.raw_message()); + return; + } + } + duckdb_v2_data_chunk_handle output = nullptr; + if (duckdb_v2_table_function_exec_get_output_chunk(info, &output, call_err.out()) != DUCKDB_V2_ERROR_NONE) { + set_callback_error(err, call_err.code(), call_err.raw_message()); + return; + } + idx_t column_count = 0; + idx_t row_count = 0; + duckdb_v2_data_chunk_get_vector_count(chunk.get(), &column_count, nullptr); + duckdb_v2_data_chunk_get_size(chunk.get(), &row_count, nullptr); + for (idx_t i = 0; i < column_count; i++) { + duckdb_v2_vector_handle target = nullptr; + duckdb_v2_vector_handle source = nullptr; + if (duckdb_v2_data_chunk_get_vector(output, i, &target, call_err.out()) != DUCKDB_V2_ERROR_NONE || + duckdb_v2_data_chunk_get_vector(chunk.get(), i, &source, call_err.out()) != DUCKDB_V2_ERROR_NONE || + duckdb_v2_vector_reference(target, source, call_err.out()) != DUCKDB_V2_ERROR_NONE || + duckdb_v2_vector_set_size(target, row_count, call_err.out()) != DUCKDB_V2_ERROR_NONE) { + set_callback_error(err, call_err.code(), call_err.raw_message()); + return; + } + } +} + +// Closes the registered streams of the connection +void close_registered_streams(duckdb_v2_connection_handle conn) { + std::vector> closing; + { + auto ®istered = registered_streams(); + std::lock_guard guard(registered.lock); + for (auto it = registered.streams.begin(); it != registered.streams.end();) { + if (it->second->connection == conn) { + closing.push_back(std::move(it->second)); + it = registered.streams.erase(it); + } else { + ++it; + } + } + } + for (auto &state : closing) { + state->Release(); + } +} + +} // namespace + +// Registers the table function that scans the registered streams +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1scan_1function(JNIEnv *env, jclass, + jobject conn_buf) { + auto conn = reinterpret_cast(env->GetDirectBufferAddress(conn_buf)); + if (!conn) { + env->ThrowNew(J_SQLException, "Invalid connection"); + return; + } + v2_error err; + duckdb_v2_factory_handle factory = nullptr; + v2_table_function function; + v2_logical_type bigint; + duckdb_v2_function_signature_handle signature = nullptr; + const char *name = ARROW_SCAN_FUNCTION; + if (duckdb_v2_connection_get_factory(conn, &factory, err.out()) != DUCKDB_V2_ERROR_NONE || + duckdb_v2_table_function_create(factory, function.out(), err.out()) != DUCKDB_V2_ERROR_NONE || + duckdb_v2_table_function_set_name(function.get(), name, std::strlen(name), err.out()) != DUCKDB_V2_ERROR_NONE || + duckdb_v2_factory_create_type_from_id(factory, DUCKDB_V2_LOGICAL_TYPE_ID_BIGINT, nullptr, nullptr, nullptr, 0, + bigint.out(), err.out()) != DUCKDB_V2_ERROR_NONE || + duckdb_v2_table_function_get_signature(function.get(), &signature, err.out()) != DUCKDB_V2_ERROR_NONE || + duckdb_v2_function_signature_add_parameter(signature, "stream_id", 9, bigint.get(), nullptr, + DUCKDB_V2_FUNCTION_PARAMETER_KIND_POSITIONAL_ONLY, + err.out()) != DUCKDB_V2_ERROR_NONE || + duckdb_v2_table_function_set_bind_callback(function.get(), scan_bind, err.out()) != DUCKDB_V2_ERROR_NONE || + duckdb_v2_table_function_set_init_global_callback(function.get(), scan_init_global, err.out()) != + DUCKDB_V2_ERROR_NONE || + duckdb_v2_table_function_set_exec_callback(function.get(), scan_exec, err.out()) != DUCKDB_V2_ERROR_NONE || + duckdb_v2_connection_register_table_function(conn, function.get(), err.out()) != DUCKDB_V2_ERROR_NONE) { + throw_sql_exception(env, err); + } +} + +// Moves the stream out of the Java-owned struct and registers it with the connection, returns its id +JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1stream(JNIEnv *env, jclass, + jobject conn_buf, + jlong stream_address) { + auto conn = reinterpret_cast(env->GetDirectBufferAddress(conn_buf)); + auto source = reinterpret_cast(stream_address); + if (!conn) { + env->ThrowNew(J_SQLException, "Invalid connection"); + return 0; + } + if (!source || !source->release) { + env->ThrowNew(J_SQLException, "Invalid Input Error: This stream has been released"); + return 0; + } + auto state = std::make_shared(); + state->stream = *source; + source->release = nullptr; + state->connection = conn; + auto ®istered = registered_streams(); + std::lock_guard guard(registered.lock); + state->id = registered.next_id++; + registered.streams[state->id] = state; + return static_cast(state->id); +} + +// Releases the registered stream, if it is not consumed or released yet +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1release_1stream(JNIEnv *, jclass, jlong id) { + auto state = registered_streams().Remove(static_cast(id)); + if (state) { + state->Release(); + } +} diff --git a/src/jni/bindings_v2.cpp b/src/jni/bindings_v2.cpp index 3e3a77423..386076feb 100644 --- a/src/jni/bindings_v2.cpp +++ b/src/jni/bindings_v2.cpp @@ -56,16 +56,6 @@ static void throw_v2_error(JNIEnv *env, const v2_error &err) { /* --- connection --- */ -// Transitional: the C API v2 handle of the connection of a connection holder -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1from_1ref(JNIEnv *env, jclass, - jobject conn_ref) { - auto conn = conn_ref_buf_to_conn(env, conn_ref); - if (env->ExceptionCheck()) { - return nullptr; - } - return make_ptr_buf(env, conn); -} - JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1interrupt(JNIEnv *env, jclass, jobject conn_buf) { CHECK_BUF(conn, conn_buf, duckdb_v2_connection_handle, "connection"); @@ -866,3 +856,352 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1add CALL_V2(duckdb_v2_statement_add_collection(st, name.data(), name.size(), collection, name_ptrs.data(), name_lens.data(), names.size(), ERR_OUT), ); } + +/* --- environments, instances and connections --- */ + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1environment_1create(JNIEnv *env, jclass) { + duckdb_v2_environment_handle environment = nullptr; + CALL_V2(duckdb_v2_environment_create(&environment, ERR_OUT), nullptr); + return make_ptr_buf(env, environment); +} + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1environment_1destroy(JNIEnv *env, jclass, + jobject env_buf) { + CHECK_BUF(environment, env_buf, duckdb_v2_environment_handle, "environment"); + CALL_V2(duckdb_v2_environment_destroy(&environment), ); +} + +// Reads the byte arrays of the startup options +static bool read_options(JNIEnv *env, jobjectArray names_j, jobjectArray values_j, std::vector &names, + std::vector &values) { + jsize count = names_j == nullptr ? 0 : env->GetArrayLength(names_j); + for (jsize i = 0; i < count; i++) { + auto name_arr = reinterpret_cast(env->GetObjectArrayElement(names_j, i)); + auto value_arr = reinterpret_cast(env->GetObjectArrayElement(values_j, i)); + names.push_back(jbyteArray_to_string(env, name_arr)); + values.push_back(jbyteArray_to_string(env, value_arr)); + env->DeleteLocalRef(name_arr); + env->DeleteLocalRef(value_arr); + if (env->ExceptionCheck()) { + return false; + } + } + return true; +} + +struct OptionPointers { + std::vector name_ptrs; + std::vector name_lens; + std::vector value_ptrs; + std::vector value_lens; + + OptionPointers(const std::vector &names, const std::vector &values) { + for (size_t i = 0; i < names.size(); i++) { + name_ptrs.push_back(names[i].data()); + name_lens.push_back(names[i].size()); + value_ptrs.push_back(values[i].data()); + value_lens.push_back(values[i].size()); + } + } +}; + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1create_1with_1options( + JNIEnv *env, jclass, jobject env_buf, jobjectArray names_j, jobjectArray values_j) { + CHECK_BUF_RET(environment, env_buf, duckdb_v2_environment_handle, "environment", nullptr); + std::vector names; + std::vector values; + if (!read_options(env, names_j, values_j, names, values)) { + return nullptr; + } + OptionPointers options(names, values); + duckdb_v2_instance_handle instance = nullptr; + CALL_V2(duckdb_v2_instance_create_with_options(environment, options.name_ptrs.data(), options.name_lens.data(), + options.value_ptrs.data(), options.value_lens.data(), names.size(), + &instance, ERR_OUT), + nullptr); + return make_ptr_buf(env, instance); +} + +// The call of the Java initializer of a new shared instance +struct InstanceInitContext { + JNIEnv *env; + jobject callback; +}; + +static void instance_init_trampoline(duckdb_v2_instance_handle instance, void *user_data, + duckdb_v2_error_info_handle *err) { + auto ctx = reinterpret_cast(user_data); + JNIEnv *env = ctx->env; + jclass callback_class = env->GetObjectClass(ctx->callback); + jmethodID init_method = env->GetMethodID(callback_class, "init", "(Ljava/nio/ByteBuffer;)V"); + env->DeleteLocalRef(callback_class); + if (init_method == nullptr) { + env->ExceptionClear(); + set_callback_error(err, DUCKDB_V2_ERROR_API, "Instance initializer not found"); + return; + } + jobject instance_buf = make_ptr_buf(env, instance); + env->CallVoidMethod(ctx->callback, init_method, instance_buf); + env->DeleteLocalRef(instance_buf); + if (env->ExceptionCheck()) { + jthrowable exception = env->ExceptionOccurred(); + env->ExceptionClear(); + std::string message = "Instance initializer failed"; + jmethodID get_message = env->GetMethodID(env->GetObjectClass(exception), "getMessage", "()Ljava/lang/String;"); + if (get_message != nullptr) { + auto message_j = reinterpret_cast(env->CallObjectMethod(exception, get_message)); + if (env->ExceptionCheck()) { + env->ExceptionClear(); + } else if (message_j != nullptr) { + message = jstring_to_string(env, message_j); + } + } + env->DeleteLocalRef(exception); + set_callback_error(err, DUCKDB_V2_ERROR_DATABASE_CATALOG, message); + } +} + +// Opens the shared instance of the path, the initializer is called with the instance when it is created +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1open_1shared( + JNIEnv *env, jclass, jobject env_buf, jbyteArray path_j, jobjectArray names_j, jobjectArray values_j, + jobject init) { + CHECK_BUF_RET(environment, env_buf, duckdb_v2_environment_handle, "environment", nullptr); + auto path = jbyteArray_to_string(env, path_j); + if (env->ExceptionCheck()) { + return nullptr; + } + std::vector names; + std::vector values; + if (!read_options(env, names_j, values_j, names, values)) { + return nullptr; + } + OptionPointers options(names, values); + InstanceInitContext ctx {env, init}; + duckdb_v2_instance_handle instance = nullptr; + v2_error err; + if (duckdb_v2_instance_open_shared(environment, path.data(), path.size(), options.name_ptrs.data(), + options.name_lens.data(), options.value_ptrs.data(), options.value_lens.data(), + names.size(), init == nullptr ? nullptr : instance_init_trampoline, + init == nullptr ? nullptr : &ctx, &instance, + err.out()) != DUCKDB_V2_ERROR_NONE) { + throw_v2_error(env, err); + return nullptr; + } + return make_ptr_buf(env, instance); +} + +// The name can be null +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1attach(JNIEnv *env, jclass, + jobject instance_buf, + jbyteArray name_j, jbyteArray path_j, + jboolean make_default) { + CHECK_BUF(instance, instance_buf, duckdb_v2_instance_handle, "instance"); + std::string name; + if (name_j != nullptr) { + name = jbyteArray_to_string(env, name_j); + } + auto path = jbyteArray_to_string(env, path_j); + if (env->ExceptionCheck()) { + return; + } + CALL_V2(duckdb_v2_instance_attach(instance, name_j == nullptr ? nullptr : name.data(), name.size(), path.data(), + path.size(), nullptr, make_default == JNI_TRUE, ERR_OUT), ); +} + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1destroy(JNIEnv *env, jclass, + jobject instance_buf) { + CHECK_BUF(instance, instance_buf, duckdb_v2_instance_handle, "instance"); + duckdb_v2_instance_destroy(&instance); +} + +// The returned config is borrowed from the instance +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1get_1config(JNIEnv *env, jclass, + jobject instance_buf) { + CHECK_BUF_RET(instance, instance_buf, duckdb_v2_instance_handle, "instance", nullptr); + duckdb_v2_config_handle config = nullptr; + CALL_V2(duckdb_v2_instance_get_config(instance, &config, ERR_OUT), nullptr); + return make_ptr_buf(env, config); +} + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1create(JNIEnv *env, jclass, + jobject instance_buf) { + CHECK_BUF_RET(instance, instance_buf, duckdb_v2_instance_handle, "instance", nullptr); + duckdb_v2_connection_handle conn = nullptr; + CALL_V2(duckdb_v2_connection_create(instance, &conn, ERR_OUT), nullptr); + return make_ptr_buf(env, conn); +} + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1destroy(JNIEnv *env, jclass, + jobject conn_buf) { + CHECK_BUF(conn, conn_buf, duckdb_v2_connection_handle, "connection"); + duckdb_v2_connection_destroy(&conn); +} + +/* --- configuration --- */ + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1set_1option_1text( + JNIEnv *env, jclass, jobject config_buf, jbyteArray name_j, jbyteArray value_j, jint scope) { + CHECK_BUF(config, config_buf, duckdb_v2_config_handle, "config"); + auto name = jbyteArray_to_string(env, name_j); + auto value = jbyteArray_to_string(env, value_j); + if (env->ExceptionCheck()) { + return; + } + CALL_V2(duckdb_v2_config_set_option_text(config, name.data(), name.size(), value.data(), value.size(), + static_cast(scope), ERR_OUT), ); +} + +// The value is borrowed for the call +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1set_1option_1value( + JNIEnv *env, jclass, jobject config_buf, jbyteArray name_j, jobject value_buf, jint scope) { + CHECK_BUF(config, config_buf, duckdb_v2_config_handle, "config"); + CHECK_BUF(value, value_buf, duckdb_v2_value_handle, "value"); + auto name = jbyteArray_to_string(env, name_j); + if (env->ExceptionCheck()) { + return; + } + CALL_V2(duckdb_v2_config_set_option_value(config, name.data(), name.size(), value, + static_cast(scope), ERR_OUT), ); +} + +JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1count(JNIEnv *env, jclass, + jobject config_buf) { + CHECK_BUF_RET(config, config_buf, duckdb_v2_config_handle, "config", 0); + idx_t count = 0; + CALL_V2(duckdb_v2_config_get_option_count(config, &count, ERR_OUT), 0); + return uint64_to_jlong(count); +} + +// The returned option is owned by the caller +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1by_1index(JNIEnv *env, jclass, + jobject config_buf, + jlong index) { + CHECK_BUF_RET(config, config_buf, duckdb_v2_config_handle, "config", nullptr); + idx_t idx = jlong_to_idx(env, index); + if (env->ExceptionCheck()) { + return nullptr; + } + duckdb_v2_option_handle option = nullptr; + CALL_V2(duckdb_v2_config_get_option_by_index(config, idx, &option, ERR_OUT), nullptr); + return make_ptr_buf(env, option); +} + +JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1option_1get_1name(JNIEnv *env, jclass, + jobject option_buf) { + CHECK_BUF_RET(option, option_buf, duckdb_v2_option_handle, "option", nullptr); + const char *name = nullptr; + idx_t name_len = 0; + CALL_V2(duckdb_v2_option_get_name(option, &name, &name_len, ERR_OUT), nullptr); + return make_jbyteArray(env, name, name_len); +} + +JNIEXPORT jboolean JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1option_1supports_1scope(JNIEnv *env, jclass, + jobject option_buf, + jint scope) { + CHECK_BUF_RET(option, option_buf, duckdb_v2_option_handle, "option", JNI_FALSE); + bool supported = false; + CALL_V2(duckdb_v2_option_supports_scope(option, static_cast(scope), &supported, ERR_OUT), + JNI_FALSE); + return supported ? JNI_TRUE : JNI_FALSE; +} + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1option_1destroy(JNIEnv *env, jclass, + jobject option_buf) { + CHECK_BUF(option, option_buf, duckdb_v2_option_handle, "option"); + duckdb_v2_option_destroy(&option); +} + +// Reads the option value, the scope that the value comes from is written to scope_out[0] when it is given +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1value_1scoped( + JNIEnv *env, jclass, jobject config_buf, jbyteArray name_j, jintArray scope_out) { + CHECK_BUF_RET(config, config_buf, duckdb_v2_config_handle, "config", nullptr); + auto name = jbyteArray_to_string(env, name_j); + if (env->ExceptionCheck()) { + return nullptr; + } + duckdb_v2_value_handle value = nullptr; + DUCKDB_V2_SETTING_SCOPE scope = DUCKDB_V2_SETTING_SCOPE_DEFAULT; + CALL_V2(duckdb_v2_config_get_option_value(config, name.data(), name.size(), &value, &scope, ERR_OUT), nullptr); + if (scope_out != nullptr) { + jint scope_j = static_cast(scope); + env->SetIntArrayRegion(scope_out, 0, 1, &scope_j); + } + return make_ptr_buf(env, value); +} + +/* --- custom options --- */ + +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1create(JNIEnv *env, jclass, + jobject factory_buf) { + CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); + duckdb_v2_custom_option_handle option = nullptr; + CALL_V2(duckdb_v2_custom_option_create(factory, &option, ERR_OUT), nullptr); + return make_ptr_buf(env, option); +} + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1destroy(JNIEnv *env, jclass, + jobject option_buf) { + CHECK_BUF(option, option_buf, duckdb_v2_custom_option_handle, "custom option"); + duckdb_v2_custom_option_destroy(&option); +} + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1name(JNIEnv *env, jclass, + jobject option_buf, + jbyteArray name_j) { + CHECK_BUF(option, option_buf, duckdb_v2_custom_option_handle, "custom option"); + auto name = jbyteArray_to_string(env, name_j); + if (env->ExceptionCheck()) { + return; + } + CALL_V2(duckdb_v2_custom_option_set_name(option, name.data(), name.size(), ERR_OUT), ); +} + +// The type is borrowed for the call +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1type(JNIEnv *env, jclass, + jobject option_buf, + jobject type_buf) { + CHECK_BUF(option, option_buf, duckdb_v2_custom_option_handle, "custom option"); + auto type = logical_type_buf_to_logical_type(env, type_buf); + if (env->ExceptionCheck()) { + return; + } + CALL_V2(duckdb_v2_custom_option_set_type(option, type, ERR_OUT), ); +} + +// The value is borrowed for the call +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1default_1value( + JNIEnv *env, jclass, jobject option_buf, jobject value_buf) { + CHECK_BUF(option, option_buf, duckdb_v2_custom_option_handle, "custom option"); + CHECK_BUF(value, value_buf, duckdb_v2_value_handle, "value"); + CALL_V2(duckdb_v2_custom_option_set_default_value(option, value, ERR_OUT), ); +} + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1description( + JNIEnv *env, jclass, jobject option_buf, jbyteArray description_j) { + CHECK_BUF(option, option_buf, duckdb_v2_custom_option_handle, "custom option"); + auto description = jbyteArray_to_string(env, description_j); + if (env->ExceptionCheck()) { + return; + } + CALL_V2(duckdb_v2_custom_option_set_description(option, description.data(), description.size(), ERR_OUT), ); +} + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1default_1scope( + JNIEnv *env, jclass, jobject option_buf, jint scope) { + CHECK_BUF(option, option_buf, duckdb_v2_custom_option_handle, "custom option"); + CALL_V2(duckdb_v2_custom_option_set_default_scope(option, static_cast(scope), ERR_OUT), ); +} + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1supports_1scope( + JNIEnv *env, jclass, jobject option_buf, jint scope, jboolean supported) { + CHECK_BUF(option, option_buf, duckdb_v2_custom_option_handle, "custom option"); + CALL_V2(duckdb_v2_custom_option_set_supports_scope(option, static_cast(scope), + supported == JNI_TRUE, ERR_OUT), ); +} + +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1register_1custom_1option( + JNIEnv *env, jclass, jobject conn_buf, jobject option_buf) { + CHECK_BUF(conn, conn_buf, duckdb_v2_connection_handle, "connection"); + CHECK_BUF(option, option_buf, duckdb_v2_custom_option_handle, "custom option"); + CALL_V2(duckdb_v2_connection_register_custom_option(conn, option, ERR_OUT), ); +} diff --git a/src/jni/config.cpp b/src/jni/config.cpp deleted file mode 100644 index 396d3d11d..000000000 --- a/src/jni/config.cpp +++ /dev/null @@ -1,164 +0,0 @@ -#include "config.hpp" - -#include "duckdb/common/virtual_file_system.hpp" -#include "refs.hpp" -#include "util.hpp" - -#include -#include - -static duckdb::Value jobj_to_value(JNIEnv *env, const std::string &key, jobject jval) { - // On the right in comments are all types that are currently present - // in DuckDB config. - if (nullptr == jval) { - return duckdb::Value(); - - } else if (env->IsInstanceOf(jval, J_Bool)) { // BOOLEAN - jboolean val = env->CallBooleanMethod(jval, J_Bool_booleanValue); - check_java_exception_and_rethrow(env); - return duckdb::Value::BOOLEAN(val); - - } else if (env->IsInstanceOf(jval, J_Byte)) { // UBIGINT - jbyte val = env->CallByteMethod(jval, J_Byte_byteValue); - check_java_exception_and_rethrow(env); - return duckdb::Value::TINYINT(val); - - } else if (env->IsInstanceOf(jval, J_Short)) { // UBIGINT - jshort val = env->CallShortMethod(jval, J_Short_shortValue); - check_java_exception_and_rethrow(env); - return duckdb::Value::SMALLINT(val); - - } else if (env->IsInstanceOf(jval, J_Int)) { // UBIGINT - jint val = env->CallIntMethod(jval, J_Int_intValue); - check_java_exception_and_rethrow(env); - return duckdb::Value::INTEGER(val); - - } else if (env->IsInstanceOf(jval, J_Long)) { // UBIGINT - jlong val = env->CallLongMethod(jval, J_Long_longValue); - check_java_exception_and_rethrow(env); - return duckdb::Value::BIGINT(val); - - } else if (env->IsInstanceOf(jval, J_Float)) { // FLOAT - jfloat val = env->CallFloatMethod(jval, J_Float_floatValue); - check_java_exception_and_rethrow(env); - return duckdb::Value::FLOAT(val); - - } else if (env->IsInstanceOf(jval, J_Double)) { // DOUBLE - jdouble val = env->CallDoubleMethod(jval, J_Double_doubleValue); - check_java_exception_and_rethrow(env); - return duckdb::Value::DOUBLE(val); - - } else if (env->IsInstanceOf(jval, J_String)) { // VARCHAR - std::string val = jstring_to_string(env, reinterpret_cast(jval)); - return duckdb::Value(val); - - } else if (env->IsInstanceOf(jval, J_List)) { // VARCHAR[] - jobject iterator = env->CallObjectMethod(jval, J_List_iterator); - check_java_exception_and_rethrow(env); - - duckdb::vector vec; - while (env->CallBooleanMethod(iterator, J_Iterator_hasNext)) { - check_java_exception_and_rethrow(env); - jobject list_entry = env->CallObjectMethod(iterator, J_Iterator_next); - check_java_exception_and_rethrow(env); - // all list entries are coalesced to string - jstring jstr = reinterpret_cast(env->CallObjectMethod(list_entry, J_Object_toString)); - check_java_exception_and_rethrow(env); - std::string sval = jstring_to_string(env, jstr); - duckdb::Value val(std::move(sval)); - vec.push_back(std::move(val)); - } - check_java_exception_and_rethrow(env); - return duckdb::Value::LIST(duckdb::LogicalType::VARCHAR, std::move(vec)); - - } else { - // coalesce to string the entry with an unknown type - jstring jstr = reinterpret_cast(env->CallObjectMethod(jval, J_Object_toString)); - check_java_exception_and_rethrow(env); - std::string str = jstring_to_string(env, jstr); - return duckdb::Value(str); - } -} - -static bool is_allowed_paths_option(const std::string &key) { - return duckdb::StringUtil::CIEquals(key, "allowed_directories") || - duckdb::StringUtil::CIEquals(key, "allowed_paths"); -} - -// DuckDB refuses to set 'allowed_directories' and 'allowed_paths' through -// SetOptionByName before the database is started. Set them directly on the -// DBConfig instead, its options are copied to the database on startup. -// The check of 'enable_external_access' is skipped intentionally, at startup -// these options are commonly used together with 'enable_external_access=false' -// and the order in which properties are applied is not defined. -static void set_allowed_paths_option(duckdb::DBConfig &config, const std::string &key, const duckdb::Value &value) { - if (value.IsNull()) { - throw duckdb::InvalidInputException("%s setting cannot be NULL", key); - } - auto list_value = value.DefaultCastAs(duckdb::LogicalType::LIST(duckdb::LogicalType::VARCHAR)); - duckdb::vector paths; - for (auto &val : duckdb::ListValue::GetChildren(list_value)) { - paths.push_back(val.GetValue()); - } - if (duckdb::StringUtil::CIEquals(key, "allowed_directories")) { - config.SetAllowedDirectories(paths); - } else { - config.SetAllowedPaths(paths); - } - // keep the option in 'user_options' like SetOptionByName does for a user config, - // it is used by the instance cache to compare configs - config.options.user_options[duckdb::Identifier(key)] = value; -} - -std::unique_ptr create_db_config(JNIEnv *env, jboolean read_only, jobject java_config) { - auto config = std::unique_ptr(new duckdb::DBConfig()); - // Required for setting like 'allowed_directories' that use - // file separator when checking the property value. - config->file_system = duckdb::make_uniq(); - config->SetOptionByName("duckdb_api", "java"); - config->AddExtensionOption( - "jdbc_stream_results", - "Whether to stream results. Only one ResultSet on a connection can be open at once when true", - duckdb::LogicalType::BOOLEAN); - if (read_only) { - config->options.access_mode = duckdb::AccessMode::READ_ONLY; - } - jobject entry_set = env->CallObjectMethod(java_config, J_Map_entrySet); - check_java_exception_and_rethrow(env); - jobject iterator = env->CallObjectMethod(entry_set, J_Set_iterator); - check_java_exception_and_rethrow(env); - - while (env->CallBooleanMethod(iterator, J_Iterator_hasNext)) { - check_java_exception_and_rethrow(env); - jobject pair = env->CallObjectMethod(iterator, J_Iterator_next); - check_java_exception_and_rethrow(env); - jobject key = env->CallObjectMethod(pair, J_Entry_getKey); - check_java_exception_and_rethrow(env); - jobject value = env->CallObjectMethod(pair, J_Entry_getValue); - check_java_exception_and_rethrow(env); - - jstring key_jstr = reinterpret_cast(env->CallObjectMethod(key, J_Object_toString)); - env->DeleteLocalRef(key); - check_java_exception_and_rethrow(env); - std::string key_str = jstring_to_string(env, key_jstr); - env->DeleteLocalRef(key_jstr); - - duckdb::Value dvalue = jobj_to_value(env, key_str, value); - env->DeleteLocalRef(value); - - try { - if (is_allowed_paths_option(key_str)) { - set_allowed_paths_option(*config, key_str, dvalue); - continue; - } - config->SetOptionByName(duckdb::Identifier(key_str), dvalue); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - throw duckdb::CatalogException("Failed to set configuration option \"%s\", error: %s", key_str, - error.RawMessage()); - } - } - check_java_exception_and_rethrow(env); - - return config; -} diff --git a/src/jni/config.hpp b/src/jni/config.hpp deleted file mode 100644 index 8218226fe..000000000 --- a/src/jni/config.hpp +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -#include "duckdb.hpp" - -#include -#include - -std::unique_ptr create_db_config(JNIEnv *env, jboolean read_only, jobject java_config); diff --git a/src/jni/duckdb_java.cpp b/src/jni/duckdb_java.cpp index 8c3c608bf..4de02e7c5 100644 --- a/src/jni/duckdb_java.cpp +++ b/src/jni/duckdb_java.cpp @@ -1,39 +1,9 @@ -#include "arrow.hpp" -#include "config.hpp" #include "duckdb.hpp" -#include "duckdb/catalog/catalog_search_path.hpp" -#include "duckdb/common/operator/cast_operators.hpp" -#include "duckdb/common/shared_ptr.hpp" -#include "duckdb/common/vector/array_vector.hpp" -#include "duckdb/common/vector/list_vector.hpp" -#include "duckdb/common/vector/struct_vector.hpp" -#include "duckdb/function/scalar/variant_utils.hpp" -#include "duckdb/function/table/arrow.hpp" #include "duckdb/main/capi_v2/capi_v2_internal.hpp" -#include "duckdb/main/capi_v2/capi_v2_result_internal.hpp" -#include "duckdb/main/client_context.hpp" -#include "duckdb/main/client_data.hpp" -#include "duckdb/main/database_manager.hpp" -#include "duckdb/main/db_instance_cache.hpp" -#include "duckdb/main/extension/extension_loader.hpp" -#include "duckdb/parser/expression/function_expression.hpp" -#include "duckdb/parser/expression/star_expression.hpp" -#include "duckdb/parser/parsed_data/create_type_info.hpp" -#include "duckdb/parser/parsed_data/create_view_info.hpp" -#include "duckdb/parser/query_node/select_node.hpp" -#include "duckdb/parser/statement/create_statement.hpp" -#include "duckdb/parser/statement/select_statement.hpp" -#include "duckdb/parser/tableref/table_function_ref.hpp" #include "functions.hpp" -#include "holders.hpp" #include "refs.hpp" -#include "types.hpp" #include "util.hpp" -#include -#include -#include - using namespace duckdb; using namespace std; @@ -73,188 +43,6 @@ JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved) { delete_global_refs(env); } -//! The database instance cache, used so that multiple connections to the same file point to the same database object -duckdb::DBInstanceCache instance_cache; - -jobject _duckdb_jdbc_startup(JNIEnv *env, jclass, jbyteArray database_j, jboolean read_only, jobject props, - jboolean cache_instance) { - auto database = jbyteArray_to_string(env, database_j); - std::unique_ptr config = create_db_config(env, read_only, props); - bool should_cache = cache_instance && database != ":memory:" && !database.empty(); - auto shared_db = instance_cache.GetOrCreateInstance(database, *config, should_cache); - auto conn_ref = new ConnectionHolder(shared_db); - - return env->NewDirectByteBuffer(conn_ref, 0); -} - -jobject _duckdb_jdbc_connect(JNIEnv *env, jclass, jobject conn_ref_buf) { - auto conn_ref = get_connection_ref(env, conn_ref_buf); - auto config = ClientConfig::GetConfig(*conn_ref->connection->context); - auto conn = new ConnectionHolder(conn_ref->db); - ClientConfig::GetConfig(*conn->connection->context) = config; - return env->NewDirectByteBuffer(conn, 0); -} - -jobject _duckdb_jdbc_create_db_ref(JNIEnv *env, jclass, jobject conn_ref_buf) { - auto conn_ref = get_connection_ref(env, conn_ref_buf); - auto db_ref = conn_ref->create_db_ref(); - return env->NewDirectByteBuffer(db_ref, 0); -} - -jlong _duckdb_jdbc_db_address(JNIEnv *env, jclass, jobject conn_ref_buf) { - auto conn_ref = get_connection_ref(env, conn_ref_buf); - // the instance cache returns a new DuckDB handle for every cache hit, the DatabaseInstance is the shared object - return (jlong)conn_ref->db->instance.get(); -} - -void _duckdb_jdbc_destroy_db_ref(JNIEnv *env, jclass, jobject db_ref_buf) { - if (nullptr == db_ref_buf) { - return; - } - auto db_ref = (DBHolder *)env->GetDirectBufferAddress(db_ref_buf); - if (db_ref) { - delete db_ref; - } -} - -jstring _duckdb_jdbc_get_schema(JNIEnv *env, jclass, jobject conn_ref_buf) { - auto conn_ref = get_connection(env, conn_ref_buf); - if (!conn_ref) { - return nullptr; - } - - auto entry = ClientData::Get(*conn_ref->context).catalog_search_path->GetDefault(); - - return env->NewStringUTF(entry.GetSchema().c_str()); -} - -static void set_catalog_search_path(JNIEnv *env, jobject conn_ref_buf, CatalogSearchEntry search_entry) { - auto conn_ref = get_connection(env, conn_ref_buf); - if (!conn_ref) { - return; - } - - conn_ref->context->RunFunctionInTransaction([&]() { - ClientData::Get(*conn_ref->context).catalog_search_path->Set(search_entry, CatalogSetPathType::SET_SCHEMA); - }); -} - -void _duckdb_jdbc_set_schema(JNIEnv *env, jclass, jobject conn_ref_buf, jstring schema) { - set_catalog_search_path( - env, conn_ref_buf, CatalogSearchEntry(Identifier(INVALID_CATALOG), Identifier(jstring_to_string(env, schema)))); -} - -void _duckdb_jdbc_set_catalog(JNIEnv *env, jclass, jobject conn_ref_buf, jstring catalog) { - set_catalog_search_path( - env, conn_ref_buf, CatalogSearchEntry(Identifier(jstring_to_string(env, catalog)), Identifier(DEFAULT_SCHEMA))); -} - -jstring _duckdb_jdbc_get_catalog(JNIEnv *env, jclass, jobject conn_ref_buf) { - auto conn_ref = get_connection(env, conn_ref_buf); - if (!conn_ref) { - return nullptr; - } - - auto entry = ClientData::Get(*conn_ref->context).catalog_search_path->GetDefault(); - if (entry.GetCatalog() == INVALID_CATALOG) { - entry.SetCatalog(DatabaseManager::GetDefaultDatabase(*conn_ref->context)); - } - - return env->NewStringUTF(entry.GetCatalog().c_str()); -} - -void _duckdb_jdbc_set_auto_commit(JNIEnv *env, jclass, jobject conn_ref_buf, jboolean auto_commit) { - auto conn_ref = get_connection(env, conn_ref_buf); - if (!conn_ref) { - return; - } - conn_ref->context->RunFunctionInTransaction([&]() { conn_ref->SetAutoCommit(auto_commit); }); -} - -jboolean _duckdb_jdbc_get_auto_commit(JNIEnv *env, jclass, jobject conn_ref_buf) { - auto conn_ref = get_connection(env, conn_ref_buf); - if (!conn_ref) { - return false; - } - return conn_ref->IsAutoCommit(); -} - -void _duckdb_jdbc_disconnect(JNIEnv *env, jclass, jobject conn_ref_buf) { - if (nullptr == conn_ref_buf) { - return; - } - auto conn_ref = (ConnectionHolder *)env->GetDirectBufferAddress(conn_ref_buf); - if (conn_ref) { - delete conn_ref; - } -} - -#include "utf8proc_wrapper.hpp" - -jint _duckdb_jdbc_fetch_size(JNIEnv *, jclass) { - return STANDARD_VECTOR_SIZE; -} - -class JavaArrowScanFactory : public ArrowScanFactory { -public: - explicit JavaArrowScanFactory(duckdb::shared_ptr state_p) : state(std::move(state_p)) { - } - - void GetSchema(ArrowSchema &schema) override { - state->GetSchema(schema); - } - - duckdb::unique_ptr ProduceStream(ArrowStreamParameters &) override { - return state->Take(); - } - -private: - duckdb::shared_ptr state; -}; - -void _duckdb_jdbc_arrow_register(JNIEnv *env, jclass, jobject conn_ref_buf, jlong arrow_array_stream_pointer, - jbyteArray name_j) { - auto conn = get_connection(env, conn_ref_buf); - if (conn == nullptr) { - return; - } - auto conn_holder = get_connection_ref(env, conn_ref_buf); - auto name = jbyteArray_to_string(env, name_j); - auto arrow_array_stream = reinterpret_cast(arrow_array_stream_pointer); - if (!arrow_array_stream || !arrow_array_stream->release) { - throw InvalidInputException("This stream has been released"); - } - - auto state = make_shared_ptr(arrow_array_stream); - conn_holder->track_arrow_stream(state); - auto factory = make_shared_ptr(std::move(state)); - // construct the `arrow_scan_dumb(...)` function expression - auto scan = make_uniq(); - scan->function = - make_uniq("arrow_scan_dumb", duckdb::vector>()); - scan->bind_info = std::move(factory); - // construct the `SELECT * FROM arrow_scan_dumb(...)` statement - auto node = make_uniq(); - node->select_list.push_back(make_uniq()); - node->from_table = std::move(scan); - auto select = make_uniq(); - select->node = std::move(node); - // construct the `CREATE TEMP VIEW AS` statement using the select statement - auto info = make_uniq(); - info->query = std::move(select); - info->temporary = true; - info->SetQualifiedName(QualifiedName(Identifier(), Identifier::InvalidSchema(), Identifier(name))); - info->on_conflict = OnCreateConflict::REPLACE_ON_CONFLICT; - auto statement = make_uniq(); - statement->info = std::move(info); - // execute the CREATE VIEW - conn->Query(std::move(statement))->ThrowIfError("Failed to create view '" + name + "': "); -} - -void _duckdb_jdbc_arrow_close_streams(JNIEnv *env, jclass, jobject conn_ref_buf) { - get_connection_ref(env, conn_ref_buf)->close_arrow_streams(); -} - static ProfilerPrintFormat GetProfilerPrintFormat(JNIEnv *env, jobject format) { jobject jname = env->CallObjectMethod(format, J_ProfilerPrintFormat_getName); check_java_exception_and_rethrow(env); @@ -262,11 +50,17 @@ static ProfilerPrintFormat GetProfilerPrintFormat(JNIEnv *env, jobject format) { return ProfilerPrintFormat(name); } +// The C API v2 has no call for the profiling information of a connection, so this is the only entry point that +// uses the engine: the C API v2 connection handle is the engine connection jstring _duckdb_jdbc_get_profiling_information(JNIEnv *env, jclass, jobject conn_ref_buf, jobject j_format) { - auto connection = get_connection(env, conn_ref_buf); - if (!connection) { + if (conn_ref_buf == nullptr) { + throw InvalidInputException("Invalid connection"); + } + auto handle = reinterpret_cast(env->GetDirectBufferAddress(conn_ref_buf)); + if (!handle) { throw InvalidInputException("Invalid connection"); } + auto connection = duckdb::capiv2::Convert(handle); auto format = GetProfilerPrintFormat(env, j_format); auto profiling_info = connection->GetProfilingInformation(format); return env->NewStringUTF(profiling_info.c_str()); diff --git a/src/jni/functions.cpp b/src/jni/functions.cpp index d50aa7d97..4a917d27c 100644 --- a/src/jni/functions.cpp +++ b/src/jni/functions.cpp @@ -1,168 +1,15 @@ // This file was generated by generator.py -#include "org_duckdb_DuckDBNative.h" #include "functions.hpp" -#include - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1startup(JNIEnv * env, jclass param0, jbyteArray param1, jboolean param2, jobject param3, jboolean param4) { - try { - return _duckdb_jdbc_startup(env, param0, param1, param2, param3, param4); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - return nullptr; - } -} - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1connect(JNIEnv * env, jclass param0, jobject param1) { - try { - return _duckdb_jdbc_connect(env, param0, param1); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - return nullptr; - } -} - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1create_1db_1ref(JNIEnv * env, jclass param0, jobject param1) { - try { - return _duckdb_jdbc_create_db_ref(env, param0, param1); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - return nullptr; - } -} - -JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1db_1address(JNIEnv * env, jclass param0, jobject param1) { - try { - return _duckdb_jdbc_db_address(env, param0, param1); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - return 0; - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1destroy_1db_1ref(JNIEnv * env, jclass param0, jobject param1) { - try { - return _duckdb_jdbc_destroy_db_ref(env, param0, param1); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1auto_1commit(JNIEnv * env, jclass param0, jobject param1, jboolean param2) { - try { - return _duckdb_jdbc_set_auto_commit(env, param0, param1, param2); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT jboolean JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1auto_1commit(JNIEnv * env, jclass param0, jobject param1) { - try { - return _duckdb_jdbc_get_auto_commit(env, param0, param1); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - return false; - } -} -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1disconnect(JNIEnv * env, jclass param0, jobject param1) { - try { - return _duckdb_jdbc_disconnect(env, param0, param1); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1schema(JNIEnv * env, jclass param0, jobject param1, jstring param2) { - try { - return _duckdb_jdbc_set_schema(env, param0, param1, param2); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1catalog(JNIEnv * env, jclass param0, jobject param1, jstring param2) { - try { - return _duckdb_jdbc_set_catalog(env, param0, param1, param2); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT jstring JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1schema(JNIEnv * env, jclass param0, jobject param1) { - try { - return _duckdb_jdbc_get_schema(env, param0, param1); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - return nullptr; - } -} - -JNIEXPORT jstring JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1catalog(JNIEnv * env, jclass param0, jobject param1) { - try { - return _duckdb_jdbc_get_catalog(env, param0, param1); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - return nullptr; - } -} - -JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1fetch_1size(JNIEnv * env, jclass param0) { - try { - return _duckdb_jdbc_fetch_size(env, param0); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - return -1; - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1register(JNIEnv * env, jclass param0, jobject param1, jlong param2, jbyteArray param3) { - try { - return _duckdb_jdbc_arrow_register(env, param0, param1, param2, param3); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - } -} - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1close_1streams(JNIEnv * env, jclass param0, jobject param1) { - try { - return _duckdb_jdbc_arrow_close_streams(env, param0, param1); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); +#include "org_duckdb_DuckDBNative.h" - } -} +#include -JNIEXPORT jstring JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1profiling_1information(JNIEnv * env, jclass param0, jobject param1, jobject param2) { +JNIEXPORT jstring JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1profiling_1information(JNIEnv *env, + jclass param0, + jobject param1, + jobject param2) { try { return _duckdb_jdbc_get_profiling_information(env, param0, param1, param2); } catch (const std::exception &e) { diff --git a/src/jni/functions.hpp b/src/jni/functions.hpp index a358709a5..accb45432 100644 --- a/src/jni/functions.hpp +++ b/src/jni/functions.hpp @@ -5,70 +5,14 @@ #include "duckdb/common/assert.hpp" #include "duckdb/common/error_data.hpp" #include "org_duckdb_DuckDBNative.h" -#include - -void ThrowJNI(JNIEnv* env, const char* message); - -jobject _duckdb_jdbc_startup(JNIEnv * env, jclass param0, jbyteArray param1, jboolean param2, jobject param3, jboolean param4); - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1startup(JNIEnv * env, jclass param0, jbyteArray param1, jboolean param2, jobject param3, jboolean param4); - -jobject _duckdb_jdbc_connect(JNIEnv * env, jclass param0, jobject param1); - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1connect(JNIEnv * env, jclass param0, jobject param1); - -jobject _duckdb_jdbc_create_db_ref(JNIEnv * env, jclass param0, jobject param1); - -JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1create_1db_1ref(JNIEnv * env, jclass param0, jobject param1); - -jlong _duckdb_jdbc_db_address(JNIEnv * env, jclass param0, jobject param1); - -JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1db_1address(JNIEnv * env, jclass param0, jobject param1); - -void _duckdb_jdbc_destroy_db_ref(JNIEnv * env, jclass param0, jobject param1); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1destroy_1db_1ref(JNIEnv * env, jclass param0, jobject param1); - -void _duckdb_jdbc_set_auto_commit(JNIEnv * env, jclass param0, jobject param1, jboolean param2); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1auto_1commit(JNIEnv * env, jclass param0, jobject param1, jboolean param2); - -jboolean _duckdb_jdbc_get_auto_commit(JNIEnv * env, jclass param0, jobject param1); - -JNIEXPORT jboolean JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1auto_1commit(JNIEnv * env, jclass param0, jobject param1); -void _duckdb_jdbc_disconnect(JNIEnv * env, jclass param0, jobject param1); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1disconnect(JNIEnv * env, jclass param0, jobject param1); - -void _duckdb_jdbc_set_schema(JNIEnv * env, jclass param0, jobject param1, jstring param2); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1schema(JNIEnv * env, jclass param0, jobject param1, jstring param2); - -void _duckdb_jdbc_set_catalog(JNIEnv * env, jclass param0, jobject param1, jstring param2); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1set_1catalog(JNIEnv * env, jclass param0, jobject param1, jstring param2); - -jstring _duckdb_jdbc_get_schema(JNIEnv * env, jclass param0, jobject param1); - -JNIEXPORT jstring JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1schema(JNIEnv * env, jclass param0, jobject param1); - -jstring _duckdb_jdbc_get_catalog(JNIEnv * env, jclass param0, jobject param1); - -JNIEXPORT jstring JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1catalog(JNIEnv * env, jclass param0, jobject param1); - -jint _duckdb_jdbc_fetch_size(JNIEnv * env, jclass param0); - -JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1fetch_1size(JNIEnv * env, jclass param0); - -void _duckdb_jdbc_arrow_register(JNIEnv * env, jclass param0, jobject param1, jlong param2, jbyteArray param3); - -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1register(JNIEnv * env, jclass param0, jobject param1, jlong param2, jbyteArray param3); - -void _duckdb_jdbc_arrow_close_streams(JNIEnv * env, jclass param0, jobject param1); +#include -JNIEXPORT void JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1arrow_1close_1streams(JNIEnv * env, jclass param0, jobject param1); +void ThrowJNI(JNIEnv *env, const char *message); -jstring _duckdb_jdbc_get_profiling_information(JNIEnv * env, jclass param0, jobject param1, jobject param2); +jstring _duckdb_jdbc_get_profiling_information(JNIEnv *env, jclass param0, jobject param1, jobject param2); -JNIEXPORT jstring JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1profiling_1information(JNIEnv * env, jclass param0, jobject param1, jobject param2); +JNIEXPORT jstring JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1profiling_1information(JNIEnv *env, + jclass param0, + jobject param1, + jobject param2); diff --git a/src/jni/holders.cpp b/src/jni/holders.cpp index 48d561f66..b004217d0 100644 --- a/src/jni/holders.cpp +++ b/src/jni/holders.cpp @@ -4,85 +4,17 @@ #include #include -ConnectionHolder *get_connection_ref(JNIEnv *env, jobject conn_ref_buf) { - if (!conn_ref_buf) { - throw duckdb::ConnectionException("Invalid connection buffer ref"); - } - auto conn_holder = reinterpret_cast(env->GetDirectBufferAddress(conn_ref_buf)); - if (!conn_holder) { - throw duckdb::ConnectionException("Invalid connection buffer"); - } - return conn_holder; -} - -void ConnectionHolder::track_arrow_stream(duckdb::shared_ptr state) { - std::lock_guard guard(arrow_streams_lock); - auto expired = [](const duckdb::weak_ptr &weak) { - return weak.expired(); - }; - arrow_streams.erase(std::remove_if(arrow_streams.begin(), arrow_streams.end(), expired), arrow_streams.end()); - arrow_streams.emplace_back(std::move(state)); -} - -void ConnectionHolder::close_arrow_streams() { - duckdb::vector> live; - { - std::lock_guard guard(arrow_streams_lock); - // Last stream created is first closed - for (auto it = arrow_streams.rbegin(); it != arrow_streams.rend(); ++it) { - auto state = it->lock(); - if (state) { - live.emplace_back(std::move(state)); - } - } - arrow_streams.clear(); - } - for (auto &state : live) { - state->Close(); - } -} - -/** - * Throws a SQLException and returns nullptr if a valid Connection can't be retrieved from the buffer. - */ -duckdb::Connection *get_connection(JNIEnv *env, jobject conn_ref_buf) { - auto conn_holder = get_connection_ref(env, conn_ref_buf); - auto conn_ref = conn_holder->connection.get(); - if (!conn_ref || !conn_ref->context) { - throw duckdb::ConnectionException("Invalid connection"); - } - - return conn_ref; -} - -static duckdb::capiv2::CV2Connection *conn_ref_buf_to_v2_conn(JNIEnv *env, jobject conn_ref_buf) { +duckdb_v2_connection_handle conn_ref_buf_to_conn(JNIEnv *env, jobject conn_ref_buf) { if (conn_ref_buf == nullptr) { env->ThrowNew(J_SQLException, "Invalid connection buffer"); return nullptr; } - auto conn_holder = reinterpret_cast(env->GetDirectBufferAddress(conn_ref_buf)); - if (conn_holder == nullptr) { - env->ThrowNew(J_SQLException, "Invalid connection holder"); - return nullptr; - } - auto conn_ref = conn_holder->connection.get(); - if (conn_ref == nullptr || conn_ref->context == nullptr) { + auto conn = reinterpret_cast(env->GetDirectBufferAddress(conn_ref_buf)); + if (conn == nullptr) { env->ThrowNew(J_SQLException, "Invalid connection"); return nullptr; } - return conn_ref; -} - -duckdb_v2_connection_handle conn_ref_buf_to_conn(JNIEnv *env, jobject conn_ref_buf) { - auto conn_ref = conn_ref_buf_to_v2_conn(env, conn_ref_buf); - if (conn_ref == nullptr) { - return nullptr; - } - return duckdb::capiv2::Convert(conn_ref); -} - -duckdb::Connection *conn_ref_buf_to_engine_conn(JNIEnv *env, jobject conn_ref_buf) { - return conn_ref_buf_to_v2_conn(env, conn_ref_buf); + return conn; } ChunkedResultHolder::ChunkedResultHolder(duckdb_v2_result_handle result_p) : result(result_p) { diff --git a/src/jni/holders.hpp b/src/jni/holders.hpp index 20966c3f6..86ce4723a 100644 --- a/src/jni/holders.hpp +++ b/src/jni/holders.hpp @@ -1,8 +1,6 @@ #pragma once #include "capi_v2.hpp" -#include "duckdb.hpp" -#include "duckdb/main/capi_v2/capi_v2_internal.hpp" #include "refs.hpp" #include @@ -10,82 +8,6 @@ #include #include -/** - * Holds a copy of a shared_ptr to an existing DB instance. - * Is used to keep this DB alive (and accessible from DB cache) - * even after the last connection to this DB is closed. - */ -struct DBHolder { - duckdb::shared_ptr db; - - DBHolder(duckdb::shared_ptr _db) : db(std::move(_db)) {}; - - DBHolder(const DBHolder &) = delete; - - DBHolder &operator=(const DBHolder &) = delete; -}; - -/** - * State of an Arrow stream exported from or registered with a connection. Arrow streams are owned by their consumers - * and can outlive the connection, connection closes the state of all its live streams before it is disconnected. - */ -struct ArrowStreamState { - virtual ~ArrowStreamState() = default; - - //! Releases the resources held by the stream, must be idempotent - virtual void Close() = 0; -}; - -/** - * Associates a duckdb::Connection with a duckdb::DuckDB. The DB may be shared amongst many ConnectionHolders, but the - * Connection is unique to this holder. Every Java DuckDBConnection has exactly 1 of these holders, and they are never - * shared. The holder is freed when the DuckDBConnection is closed. When the last holder sharing a DuckDB is freed, the - * DuckDB is released as well. - * - * The connection is created as a capiv2::CV2Connection (that is a duckdb::Connection) so it can also be used as - * a connection handle of the C API v2. - */ -struct ConnectionHolder { - const duckdb::shared_ptr db; - const duckdb::unique_ptr connection; - - ConnectionHolder(duckdb::shared_ptr _db) - : db(_db), connection(duckdb::make_uniq(*_db)) { - } - - ~ConnectionHolder() { - close_arrow_streams(); - } - - void track_arrow_stream(duckdb::shared_ptr state); - - void close_arrow_streams(); - - DBHolder *create_db_ref() { - return new DBHolder(db); - } - -private: - std::mutex arrow_streams_lock; - //! Streams are untracked implicitly when they are released by their consumers - duckdb::vector> arrow_streams; -}; - -struct StatementHolder { - duckdb::unique_ptr stmt; -}; - -struct PendingHolder { - duckdb::unique_ptr pending; - bool streaming = false; -}; - -struct ResultHolder { - duckdb::unique_ptr res; - duckdb::unique_ptr> stream; - duckdb::unique_ptr chunk; -}; - /** * Result of a prepared statement execution that is read by chunks (see DuckDBChunkedResult) using C API v2. * The column names and types are captured when the result is created, the error is set when fetching of @@ -139,17 +61,8 @@ struct LocalRefHolder { ~LocalRefHolder() noexcept; }; -ConnectionHolder *get_connection_ref(JNIEnv *env, jobject conn_ref_buf); - -duckdb::Connection *get_connection(JNIEnv *env, jobject conn_ref_buf); - /** - * Returns the C API v2 handle of the connection of the specified holder. Throws a SQLException and returns nullptr - * if a valid Connection can't be retrieved from the buffer. + * Returns the C API v2 handle of the connection that is passed from Java as a direct buffer. Throws a SQLException and + * returns nullptr if a valid connection can't be retrieved from the buffer. */ duckdb_v2_connection_handle conn_ref_buf_to_conn(JNIEnv *env, jobject conn_ref_buf); - -/** - * Same as conn_ref_buf_to_conn, returns the engine connection. - */ -duckdb::Connection *conn_ref_buf_to_engine_conn(JNIEnv *env, jobject conn_ref_buf); diff --git a/src/jni/types.cpp b/src/jni/types.cpp deleted file mode 100644 index 2bcbb8668..000000000 --- a/src/jni/types.cpp +++ /dev/null @@ -1,261 +0,0 @@ -#include "types.hpp" - -#include "refs.hpp" -#include "util.hpp" - -#include -#include - -std::string type_to_jduckdb_type(duckdb::LogicalType logical_type) { - switch (logical_type.id()) { - case duckdb::LogicalTypeId::DECIMAL: { - - uint32_t width = 0; - uint32_t scale = 0; - logical_type.GetDecimalProperties(width, scale); - std::string width_scale = std::to_string(width) + std::string(";") + std::to_string(scale); - - auto physical_type = logical_type.InternalType(); - switch (physical_type) { - case duckdb::PhysicalType::INT16: { - std::string res = std::string("DECIMAL16;") + width_scale; - return res; - } - case duckdb::PhysicalType::INT32: { - std::string res = std::string("DECIMAL32;") + width_scale; - return res; - } - case duckdb::PhysicalType::INT64: { - std::string res = std::string("DECIMAL64;") + width_scale; - return res; - } - case duckdb::PhysicalType::INT128: { - std::string res = std::string("DECIMAL128;") + width_scale; - return res; - } - default: - return std::string("no physical type found"); - } - } break; - default: - // JSON requires special handling because it is mapped - // to JsonNode class - if (logical_type.IsJSONType()) { - return logical_type.GetAlias(); - } - return duckdb::EnumUtil::ToString(logical_type.id()); - } -} - -duckdb::Value create_value_from_bigdecimal(JNIEnv *env, jobject decimal) { - jint precision = env->CallIntMethod(decimal, J_BigDecimal_precision); - check_java_exception_and_rethrow(env); - jint scale = env->CallIntMethod(decimal, J_BigDecimal_scale); - check_java_exception_and_rethrow(env); - - // Java BigDecimal type can have scale that exceeds the precision - // Which our DECIMAL type does not support (assert(width >= scale)) - if (scale > precision) { - precision = scale; - } - - // DECIMAL scale is unsigned, so negative values are not supported - if (scale < 0) { - throw duckdb::InvalidInputException("Converting from a BigDecimal with negative scale is not supported"); - } - - duckdb::Value val; - - if (precision <= 18) { // normal sizes -> avoid string processing - jobject no_point_dec = env->CallObjectMethod(decimal, J_BigDecimal_scaleByPowTen, scale); - check_java_exception_and_rethrow(env); - jlong result = env->CallLongMethod(no_point_dec, J_BigDecimal_longValue); - check_java_exception_and_rethrow(env); - val = duckdb::Value::DECIMAL((int64_t)result, (uint8_t)precision, (uint8_t)scale); - } else if (precision <= 38) { // larger than int64 -> get string and cast - jobject str_val = env->CallObjectMethod(decimal, J_BigDecimal_toPlainString); - check_java_exception_and_rethrow(env); - auto *str_char = env->GetStringUTFChars((jstring)str_val, 0); - val = duckdb::Value(str_char); - val = val.DefaultCastAs(duckdb::LogicalType::DECIMAL(precision, scale)); - env->ReleaseStringUTFChars((jstring)str_val, str_char); - } - - return val; -} - -static duckdb::Value create_value_from_hugeint(JNIEnv *env, jobject hugeint) { - jlong lower = env->GetLongField(hugeint, J_HugeInt_lower); - jlong upper = env->GetLongField(hugeint, J_HugeInt_upper); - duckdb::hugeint_t hi(upper, lower); - return duckdb::Value::HUGEINT(std::move(hi)); -} - -static duckdb::Value create_value_from_uuid(JNIEnv *env, jobject param) { - jlong most_significant = env->CallLongMethod(param, J_UUID_getMostSignificantBits); - check_java_exception_and_rethrow(env); - // Account for the following logic in UUID::FromString: - // Flip the first bit to make `order by uuid` same as `order by uuid::varchar` - most_significant ^= (std::numeric_limits::min)(); - jlong least_significant = env->CallLongMethod(param, J_UUID_getLeastSignificantBits); - check_java_exception_and_rethrow(env); - duckdb::hugeint_t hi = duckdb::hugeint_t(most_significant, least_significant); - return duckdb::Value::UUID(std::move(hi)); -} - -static duckdb::Value create_value_from_map(JNIEnv *env, jobject param, duckdb::ClientContext &context) { - jstring jstr = reinterpret_cast(env->CallObjectMethod(param, J_DuckMap_getSQLTypeName)); - check_java_exception_and_rethrow(env); - auto typeName = jstring_to_string(env, jstr); - - duckdb::LogicalType type; - context.RunFunctionInTransaction([&]() { type = duckdb::TransformStringToLogicalType(typeName, context); }); - - auto entrySet = env->CallObjectMethod(param, J_Map_entrySet); - check_java_exception_and_rethrow(env); - auto iterator = env->CallObjectMethod(entrySet, J_Set_iterator); - check_java_exception_and_rethrow(env); - duckdb::vector entries; - while (env->CallBooleanMethod(iterator, J_Iterator_hasNext)) { - check_java_exception_and_rethrow(env); - auto entry = env->CallObjectMethod(iterator, J_Iterator_next); - check_java_exception_and_rethrow(env); - - auto key = env->CallObjectMethod(entry, J_Entry_getKey); - check_java_exception_and_rethrow(env); - auto value = env->CallObjectMethod(entry, J_Entry_getValue); - check_java_exception_and_rethrow(env); - D_ASSERT(key); - D_ASSERT(value); - - entries.push_back(duckdb::Value::STRUCT( - {{"key", to_duckdb_value(env, key, context)}, {"value", to_duckdb_value(env, value, context)}})); - } - check_java_exception_and_rethrow(env); - - return duckdb::Value::MAP(duckdb::ListType::GetChildType(type), entries); -} - -static duckdb::Value create_value_from_struct(JNIEnv *env, jobject param, duckdb::ClientContext &context) { - jstring jstr = reinterpret_cast(env->CallObjectMethod(param, J_Struct_getSQLTypeName)); - check_java_exception_and_rethrow(env); - auto typeName = jstring_to_string(env, jstr); - - duckdb::LogicalType type; - context.RunFunctionInTransaction([&]() { type = TransformStringToLogicalType(typeName, context); }); - - jobjectArray jvalues = reinterpret_cast(env->CallObjectMethod(param, J_Struct_getAttributes)); - check_java_exception_and_rethrow(env); - - int size = env->GetArrayLength(jvalues); - - duckdb::child_list_t values; - - for (int i = 0; i < size; i++) { - auto name = duckdb::StructType::GetChildName(type, i); - auto jvalue = env->GetObjectArrayElement(jvalues, i); - auto value = to_duckdb_value(env, jvalue, context); - env->DeleteLocalRef(jvalue); - values.emplace_back(name, std::move(value)); - } - - return duckdb::Value::STRUCT(std::move(values)); -} - -static duckdb::Value create_value_from_array(JNIEnv *env, jobject param, duckdb::ClientContext &context) { - jstring jstr = reinterpret_cast(env->CallObjectMethod(param, J_Array_getBaseTypeName)); - check_java_exception_and_rethrow(env); - auto typeName = jstring_to_string(env, jstr); - jobjectArray jvalues = reinterpret_cast(env->CallObjectMethod(param, J_Array_getArray)); - check_java_exception_and_rethrow(env); - int size = env->GetArrayLength(jvalues); - - duckdb::LogicalType type; - context.RunFunctionInTransaction([&]() { type = TransformStringToLogicalType(typeName, context); }); - - duckdb::vector values; - for (int i = 0; i < size; i++) { - auto jvalue = env->GetObjectArrayElement(jvalues, i); - auto value = to_duckdb_value(env, jvalue, context); - env->DeleteLocalRef(jvalue); - values.emplace_back(std::move(value)); - } - - return (duckdb::Value::LIST(type, values)); -} - -duckdb::Value to_duckdb_value(JNIEnv *env, jobject param, duckdb::ClientContext &context) { - param = env->CallStaticObjectMethod(J_Timestamp, J_Timestamp_valueOf, param); - check_java_exception_and_rethrow(env); - - if (param == nullptr) { - return (duckdb::Value()); - } else if (env->IsInstanceOf(param, J_Bool)) { - jboolean val = env->CallBooleanMethod(param, J_Bool_booleanValue); - check_java_exception_and_rethrow(env); - return duckdb::Value::BOOLEAN(val); - } else if (env->IsInstanceOf(param, J_Byte)) { - jbyte val = env->CallByteMethod(param, J_Byte_byteValue); - check_java_exception_and_rethrow(env); - return duckdb::Value::TINYINT(val); - } else if (env->IsInstanceOf(param, J_Short)) { - jshort val = env->CallShortMethod(param, J_Short_shortValue); - check_java_exception_and_rethrow(env); - return duckdb::Value::SMALLINT(val); - } else if (env->IsInstanceOf(param, J_Int)) { - jint val = env->CallIntMethod(param, J_Int_intValue); - check_java_exception_and_rethrow(env); - return duckdb::Value::INTEGER(val); - } else if (env->IsInstanceOf(param, J_Long)) { - jlong val = env->CallLongMethod(param, J_Long_longValue); - check_java_exception_and_rethrow(env); - return duckdb::Value::BIGINT(val); - } else if (env->IsInstanceOf(param, J_HugeInt)) { - return create_value_from_hugeint(env, param); - } else if (env->IsInstanceOf(param, J_TimestampTZ)) { // Check for subclass before superclass! - jlong val = env->CallLongMethod(param, J_TimestampTZ_getMicrosEpoch); - check_java_exception_and_rethrow(env); - return duckdb::Value::TIMESTAMPTZ(static_cast(val)); - } else if (env->IsInstanceOf(param, J_DuckDBDate)) { - jlong val = env->CallLongMethod(param, J_DuckDBDate_getDaysSinceEpoch); - check_java_exception_and_rethrow(env); - return duckdb::Value::DATE(static_cast(val)); - } else if (env->IsInstanceOf(param, J_DuckDBTime)) { - jlong val = env->CallLongMethod(param, J_Timestamp_getMicrosEpoch); - check_java_exception_and_rethrow(env); - return duckdb::Value::TIME(static_cast(val)); - } else if (env->IsInstanceOf(param, J_TimestampNS)) { // Check for subclass before superclass! - jlong val = env->CallLongMethod(param, J_TimestampNS_getNanosEpoch); - check_java_exception_and_rethrow(env); - return duckdb::Value::TIMESTAMPNS(static_cast(val)); - } else if (env->IsInstanceOf(param, J_Timestamp)) { - jlong val = env->CallLongMethod(param, J_Timestamp_getMicrosEpoch); - check_java_exception_and_rethrow(env); - return duckdb::Value::TIMESTAMP(static_cast(val)); - } else if (env->IsInstanceOf(param, J_Float)) { - jfloat val = env->CallFloatMethod(param, J_Float_floatValue); - check_java_exception_and_rethrow(env); - return duckdb::Value::FLOAT(val); - } else if (env->IsInstanceOf(param, J_Double)) { - jdouble val = env->CallDoubleMethod(param, J_Double_doubleValue); - check_java_exception_and_rethrow(env); - return duckdb::Value::DOUBLE(val); - } else if (env->IsInstanceOf(param, J_BigDecimal)) { - return create_value_from_bigdecimal(env, param); - } else if (env->IsInstanceOf(param, J_String)) { - auto param_string = jstring_to_string(env, (jstring)param); - return (duckdb::Value(param_string)); - } else if (env->IsInstanceOf(param, J_ByteArray)) { - return (duckdb::Value::BLOB_RAW(jbyteArray_to_string(env, (jbyteArray)param))); - } else if (env->IsInstanceOf(param, J_UUID)) { - return create_value_from_uuid(env, param); - } else if (env->IsInstanceOf(param, J_DuckMap)) { - return create_value_from_map(env, param, context); - } else if (env->IsInstanceOf(param, J_Struct)) { - return create_value_from_struct(env, param, context); - } else if (env->IsInstanceOf(param, J_Array)) { - return create_value_from_array(env, param, context); - } else { - throw duckdb::InvalidInputException("Unsupported parameter type"); - } -} diff --git a/src/jni/types.hpp b/src/jni/types.hpp deleted file mode 100644 index adbf36da9..000000000 --- a/src/jni/types.hpp +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include "duckdb.hpp" - -#include - -std::string type_to_jduckdb_type(duckdb::LogicalType logical_type); - -duckdb::Value create_value_from_bigdecimal(JNIEnv *env, jobject decimal); - -duckdb::Value to_duckdb_value(JNIEnv *env, jobject param, duckdb::ClientContext &context); diff --git a/src/main/java/org/duckdb/DuckDBBindings.java b/src/main/java/org/duckdb/DuckDBBindings.java index 57fc799de..219734ab5 100644 --- a/src/main/java/org/duckdb/DuckDBBindings.java +++ b/src/main/java/org/duckdb/DuckDBBindings.java @@ -278,9 +278,6 @@ static native void duckdb_vector_assign_string_elements(ByteBuffer vector, long // C API v2 - // transitional: the C API v2 connection of a connection reference - static native ByteBuffer duckdb_v2_connection_from_ref(ByteBuffer conn_ref) throws SQLException; - static native void duckdb_v2_connection_interrupt(ByteBuffer conn) throws SQLException; static native QueryProgress duckdb_v2_connection_progress_get(ByteBuffer conn) throws SQLException; @@ -476,6 +473,111 @@ static native void duckdb_v2_column_data_collection_append(ByteBuffer collection static native void duckdb_v2_statement_add_collection(ByteBuffer statement, byte[] name, ByteBuffer collection, byte[][] column_names) throws SQLException; + // environments, instances and connections + + // the initializer of a new shared instance, called with the instance (that is borrowed for the call) + interface InstanceInit { + void init(ByteBuffer instance) throws SQLException; + } + + static native ByteBuffer duckdb_v2_environment_create() throws SQLException; + + static native void duckdb_v2_environment_destroy(ByteBuffer environment) throws SQLException; + + static native ByteBuffer duckdb_v2_instance_create_with_options(ByteBuffer environment, byte[][] names, + byte[][] values) throws SQLException; + + // opens the shared instance of the path, the initializer (can be null) is called when the instance is created + static native ByteBuffer duckdb_v2_instance_open_shared(ByteBuffer environment, byte[] path, byte[][] names, + byte[][] values, InstanceInit init) throws SQLException; + + // the name can be null + static native void duckdb_v2_instance_attach(ByteBuffer instance, byte[] name, byte[] path, boolean makeDefault) + throws SQLException; + + static native void duckdb_v2_instance_destroy(ByteBuffer instance) throws SQLException; + + // the returned config is borrowed from the instance + static native ByteBuffer duckdb_v2_instance_get_config(ByteBuffer instance) throws SQLException; + + static native ByteBuffer duckdb_v2_connection_create(ByteBuffer instance) throws SQLException; + + static native void duckdb_v2_connection_destroy(ByteBuffer conn) throws SQLException; + + // configuration + + static final int SCOPE_DEFAULT = 0; + static final int SCOPE_GLOBAL = 1; + static final int SCOPE_SESSION = 2; + + static native void duckdb_v2_config_set_option_text(ByteBuffer config, byte[] name, byte[] value, int scope) + throws SQLException; + + // the value is borrowed for the call + static native void duckdb_v2_config_set_option_value(ByteBuffer config, byte[] name, ByteBuffer value, int scope) + throws SQLException; + + static native long duckdb_v2_config_get_option_count(ByteBuffer config) throws SQLException; + + // the returned option is owned by the caller + static native ByteBuffer duckdb_v2_config_get_option_by_index(ByteBuffer config, long index) throws SQLException; + + static native byte[] duckdb_v2_option_get_name(ByteBuffer option) throws SQLException; + + static native boolean duckdb_v2_option_supports_scope(ByteBuffer option, int scope) throws SQLException; + + static native void duckdb_v2_option_destroy(ByteBuffer option) throws SQLException; + + // the scope that the value comes from is written to scope_out[0], scope_out can be null + static native ByteBuffer duckdb_v2_config_get_option_value_scoped(ByteBuffer config, byte[] name, int[] scope_out) + throws SQLException; + + // custom options + + static native ByteBuffer duckdb_v2_custom_option_create(ByteBuffer factory) throws SQLException; + + static native void duckdb_v2_custom_option_destroy(ByteBuffer option) throws SQLException; + + static native void duckdb_v2_custom_option_set_name(ByteBuffer option, byte[] name) throws SQLException; + + // the type is borrowed for the call + static native void duckdb_v2_custom_option_set_type(ByteBuffer option, ByteBuffer type) throws SQLException; + + // the value is borrowed for the call + static native void duckdb_v2_custom_option_set_default_value(ByteBuffer option, ByteBuffer value) + throws SQLException; + + static native void duckdb_v2_custom_option_set_description(ByteBuffer option, byte[] description) + throws SQLException; + + static native void duckdb_v2_custom_option_set_default_scope(ByteBuffer option, int scope) throws SQLException; + + static native void duckdb_v2_custom_option_set_supports_scope(ByteBuffer option, int scope, boolean supported) + throws SQLException; + + static native void duckdb_v2_connection_register_custom_option(ByteBuffer conn, ByteBuffer option) + throws SQLException; + + // Arrow export + + // Executes the statement (that reads the collection) on the helper connection with the Arrow result format and + // returns the address of the ArrowArrayStream. The stream owns the helper connection, the statement and the + // collection (the stream is released by its consumer), conn is the connection that the stream is closed with. + static native long duckdb_v2_arrow_export_stream(ByteBuffer conn, ByteBuffer helper, ByteBuffer statement, + ByteBuffer collection, long batch_size) throws SQLException; + + // registers the table function that scans the registered Arrow streams + static native void duckdb_v2_arrow_register_scan_function(ByteBuffer conn) throws SQLException; + + // moves the stream (the address of an ArrowArrayStream) out of its struct and registers it, returns its id + static native long duckdb_v2_arrow_register_stream(ByteBuffer conn, long stream_address) throws SQLException; + + // releases the registered stream, if it is not consumed or released yet + static native void duckdb_v2_arrow_release_stream(long id); + + // closes the exported and the registered streams of the connection that are not released by their consumers yet + static native void duckdb_v2_arrow_close_streams(ByteBuffer conn); + // DUCKDB_V2_RESULT_STEP_STATUS static final int RESULT_STEP_WAITING = 0; static final int RESULT_STEP_CHUNK = 1; diff --git a/src/main/java/org/duckdb/DuckDBConnection.java b/src/main/java/org/duckdb/DuckDBConnection.java index 8f88b2261..52e5d2d75 100644 --- a/src/main/java/org/duckdb/DuckDBConnection.java +++ b/src/main/java/org/duckdb/DuckDBConnection.java @@ -36,6 +36,9 @@ public final class DuckDBConnection implements java.sql.Connection { public static final String DEFAULT_SCHEMA = "main"; ByteBuffer connRef; + DuckDBInstances.InstanceRef instanceRef; + // The ids of the Arrow streams that are registered with the connection, by the names of their views + final java.util.HashMap arrowStreams = new java.util.HashMap<>(); final ReentrantLock connRefLock = new ReentrantLock(); final LinkedHashSet pendingQueries = new LinkedHashSet<>(); final LinkedHashSet preparedStatements = new LinkedHashSet<>(); @@ -85,22 +88,20 @@ public static DuckDBConnection newConnection(String url, boolean readOnly, Strin String monitorName = removeOption(properties, DuckDBDriver.JDBC_JFR_MEMORY_MONITOR); String instanceCacheStr = removeOption(properties, DuckDBDriver.JDBC_INSTANCE_CACHE); boolean instanceCache = isStringTruish(instanceCacheStr, true); - ByteBuffer nativeReference = - DuckDBNative.duckdb_jdbc_startup(dbName.getBytes(UTF_8), readOnly, properties, instanceCache); - return new DuckDBConnection(nativeReference, url, readOnly, sessionInitSQL, autoCommit, monitorName); + DuckDBInstances.Connected connected = DuckDBInstances.startup(dbName, readOnly, properties, instanceCache); + return new DuckDBConnection(connected, url, readOnly, sessionInitSQL, autoCommit, monitorName); } - private DuckDBConnection(ByteBuffer connectionReference, String url, boolean readOnly, String sessionInitSQL, + private DuckDBConnection(DuckDBInstances.Connected connected, String url, boolean readOnly, String sessionInitSQL, boolean autoCommit, String monitorName) throws SQLException { - this.connRef = connectionReference; + this.connRef = connected.conn; + this.instanceRef = connected.instanceRef; this.url = url; this.readOnly = readOnly; this.autoCommit = autoCommit; this.sessionInitSQL = sessionInitSQL; this.monitorName = (monitorName != null && !monitorName.isEmpty()) ? monitorName : null; - this.dbAddress = DuckDBNative.duckdb_jdbc_db_address(connectionReference); - // Hardcoded 'true' here is intentional, autocommit is handled in stmt#execute() - DuckDBNative.duckdb_jdbc_set_auto_commit(connectionReference, true); + this.dbAddress = connected.instanceRef.address; if (this.monitorName != null) { JfrMemoryMonitor.connectionOpened(this); } @@ -146,8 +147,8 @@ private DuckDBConnection duplicate(String monitorName) throws SQLException { connRefLock.lock(); try { checkOpen(); - ByteBuffer dupRef = DuckDBNative.duckdb_jdbc_connect(connRef); - return new DuckDBConnection(dupRef, url, readOnly, sessionInitSQL, autoCommit, monitorName); + DuckDBInstances.Connected dup = DuckDBInstances.connect(this); + return new DuckDBConnection(dup, url, readOnly, sessionInitSQL, autoCommit, monitorName); } finally { connRefLock.unlock(); } @@ -222,7 +223,7 @@ public void close() throws SQLException { // on Java side, last stream created is first closed on native side DuckDBNative.duckdb_jdbc_arrow_close_streams(connRef); - DuckDBNative.duckdb_jdbc_disconnect(connRef); + DuckDBInstances.disconnect(connRef, instanceRef); connRef = null; notifyMonitor = (monitorName != null); } finally { @@ -293,9 +294,6 @@ public void setAutoCommit(boolean autoCommit) throws SQLException { } } return; - - // Native method is not working as one would expect ... uncomment maybe later - // DuckDBNative.duckdb_jdbc_set_auto_commit(conn_ref, autoCommit); } public boolean getAutoCommit() throws SQLException { @@ -303,9 +301,6 @@ public boolean getAutoCommit() throws SQLException { throw createSQLException("Connection was closed", ErrorCode.CONNECTION_CLOSED); } return this.autoCommit; - - // Native method is not working as one would expect ... uncomment maybe later - // return DuckDBNative.duckdb_jdbc_get_auto_commit(conn_ref); } public PreparedStatement prepareStatement(String sql) throws SQLException { @@ -327,7 +322,7 @@ public void setCatalog(String catalog) throws SQLException { connRefLock.lock(); try { checkOpen(); - DuckDBNative.duckdb_jdbc_set_catalog(connRef, catalog); + DuckDBCore.setCatalog(this, catalog); } finally { connRefLock.unlock(); } @@ -338,7 +333,7 @@ public String getCatalog() throws SQLException { connRefLock.lock(); try { checkOpen(); - return DuckDBNative.duckdb_jdbc_get_catalog(connRef); + return DuckDBCore.getCatalog(this); } finally { connRefLock.unlock(); } @@ -349,7 +344,7 @@ public void setSchema(String schema) throws SQLException { connRefLock.lock(); try { checkOpen(); - DuckDBNative.duckdb_jdbc_set_schema(connRef, schema); + DuckDBCore.setSchema(this, schema); } finally { connRefLock.unlock(); } @@ -360,7 +355,7 @@ public String getSchema() throws SQLException { connRefLock.lock(); try { checkOpen(); - return DuckDBNative.duckdb_jdbc_get_schema(connRef); + return DuckDBCore.getSchema(this); } finally { connRefLock.unlock(); } @@ -585,7 +580,7 @@ public void registerArrowStream(String name, Object arrow_array_stream) { connRefLock.lock(); try { checkOpen(); - DuckDBNative.duckdb_jdbc_arrow_register(connRef, array_stream_address, name.getBytes(UTF_8)); + DuckDBNative.duckdb_jdbc_arrow_register(this, array_stream_address, name); } finally { connRefLock.unlock(); } diff --git a/src/main/java/org/duckdb/DuckDBCore.java b/src/main/java/org/duckdb/DuckDBCore.java index cd0f8a74c..73ab7d052 100644 --- a/src/main/java/org/duckdb/DuckDBCore.java +++ b/src/main/java/org/duckdb/DuckDBCore.java @@ -142,7 +142,7 @@ private static ByteBuffer conn(ByteBuffer connRef) throws SQLException { if (connRef == null) { throw invalid("Invalid connection"); } - return duckdb_v2_connection_from_ref(connRef); + return connRef; } private static long fieldCount(ByteBuffer schema) throws SQLException { @@ -425,6 +425,49 @@ static ByteBuffer queryValue(DuckDBConnection connection, String sql) throws SQL } } + /** Runs the statement and discards its result. */ + static void executeSql(DuckDBConnection connection, String sql) throws SQLException { + connection.queryGate.acquireUninterruptibly(); + try { + ByteBuffer conn = conn(connection.connRef); + ByteBuffer statement = parseSingleStatement(conn, sql); + ByteBuffer result; + try { + result = duckdb_v2_statement_execute(conn, statement, null); + } finally { + duckdb_v2_sql_statement_destroy(statement); + } + try { + duckdb_v2_result_drain(result); + } finally { + duckdb_v2_result_destroy(result); + } + } finally { + connection.queryGate.release(); + } + } + + private static String queryString(DuckDBConnection connection, String sql) throws SQLException { + List res = queryStrings(connection, sql); + return res.isEmpty() ? null : res.get(0); + } + + static String getSchema(DuckDBConnection connection) throws SQLException { + return queryString(connection, "SELECT current_schema()"); + } + + static String getCatalog(DuckDBConnection connection) throws SQLException { + return queryString(connection, "SELECT current_database()"); + } + + static void setSchema(DuckDBConnection connection, String schema) throws SQLException { + executeSql(connection, "SET schema = " + DuckDBV2Appender.quoteLiteral(schema)); + } + + static void setCatalog(DuckDBConnection connection, String catalog) throws SQLException { + executeSql(connection, "USE " + DuckDBV2Appender.quoteIdentifier(catalog)); + } + // --------------------------------------------------------------------------------------------------------- // Execution // --------------------------------------------------------------------------------------------------------- @@ -567,6 +610,115 @@ static void freeResult(ResultRef ref) throws SQLException { } } + /** + * Registers the Arrow stream (the address of an ArrowArrayStream) with the connection as a view with the name. The + * stream is moved out of its struct, it is released when it is consumed by a scan, when the view is replaced or + * when the connection is closed. + */ + static void registerArrowStream(DuckDBConnection connection, long streamAddress, String name) throws SQLException { + long id = duckdb_v2_arrow_register_stream(conn(connection.connRef), streamAddress); + try { + executeSql(connection, "CREATE OR REPLACE TEMPORARY VIEW " + DuckDBV2Appender.quoteIdentifier(name) + + " AS SELECT * FROM __jdbc_arrow_stream_scan(" + id + ")"); + } catch (SQLException e) { + duckdb_v2_arrow_release_stream(id); + throw new SQLException("Failed to create view '" + name + + "': " + DuckDBInstances.rawMessage(e.getMessage())); + } + // the stream of the view that is replaced is released + Long replaced = connection.arrowStreams.put(name, id); + if (replaced != null) { + duckdb_v2_arrow_release_stream(replaced); + } + } + + private static final byte[] ARROW_ROWS_NAME = "__jdbc_result_rows".getBytes(UTF_8); + + /** + * Exports the rows of the result that are not read yet as an Arrow stream of record batches of at most + * batchSize rows, returns the address of the ArrowArrayStream. The rows are moved into the stream, a result that is + * streamed is read into the memory first. The rows are bound to a statement (SELECT * FROM the rows) that runs on + * a connection of its own, so that the connection of the result stays usable while the stream is open. + */ + static long exportArrow(ResultRef ref, DuckDBConnection connection, long batchSize) throws SQLException { + if (ref == null || ref.schema == null) { + throw invalid("Invalid result set"); + } + if (batchSize <= 0) { + throw invalid("Arrow batch size must be greater than 0"); + } + connection.queryGate.acquireUninterruptibly(); + ByteBuffer collection = null; + ByteBuffer helper = null; + ByteBuffer statement = null; + try { + ByteBuffer connHandle = conn(connection.connRef); + ByteBuffer factory = duckdb_v2_connection_get_factory(connHandle); + if (ref.currentChunk != null) { + duckdb_destroy_data_chunk(ref.currentChunk); + ref.currentChunk = null; + } + int columnCount = ref.names.length; + ByteBuffer[] types = new ByteBuffer[columnCount]; + byte[][] names = new byte[columnCount][]; + for (int i = 0; i < columnCount; i++) { + types[i] = duckdb_v2_schema_get_field_type(ref.schema, i); + names[i] = ref.names[i].getBytes(UTF_8); + } + collection = duckdb_v2_column_data_collection_create(factory, types); + ByteBuffer appendState = duckdb_v2_column_data_collection_append_state_create(collection); + try { + ByteBuffer chunk; + while ((chunk = ref.chunks.poll()) != null) { + try { + duckdb_v2_column_data_collection_append(collection, appendState, chunk); + } finally { + duckdb_destroy_data_chunk(chunk); + } + } + if (ref.streamResult != null) { + ByteBuffer result = ref.streamResult; + ref.streamResult = null; + try { + while ((chunk = duckdb_v2_result_fetch_chunk(result)) != null) { + try { + duckdb_v2_column_data_collection_append(collection, appendState, chunk); + } finally { + duckdb_destroy_data_chunk(chunk); + } + } + } finally { + duckdb_v2_result_destroy(result); + } + } + } finally { + duckdb_v2_column_data_collection_append_state_destroy(appendState); + } + + helper = duckdb_v2_connection_create(connection.instanceRef.instance()); + DuckDBInstances.copySessionSettings(connHandle, helper); + statement = parseSingleStatement(helper, "SELECT * FROM " + new String(ARROW_ROWS_NAME, UTF_8)); + duckdb_v2_statement_add_collection(statement, ARROW_ROWS_NAME, collection, names); + long address = duckdb_v2_arrow_export_stream(connHandle, helper, statement, collection, batchSize); + // the stream owns them now + statement = null; + collection = null; + helper = null; + return address; + } finally { + if (statement != null) { + duckdb_v2_sql_statement_destroy(statement); + } + if (collection != null) { + duckdb_v2_column_data_collection_destroy(collection); + } + if (helper != null) { + duckdb_v2_connection_destroy(helper); + } + connection.queryGate.release(); + } + } + // --------------------------------------------------------------------------------------------------------- // Metadata // --------------------------------------------------------------------------------------------------------- diff --git a/src/main/java/org/duckdb/DuckDBDriver.java b/src/main/java/org/duckdb/DuckDBDriver.java index 73c4ac359..5caa79409 100644 --- a/src/main/java/org/duckdb/DuckDBDriver.java +++ b/src/main/java/org/duckdb/DuckDBDriver.java @@ -40,7 +40,7 @@ public class DuckDBDriver implements java.sql.Driver { static final ScheduledThreadPoolExecutor scheduler; - private static final LinkedHashMap pinnedDbRefs = new LinkedHashMap<>(); + private static final LinkedHashMap pinnedDbRefs = new LinkedHashMap<>(); private static final ReentrantLock pinnedDbRefsLock = new ReentrantLock(); private static boolean pinnedDbRefsShutdownHookRegistered = false; private static boolean pinnedDbRefsShutdownHookRun = false; @@ -246,7 +246,7 @@ private static void pinDB(boolean pinnedDbOpt, String url, DuckDBConnection conn } // No need to hold connRef lock here, this connection is not // yet available to client at this point, so it cannot be closed. - ByteBuffer dbRef = DuckDBNative.duckdb_jdbc_create_db_ref(conn.connRef); + DuckDBInstances.InstanceRef dbRef = conn.instanceRef.retain(); pinnedDbRefs.put(dbName, dbRef); if (!pinnedDbRefsShutdownHookRegistered) { @@ -265,11 +265,11 @@ public static boolean releaseDB(String url) throws SQLException { return false; } String dbName = dbNameFromUrl(url); - ByteBuffer dbRef = pinnedDbRefs.remove(dbName); + DuckDBInstances.InstanceRef dbRef = pinnedDbRefs.remove(dbName); if (null == dbRef) { return false; } - DuckDBNative.duckdb_jdbc_destroy_db_ref(dbRef); + dbRef.release(); return true; } finally { pinnedDbRefsLock.unlock(); @@ -503,14 +503,12 @@ private static class PinnedDbRefsShutdownHook implements Runnable { public void run() { pinnedDbRefsLock.lock(); try { - List dbRefsList = new ArrayList<>(pinnedDbRefs.values()); + List dbRefsList = new ArrayList<>(pinnedDbRefs.values()); Collections.reverse(dbRefsList); - for (ByteBuffer dbRef : dbRefsList) { - DuckDBNative.duckdb_jdbc_destroy_db_ref(dbRef); + for (DuckDBInstances.InstanceRef dbRef : dbRefsList) { + dbRef.release(); } pinnedDbRefsShutdownHookRun = true; - } catch (SQLException e) { - e.printStackTrace(); } finally { pinnedDbRefsLock.unlock(); } diff --git a/src/main/java/org/duckdb/DuckDBInstances.java b/src/main/java/org/duckdb/DuckDBInstances.java new file mode 100644 index 000000000..962422cc4 --- /dev/null +++ b/src/main/java/org/duckdb/DuckDBInstances.java @@ -0,0 +1,347 @@ +package org.duckdb; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.duckdb.DuckDBBindings.*; + +import java.nio.ByteBuffer; +import java.nio.file.Paths; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicLong; + +/** + * Opens the database instances and the connections to them, on top of the C API v2 entry points of + * {@link DuckDBBindings}. + */ +final class DuckDBInstances { + private DuckDBInstances() { + } + + static final String JDBC_STREAM_RESULTS_OPTION = "jdbc_stream_results"; + + // The options that need a running instance, they cannot be given at startup + private static final String[] RUNTIME_OPTIONS = {"allowed_directories", "allowed_paths", "disabled_filesystems", + "enable_logging", "logging_level", "logging_mode", + "logging_storage", "enabled_log_types", "disabled_log_types"}; + + private static final String MEMORY_PREFIX = ":memory:"; + + // The addresses of the instances that are not shared are even, of the shared ones are odd + private static final AtomicLong NEXT_ADDRESS = new AtomicLong(1); + + private static ByteBuffer defaultEnvironment = null; + + /** + * A database instance, that is shared by the connections to it (and by the pinned references to it). The + * instance is destroyed with the last reference. + */ + static final class InstanceRef { + private int refs = 1; + private final ByteBuffer environment; + private ByteBuffer instance; + final long address; + + private InstanceRef(ByteBuffer environment, ByteBuffer instance, long address) { + this.environment = environment; + this.instance = instance; + this.address = address; + } + + synchronized InstanceRef retain() { + if (instance == null) { + throw new IllegalStateException("The instance is destroyed"); + } + refs++; + return this; + } + + ByteBuffer instance() { + return instance; + } + + void release() { + ByteBuffer toDestroy = null; + synchronized (this) { + if (instance == null) { + return; + } + if (--refs == 0) { + toDestroy = instance; + instance = null; + } + } + if (toDestroy != null) { + try { + duckdb_v2_instance_destroy(toDestroy); + if (environment != null) { + duckdb_v2_environment_destroy(environment); + } + } catch (SQLException e) { + // nothing else can be done + } + } + } + } + + /** A connection with the instance that it works on. */ + static final class Connected { + final InstanceRef instanceRef; + final ByteBuffer conn; + + Connected(InstanceRef instanceRef, ByteBuffer conn) { + this.instanceRef = instanceRef; + this.conn = conn; + } + } + + private static synchronized ByteBuffer defaultEnvironment() throws SQLException { + if (defaultEnvironment == null) { + defaultEnvironment = duckdb_v2_environment_create(); + } + return defaultEnvironment; + } + + private static boolean isRuntimeOption(String name) { + String lower = name.toLowerCase(Locale.ROOT); + for (String option : RUNTIME_OPTIONS) { + if (option.equals(lower)) { + return true; + } + } + return false; + } + + private static String quoteListEntry(String entry) { + return "'" + entry.replace("'", "''") + "'"; + } + + // The text of a Java configuration value in the form that is accepted by SET, null for nulls + private static String valueToText(Object value) { + if (value == null) { + return null; + } else if (value instanceof Float || value instanceof Double) { + return Double.toString(((Number) value).doubleValue()); + } else if (value instanceof Iterable) { + StringBuilder res = new StringBuilder("["); + boolean first = true; + // all list entries are coalesced to string + for (Object entry : (Iterable) value) { + if (!first) { + res.append(", "); + } + first = false; + res.append(quoteListEntry(String.valueOf(entry))); + } + return res.append("]").toString(); + } + return value.toString(); + } + + // The message of the error without the name of its type, as in "Invalid Input Error: message" + static String rawMessage(String message) { + if (message == null) { + return ""; + } + int pos = message.indexOf(" Error: "); + if (pos < 0 || pos > 40) { + return message; + } + return message.substring(pos + " Error: ".length()); + } + + private static byte[][] utf8(List strings) { + byte[][] res = new byte[strings.size()][]; + for (int i = 0; i < res.length; i++) { + res[i] = strings.get(i).getBytes(UTF_8); + } + return res; + } + + private static void registerStreamResultsOption(ByteBuffer instance) throws SQLException { + ByteBuffer conn = duckdb_v2_connection_create(instance); + try { + ByteBuffer factory = duckdb_v2_connection_get_factory(conn); + ByteBuffer option = duckdb_v2_custom_option_create(factory); + try { + ByteBuffer type = duckdb_create_logical_type(CAPIType.DUCKDB_TYPE_BOOLEAN.typeId); + ByteBuffer defaultValue = duckdb_v2_value_create_bool(factory, false); + try { + duckdb_v2_custom_option_set_name(option, JDBC_STREAM_RESULTS_OPTION.getBytes(UTF_8)); + duckdb_v2_custom_option_set_type(option, type); + duckdb_v2_custom_option_set_default_value(option, defaultValue); + duckdb_v2_custom_option_set_description( + option, + "Whether to stream results. Only one ResultSet on a connection can be open at once when true" + .getBytes(UTF_8)); + duckdb_v2_custom_option_set_default_scope(option, SCOPE_SESSION); + duckdb_v2_custom_option_set_supports_scope(option, SCOPE_GLOBAL, true); + duckdb_v2_custom_option_set_supports_scope(option, SCOPE_SESSION, true); + duckdb_v2_connection_register_custom_option(conn, option); + duckdb_v2_arrow_register_scan_function(conn); + } finally { + duckdb_v2_value_destroy(defaultValue); + duckdb_destroy_logical_type(type); + } + } finally { + duckdb_v2_custom_option_destroy(option); + } + } finally { + duckdb_v2_connection_destroy(conn); + } + } + + // The settings that cannot be given at startup are written when the instance is created + private static void initInstance(ByteBuffer instance, List runtimeOptions) throws SQLException { + registerStreamResultsOption(instance); + ByteBuffer config = duckdb_v2_instance_get_config(instance); + for (String[] option : runtimeOptions) { + try { + duckdb_v2_config_set_option_text(config, option[0].getBytes(UTF_8), option[1].getBytes(UTF_8), + SCOPE_GLOBAL); + } catch (SQLException e) { + throw new SQLException("Failed to set configuration option \"" + option[0] + + "\", error: " + rawMessage(e.getMessage())); + } + } + } + + /** Opens the database and connects to it. */ + static Connected startup(String database, boolean readOnly, Properties props, boolean cacheInstance) + throws SQLException { + List names = new ArrayList<>(); + List values = new ArrayList<>(); + List runtimeOptions = new ArrayList<>(); + names.add("duckdb_api"); + values.add("java"); + if (readOnly) { + names.add("access_mode"); + values.add("READ_ONLY"); + } + for (Map.Entry entry : props.entrySet()) { + String key = String.valueOf(entry.getKey()); + String value = valueToText(entry.getValue()); + if (value == null) { + continue; + } + if (JDBC_STREAM_RESULTS_OPTION.equals(key) || isRuntimeOption(key)) { + runtimeOptions.add(new String[] {key, value}); + } else { + names.add(key); + values.add(value); + } + } + + boolean shouldCache = cacheInstance && !database.equals(MEMORY_PREFIX) && !database.isEmpty(); + InstanceRef ref; + if (shouldCache) { + ByteBuffer instance; + try { + instance = duckdb_v2_instance_open_shared(defaultEnvironment(), database.getBytes(UTF_8), utf8(names), + utf8(values), inst -> initInstance(inst, runtimeOptions)); + } catch (SQLException e) { + throw new SQLException("Connection Error: " + rawMessage(e.getMessage()), e.getSQLState(), + e.getErrorCode(), e); + } + ref = new InstanceRef(null, instance, hashOfPath(database) | 1L); + } else { + ByteBuffer environment = duckdb_v2_environment_create(); + ByteBuffer instance = null; + try { + instance = duckdb_v2_instance_create_with_options(environment, utf8(names), utf8(values)); + if (database.length() > MEMORY_PREFIX.length() && database.startsWith(MEMORY_PREFIX)) { + // a named in-memory database + duckdb_v2_instance_attach(instance, database.substring(MEMORY_PREFIX.length()).getBytes(UTF_8), + MEMORY_PREFIX.getBytes(UTF_8), true); + } else { + duckdb_v2_instance_attach(instance, null, + (database.isEmpty() ? MEMORY_PREFIX : database).getBytes(UTF_8), true); + } + initInstance(instance, runtimeOptions); + } catch (SQLException | RuntimeException e) { + if (instance != null) { + duckdb_v2_instance_destroy(instance); + } + duckdb_v2_environment_destroy(environment); + throw e; + } + ref = new InstanceRef(environment, instance, NEXT_ADDRESS.incrementAndGet() << 1); + } + try { + return new Connected(ref, duckdb_v2_connection_create(ref.instance())); + } catch (SQLException | RuntimeException e) { + ref.release(); + throw e; + } + } + + private static long hashOfPath(String database) { + String key; + try { + key = Paths.get(database).toAbsolutePath().normalize().toString(); + } catch (RuntimeException e) { + key = database; + } + return key.hashCode() & 0xffffffffL; + } + + /** Connects to the instance of the connection, the session settings of the connection are copied. */ + static Connected connect(DuckDBConnection source) throws SQLException { + InstanceRef ref = source.instanceRef.retain(); + ByteBuffer conn = null; + try { + conn = duckdb_v2_connection_create(ref.instance()); + copySessionSettings(source.connRef, conn); + return new Connected(ref, conn); + } catch (SQLException | RuntimeException e) { + if (conn != null) { + duckdb_v2_connection_destroy(conn); + } + ref.release(); + throw e; + } + } + + /** Copies the session settings of the connection to the other connection. */ + static void copySessionSettings(ByteBuffer from, ByteBuffer to) throws SQLException { + ByteBuffer fromConfig = duckdb_v2_connection_get_config(from); + ByteBuffer toConfig = duckdb_v2_connection_get_config(to); + long count = duckdb_v2_config_get_option_count(fromConfig); + int[] scope = new int[1]; + for (long i = 0; i < count; i++) { + ByteBuffer option = duckdb_v2_config_get_option_by_index(fromConfig, i); + try { + if (!duckdb_v2_option_supports_scope(option, SCOPE_SESSION)) { + continue; + } + byte[] name = duckdb_v2_option_get_name(option); + ByteBuffer value = duckdb_v2_config_get_option_value_scoped(fromConfig, name, scope); + try { + if (scope[0] == SCOPE_SESSION) { + duckdb_v2_config_set_option_value(toConfig, name, value, SCOPE_SESSION); + } + } finally { + duckdb_v2_value_destroy(value); + } + } catch (SQLException e) { + // the setting cannot be copied + } finally { + duckdb_v2_option_destroy(option); + } + } + } + + /** Closes the connection and releases its reference to the instance. */ + static void disconnect(ByteBuffer conn, InstanceRef instanceRef) { + try { + duckdb_v2_connection_destroy(conn); + } catch (SQLException e) { + // nothing else can be done + } finally { + instanceRef.release(); + } + } +} diff --git a/src/main/java/org/duckdb/DuckDBNative.java b/src/main/java/org/duckdb/DuckDBNative.java index 5ba9b33a0..d5be48c97 100644 --- a/src/main/java/org/duckdb/DuckDBNative.java +++ b/src/main/java/org/duckdb/DuckDBNative.java @@ -131,34 +131,6 @@ private static void loadFromCurrentJarDir(String libName) throws Exception { * the C header. CMake does this as well */ - // results ConnectionHolder reference object - static native ByteBuffer duckdb_jdbc_startup(byte[] path, boolean read_only, Properties props, - boolean cache_instance) throws SQLException; - - // returns conn_ref connection reference object - static native ByteBuffer duckdb_jdbc_connect(ByteBuffer conn_ref) throws SQLException; - - static native ByteBuffer duckdb_jdbc_create_db_ref(ByteBuffer conn_ref) throws SQLException; - - static native void duckdb_jdbc_destroy_db_ref(ByteBuffer db_ref) throws SQLException; - - /** Returns the native address of the underlying DuckDB instance as a stable identity key. */ - static native long duckdb_jdbc_db_address(ByteBuffer conn_ref) throws SQLException; - - static native void duckdb_jdbc_set_auto_commit(ByteBuffer conn_ref, boolean auto_commit) throws SQLException; - - static native boolean duckdb_jdbc_get_auto_commit(ByteBuffer conn_ref) throws SQLException; - - static native void duckdb_jdbc_disconnect(ByteBuffer conn_ref); - - static native void duckdb_jdbc_set_schema(ByteBuffer conn_ref, String schema); - - static native void duckdb_jdbc_set_catalog(ByteBuffer conn_ref, String catalog); - - static native String duckdb_jdbc_get_schema(ByteBuffer conn_ref); - - static native String duckdb_jdbc_get_catalog(ByteBuffer conn_ref); - // The statements, queries and results are implemented in Java on top of the C API v2 entry points of // DuckDBBindings, see DuckDBCore @@ -223,24 +195,30 @@ static String[] duckdb_jdbc_cast_result_to_strings(DuckDBCore.ResultRef res_ref, return DuckDBCore.castResultToStrings(res_ref, col_idx); } - static native int duckdb_jdbc_fetch_size(); + static long duckdb_jdbc_arrow_stream(DuckDBCore.ResultRef res_ref, DuckDBConnection conn, long batch_size) + throws SQLException { + return DuckDBCore.exportArrow(res_ref, conn, batch_size); + } - // TODO: the Arrow export is not ported to the C API v2 yet - static long duckdb_jdbc_arrow_stream(DuckDBCore.ResultRef res_ref, ByteBuffer conn_ref, long batch_size) + static void duckdb_jdbc_arrow_register(DuckDBConnection conn, long arrow_array_stream_pointer, String name) throws SQLException { - throw new java.sql.SQLFeatureNotSupportedException("Arrow export is not supported yet"); + DuckDBCore.registerArrowStream(conn, arrow_array_stream_pointer, name); } - static native void duckdb_jdbc_arrow_register(ByteBuffer conn_ref, long arrow_array_stream_pointer, byte[] name); + static void duckdb_jdbc_arrow_close_streams(ByteBuffer conn_ref) { + DuckDBBindings.duckdb_v2_arrow_close_streams(conn_ref); + } - static native void duckdb_jdbc_arrow_close_streams(ByteBuffer conn_ref); + static int duckdb_jdbc_fetch_size() { + return (int) DuckDBBindings.duckdb_vector_size(); + } static void duckdb_jdbc_interrupt(ByteBuffer conn_ref) throws SQLException { - DuckDBBindings.duckdb_v2_connection_interrupt(DuckDBBindings.duckdb_v2_connection_from_ref(conn_ref)); + DuckDBBindings.duckdb_v2_connection_interrupt(conn_ref); } static QueryProgress duckdb_jdbc_query_progress(ByteBuffer conn_ref) throws SQLException { - return DuckDBBindings.duckdb_v2_connection_progress_get(DuckDBBindings.duckdb_v2_connection_from_ref(conn_ref)); + return DuckDBBindings.duckdb_v2_connection_progress_get(conn_ref); } protected static native String duckdb_jdbc_get_profiling_information(ByteBuffer conn_ref, diff --git a/src/main/java/org/duckdb/DuckDBResultSet.java b/src/main/java/org/duckdb/DuckDBResultSet.java index 0568b4ea3..7f31efe42 100644 --- a/src/main/java/org/duckdb/DuckDBResultSet.java +++ b/src/main/java/org/duckdb/DuckDBResultSet.java @@ -130,7 +130,7 @@ private void check(int columnIndex) throws SQLException { * When the connection is closed before the reader, the reader fails to load next batches. * * @param arrow_buffer_allocator an instance of {@link org.apache.arrow.memory.BufferAllocator} - * @param arrow_batch_size batch size of arrow vectors to return + * @param arrow_batch_size maximum number of rows of the arrow vectors to return, the batches can be smaller * @return an instance of {@link org.apache.arrow.vector.ipc.ArrowReader} */ public synchronized Object arrowExportStream(Object arrow_buffer_allocator, long arrow_batch_size) @@ -149,7 +149,7 @@ public synchronized Object arrowExportStream(Object arrow_buffer_allocator, long resultRefLock.lock(); try { checkOpen(); - stream_pointer = DuckDBNative.duckdb_jdbc_arrow_stream(resultRef, conn.connRef, arrow_batch_size); + stream_pointer = DuckDBNative.duckdb_jdbc_arrow_stream(resultRef, conn, arrow_batch_size); } finally { resultRefLock.unlock(); } diff --git a/src/main/java/org/duckdb/DuckDBSingleValueAppender.java b/src/main/java/org/duckdb/DuckDBSingleValueAppender.java index c1f4ca210..5715b7e1f 100644 --- a/src/main/java/org/duckdb/DuckDBSingleValueAppender.java +++ b/src/main/java/org/duckdb/DuckDBSingleValueAppender.java @@ -132,7 +132,7 @@ private void appendValue(ByteBuffer value) throws SQLException { } private ByteBuffer factory() throws SQLException { - return duckdb_v2_connection_get_factory(duckdb_v2_connection_from_ref(conn.connRef)); + return duckdb_v2_connection_get_factory(conn.connRef); } private void appendObject(Object value) throws SQLException { diff --git a/src/main/java/org/duckdb/DuckDBV2Appender.java b/src/main/java/org/duckdb/DuckDBV2Appender.java index f57beef6f..d331556a1 100644 --- a/src/main/java/org/duckdb/DuckDBV2Appender.java +++ b/src/main/java/org/duckdb/DuckDBV2Appender.java @@ -58,7 +58,7 @@ static DuckDBV2Appender create(DuckDBConnection conn, String catalog, String sch } qualified.append(quoteIdentifier(table)); - ByteBuffer connHandle = duckdb_v2_connection_from_ref(conn.connRef); + ByteBuffer connHandle = conn.connRef; ByteBuffer factory = duckdb_v2_connection_get_factory(connHandle); // the columns of the table: binding reports them without reading a row @@ -179,7 +179,7 @@ int flush() { } conn.queryGate.acquireUninterruptibly(); try { - ByteBuffer connHandle = duckdb_v2_connection_from_ref(conn.connRef); + ByteBuffer connHandle = conn.connRef; ByteBuffer result = duckdb_v2_statement_execute(connHandle, statement, null); try { duckdb_v2_result_drain(result); @@ -234,8 +234,7 @@ int appendDefaultToChunk(ByteBuffer chunk, long col, long row) { value = DuckDBCore.queryValue(conn, "SELECT " + defaultSql); } else { // a column without a default value gets the NULL default - value = - DuckDBCore.nullValue(duckdb_v2_connection_get_factory(duckdb_v2_connection_from_ref(conn.connRef))); + value = DuckDBCore.nullValue(duckdb_v2_connection_get_factory(conn.connRef)); } try { duckdb_v2_vector_set_value(vec, row, value); diff --git a/src/test/external/TestArrow.java b/src/test/external/TestArrow.java index b405a15de..ada83e9d7 100644 --- a/src/test/external/TestArrow.java +++ b/src/test/external/TestArrow.java @@ -657,7 +657,13 @@ public static void test_arrow_export_batch_size() throws Exception { sum += vec.get(i); } } - assertListsEqual(batchSizes, asList(4096, 4096, 1808)); + // batches are filled by the threads of the query, so they can be smaller than the batch size + int rows = 0; + for (int size : batchSizes) { + assertTrue(size > 0 && size <= 4096, "batch size: " + size); + rows += size; + } + assertEquals(rows, 10000); assertEquals(sum, 9999L * 10000L / 2); } } @@ -687,7 +693,7 @@ public static void test_arrow_export_streaming_result() throws Exception { } assertEquals(count, 100000L); assertEquals(sum, 99999L * 100000L / 2); - assertEquals(batches, 10); + assertTrue(batches >= 10); } } From 1db908a8b73c92f73cbaabcf8a1e4296b7308034 Mon Sep 17 00:00:00 2001 From: Robinho-MR Date: Fri, 27 Nov 2026 15:28:47 +0000 Subject: [PATCH 07/21] Read the profiling information through the C API v2 and remove the generated native entry points --- CMakeLists.txt | 1 - CMakeLists.txt.in | 1 - duckdb_java.def | 2 +- duckdb_java.exp | 2 +- duckdb_java.map | 2 +- generator.py | 28 ---------------- header2whatever.yaml | 8 ----- src/jni/bindings_scalar_function.cpp | 1 - src/jni/bindings_v2.cpp | 21 ++++++++++++ src/jni/duckdb_java.cpp | 34 -------------------- src/jni/functions.cpp | 21 ------------ src/jni/functions.cpp.template | 24 -------------- src/jni/functions.hpp | 18 ----------- src/jni/functions.hpp.template | 16 --------- src/main/java/org/duckdb/DuckDBBindings.java | 6 ++++ src/main/java/org/duckdb/DuckDBNative.java | 10 ++++-- 16 files changed, 37 insertions(+), 158 deletions(-) delete mode 100644 generator.py delete mode 100644 header2whatever.yaml delete mode 100644 src/jni/functions.cpp delete mode 100644 src/jni/functions.cpp.template delete mode 100644 src/jni/functions.hpp delete mode 100644 src/jni/functions.hpp.template diff --git a/CMakeLists.txt b/CMakeLists.txt index b49e3eda9..e4c172674 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -674,7 +674,6 @@ add_library(duckdb_java SHARED src/jni/bindings_value.cpp src/jni/capi_v2.cpp src/jni/duckdb_java.cpp - src/jni/functions.cpp src/jni/holders.cpp src/jni/refs.cpp src/jni/util.cpp diff --git a/CMakeLists.txt.in b/CMakeLists.txt.in index 0c812cac5..fb0c3d761 100644 --- a/CMakeLists.txt.in +++ b/CMakeLists.txt.in @@ -153,7 +153,6 @@ add_library(duckdb_java SHARED src/jni/bindings_value.cpp src/jni/capi_v2.cpp src/jni/duckdb_java.cpp - src/jni/functions.cpp src/jni/holders.cpp src/jni/refs.cpp src/jni/util.cpp diff --git a/duckdb_java.def b/duckdb_java.def index 4668b96ce..04d213bc3 100644 --- a/duckdb_java.def +++ b/duckdb_java.def @@ -4,7 +4,6 @@ EXPORTS JNI_OnLoad JNI_OnUnload -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1profiling_1information Java_org_duckdb_DuckDBBindings_duckdb_1vector_1size Java_org_duckdb_DuckDBBindings_duckdb_1create_1scalar_1function @@ -234,6 +233,7 @@ Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1export_1stream Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1scan_1function Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1stream Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1release_1stream +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1profiling_1information ; ADBC entry point duckdb_adbc_init diff --git a/duckdb_java.exp b/duckdb_java.exp index b2b08a5f2..00dc51492 100644 --- a/duckdb_java.exp +++ b/duckdb_java.exp @@ -1,7 +1,6 @@ _JNI_OnLoad _JNI_OnUnload -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1profiling_1information _Java_org_duckdb_DuckDBBindings_duckdb_1vector_1size _Java_org_duckdb_DuckDBBindings_duckdb_1create_1scalar_1function @@ -231,6 +230,7 @@ _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1export_1stream _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1scan_1function _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1stream _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1release_1stream +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1profiling_1information # ADBC entry point _duckdb_adbc_init diff --git a/duckdb_java.map b/duckdb_java.map index 9191c9174..8c2ba4af8 100644 --- a/duckdb_java.map +++ b/duckdb_java.map @@ -3,7 +3,6 @@ DUCKDB_JAVA { JNI_OnLoad; JNI_OnUnload; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1profiling_1information; Java_org_duckdb_DuckDBBindings_duckdb_1vector_1size; Java_org_duckdb_DuckDBBindings_duckdb_1create_1scalar_1function; @@ -233,6 +232,7 @@ DUCKDB_JAVA { Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1scan_1function; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1stream; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1release_1stream; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1profiling_1information; /* ADBC entry point */ duckdb_adbc_init; diff --git a/generator.py b/generator.py deleted file mode 100644 index 7860b1405..000000000 --- a/generator.py +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env python3 - -import header2whatever -from CppHeaderParser.CppHeaderParser import CppMethod - - -def function_hook(fn: CppMethod, config): - name = fn['name'] - params = fn['parameters'] - names = ['env'] + [f'param{i}' for i, param in enumerate(params[1:])] - return_type = fn['rtnType'].split(' ', 1)[1] - return_type = return_type.rsplit(' ', 1)[0] - - fn.update( - { - 'name': name, - 'names': ', '.join(names), - 'params': ', '.join(f'{param["type"]} {name}' for param, name in zip(params, names)), - 'return_type': return_type, - 'short_name': ( - '_duckdb_jdbc_' + name.replace('Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1', '').replace('1', '') - ), - } - ) - - -if __name__ == '__main__': - header2whatever.batch_convert('header2whatever.yaml', 'src/jni', '.') diff --git a/header2whatever.yaml b/header2whatever.yaml deleted file mode 100644 index 572e4fd32..000000000 --- a/header2whatever.yaml +++ /dev/null @@ -1,8 +0,0 @@ -- headers: - - "build/release/CMakeFiles/duckdb_jdbc.dir/native_headers/org_duckdb_DuckDBNative.h" - hooks: generator.py - templates: - - src: "src/jni/functions.hpp.template" - dst: "functions.hpp" - - src: "src/jni/functions.cpp.template" - dst: "functions.cpp" diff --git a/src/jni/bindings_scalar_function.cpp b/src/jni/bindings_scalar_function.cpp index 2708fada5..10545fd58 100644 --- a/src/jni/bindings_scalar_function.cpp +++ b/src/jni/bindings_scalar_function.cpp @@ -1,5 +1,4 @@ #include "bindings.hpp" -#include "functions.hpp" #include "holders.hpp" #include "refs.hpp" #include "util.hpp" diff --git a/src/jni/bindings_v2.cpp b/src/jni/bindings_v2.cpp index 386076feb..81d7cb10e 100644 --- a/src/jni/bindings_v2.cpp +++ b/src/jni/bindings_v2.cpp @@ -1205,3 +1205,24 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1re CHECK_BUF(option, option_buf, duckdb_v2_custom_option_handle, "custom option"); CALL_V2(duckdb_v2_connection_register_custom_option(conn, option, ERR_OUT), ); } + +/* --- profiling --- */ + +static void text_sink(const char *text, idx_t text_length, void *user_data, duckdb_v2_error_info_handle *) { + static_cast(user_data)->assign(text, text_length); +} + +// The profiling information of the last query of the connection in the format ("" is the default one) +JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1profiling_1information( + JNIEnv *env, jclass, jobject conn_buf, jbyteArray format_j) { + CHECK_BUF_RET(conn, conn_buf, duckdb_v2_connection_handle, "connection", nullptr); + auto format = jbyteArray_to_string(env, format_j); + if (env->ExceptionCheck()) { + return nullptr; + } + std::string text; + CALL_V2( + duckdb_v2_connection_get_profiling_information(conn, format.data(), format.size(), text_sink, &text, ERR_OUT), + nullptr); + return make_jbyteArray(env, text.data(), text.size()); +} diff --git a/src/jni/duckdb_java.cpp b/src/jni/duckdb_java.cpp index 4de02e7c5..9e29d1f96 100644 --- a/src/jni/duckdb_java.cpp +++ b/src/jni/duckdb_java.cpp @@ -1,19 +1,8 @@ -#include "duckdb.hpp" -#include "duckdb/main/capi_v2/capi_v2_internal.hpp" -#include "functions.hpp" #include "refs.hpp" #include "util.hpp" -using namespace duckdb; -using namespace std; - static jint JNI_VERSION = JNI_VERSION_1_6; -void ThrowJNI(JNIEnv *env, const char *message) { - D_ASSERT(J_SQLException); - env->ThrowNew(J_SQLException, message); -} - JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { JNIEnv *env; if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION) != JNI_OK) { @@ -42,26 +31,3 @@ JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved) { } delete_global_refs(env); } - -static ProfilerPrintFormat GetProfilerPrintFormat(JNIEnv *env, jobject format) { - jobject jname = env->CallObjectMethod(format, J_ProfilerPrintFormat_getName); - check_java_exception_and_rethrow(env); - const std::string name = jstring_to_string(env, static_cast(jname)); - return ProfilerPrintFormat(name); -} - -// The C API v2 has no call for the profiling information of a connection, so this is the only entry point that -// uses the engine: the C API v2 connection handle is the engine connection -jstring _duckdb_jdbc_get_profiling_information(JNIEnv *env, jclass, jobject conn_ref_buf, jobject j_format) { - if (conn_ref_buf == nullptr) { - throw InvalidInputException("Invalid connection"); - } - auto handle = reinterpret_cast(env->GetDirectBufferAddress(conn_ref_buf)); - if (!handle) { - throw InvalidInputException("Invalid connection"); - } - auto connection = duckdb::capiv2::Convert(handle); - auto format = GetProfilerPrintFormat(env, j_format); - auto profiling_info = connection->GetProfilingInformation(format); - return env->NewStringUTF(profiling_info.c_str()); -} diff --git a/src/jni/functions.cpp b/src/jni/functions.cpp deleted file mode 100644 index 4a917d27c..000000000 --- a/src/jni/functions.cpp +++ /dev/null @@ -1,21 +0,0 @@ -// This file was generated by generator.py - -#include "functions.hpp" - -#include "org_duckdb_DuckDBNative.h" - -#include - -JNIEXPORT jstring JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1profiling_1information(JNIEnv *env, - jclass param0, - jobject param1, - jobject param2) { - try { - return _duckdb_jdbc_get_profiling_information(env, param0, param1, param2); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - return nullptr; - } -} diff --git a/src/jni/functions.cpp.template b/src/jni/functions.cpp.template deleted file mode 100644 index 4fa4537e1..000000000 --- a/src/jni/functions.cpp.template +++ /dev/null @@ -1,24 +0,0 @@ -// This file was generated by generator.py - -#include "org_duckdb_DuckDBNative.h" -#include "functions.hpp" -#include -{% for function in header.functions %} - -JNIEXPORT {{ function.return_type or 'void' }} JNICALL {{function.name}}({{function.params}}) { - try { - return {{function.short_name}}({{function.names}}); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - {% if function.return_type == 'jboolean' %} - return false; - {% elif function.return_type in['jint', 'jlong'] %} - return -1; - {% elif function.return_type in['jobject', 'jstring', 'jobjectArray'] %} - return nullptr; - {% endif %} - } -} -{% endfor %} diff --git a/src/jni/functions.hpp b/src/jni/functions.hpp deleted file mode 100644 index accb45432..000000000 --- a/src/jni/functions.hpp +++ /dev/null @@ -1,18 +0,0 @@ -// This file was generated by generator.py - -#pragma once - -#include "duckdb/common/assert.hpp" -#include "duckdb/common/error_data.hpp" -#include "org_duckdb_DuckDBNative.h" - -#include - -void ThrowJNI(JNIEnv *env, const char *message); - -jstring _duckdb_jdbc_get_profiling_information(JNIEnv *env, jclass param0, jobject param1, jobject param2); - -JNIEXPORT jstring JNICALL Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1get_1profiling_1information(JNIEnv *env, - jclass param0, - jobject param1, - jobject param2); diff --git a/src/jni/functions.hpp.template b/src/jni/functions.hpp.template deleted file mode 100644 index 9f90d37e1..000000000 --- a/src/jni/functions.hpp.template +++ /dev/null @@ -1,16 +0,0 @@ -// This file was generated by generator.py - -#pragma once - -#include "duckdb/common/assert.hpp" -#include "duckdb/common/error_data.hpp" -#include "org_duckdb_DuckDBNative.h" -#include - -void ThrowJNI(JNIEnv* env, const char* message); -{% for function in header.functions %} - -{{function.return_type or 'void'}} {{function.short_name}}({{function.params}}); - -JNIEXPORT {{ function.return_type or 'void' }} JNICALL {{function.name}}({{function.params}}); -{% endfor %} diff --git a/src/main/java/org/duckdb/DuckDBBindings.java b/src/main/java/org/duckdb/DuckDBBindings.java index 219734ab5..063654ca3 100644 --- a/src/main/java/org/duckdb/DuckDBBindings.java +++ b/src/main/java/org/duckdb/DuckDBBindings.java @@ -578,6 +578,12 @@ static native long duckdb_v2_arrow_export_stream(ByteBuffer conn, ByteBuffer hel // closes the exported and the registered streams of the connection that are not released by their consumers yet static native void duckdb_v2_arrow_close_streams(ByteBuffer conn); + // profiling + + // the profiling information of the last query of the connection, the format is "" for the default one + static native byte[] duckdb_v2_connection_get_profiling_information(ByteBuffer conn, byte[] format) + throws SQLException; + // DUCKDB_V2_RESULT_STEP_STATUS static final int RESULT_STEP_WAITING = 0; static final int RESULT_STEP_CHUNK = 1; diff --git a/src/main/java/org/duckdb/DuckDBNative.java b/src/main/java/org/duckdb/DuckDBNative.java index d5be48c97..aeddffb80 100644 --- a/src/main/java/org/duckdb/DuckDBNative.java +++ b/src/main/java/org/duckdb/DuckDBNative.java @@ -1,5 +1,6 @@ package org.duckdb; +import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; import java.io.FileNotFoundException; @@ -221,7 +222,10 @@ static QueryProgress duckdb_jdbc_query_progress(ByteBuffer conn_ref) throws SQLE return DuckDBBindings.duckdb_v2_connection_progress_get(conn_ref); } - protected static native String duckdb_jdbc_get_profiling_information(ByteBuffer conn_ref, - ProfilerPrintFormat format) - throws SQLException; + protected static String duckdb_jdbc_get_profiling_information(ByteBuffer conn_ref, ProfilerPrintFormat format) + throws SQLException { + String name = "default".equals(format.getName()) ? "" : format.getName(); + return new String(DuckDBBindings.duckdb_v2_connection_get_profiling_information(conn_ref, name.getBytes(UTF_8)), + UTF_8); + } } From 755edefa3af0230d4e792e5762ab02168fcab7d5 Mon Sep 17 00:00:00 2001 From: Robinho-MR Date: Fri, 27 Nov 2026 16:10:53 +0000 Subject: [PATCH 08/21] Read the strings from the vector data and reduce the native calls per query --- duckdb_java.def | 5 + duckdb_java.exp | 5 + duckdb_java.map | 5 + src/jni/bindings_v2.cpp | 132 +++++++ src/main/java/org/duckdb/DuckDBBindings.java | 22 ++ .../java/org/duckdb/DuckDBConnection.java | 23 ++ src/main/java/org/duckdb/DuckDBCore.java | 372 ++++++++++++++---- .../org/duckdb/DuckDBPreparedStatement.java | 20 +- 8 files changed, 506 insertions(+), 78 deletions(-) diff --git a/duckdb_java.def b/duckdb_java.def index 04d213bc3..3da7e6c9e 100644 --- a/duckdb_java.def +++ b/duckdb_java.def @@ -234,6 +234,11 @@ Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1scan_1function Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1stream Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1release_1stream Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1profiling_1information +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1cast +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1long_1strings +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1bool_1option +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1names +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1type_1ids ; ADBC entry point duckdb_adbc_init diff --git a/duckdb_java.exp b/duckdb_java.exp index 00dc51492..da678846c 100644 --- a/duckdb_java.exp +++ b/duckdb_java.exp @@ -231,6 +231,11 @@ _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1scan_1function _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1stream _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1release_1stream _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1profiling_1information +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1cast +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1long_1strings +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1bool_1option +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1names +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1type_1ids # ADBC entry point _duckdb_adbc_init diff --git a/duckdb_java.map b/duckdb_java.map index 8c2ba4af8..598b1e5ee 100644 --- a/duckdb_java.map +++ b/duckdb_java.map @@ -233,6 +233,11 @@ DUCKDB_JAVA { Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1stream; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1release_1stream; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1profiling_1information; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1cast; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1long_1strings; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1bool_1option; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1names; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1type_1ids; /* ADBC entry point */ duckdb_adbc_init; diff --git a/src/jni/bindings_v2.cpp b/src/jni/bindings_v2.cpp index 81d7cb10e..81f201760 100644 --- a/src/jni/bindings_v2.cpp +++ b/src/jni/bindings_v2.cpp @@ -5,6 +5,7 @@ #include "refs.hpp" #include "util.hpp" +#include #include template @@ -1226,3 +1227,134 @@ JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connecti nullptr); return make_jbyteArray(env, text.data(), text.size()); } + +/* --- reading strings --- */ + +// Copies the strings (or BLOBs) of the rows of the vector data, that do not fit into the 16 bytes of the entry, into +// one array. The string of the i-th row is at [offsets_out[i], offsets_out[i + 1]) of the result. The short strings are +// read from the data buffer on Java side, without any call. +JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1long_1strings( + JNIEnv *env, jclass, jobject data_buf, jintArray rows_j, jint count, jintArray offsets_out) { + if (data_buf == nullptr || rows_j == nullptr || offsets_out == nullptr || count < 0) { + env->ThrowNew(J_SQLException, "Invalid strings buffer"); + return nullptr; + } + auto data = reinterpret_cast(env->GetDirectBufferAddress(data_buf)); + if (data == nullptr) { + env->ThrowNew(J_SQLException, "Invalid vector data"); + return nullptr; + } + std::vector rows(static_cast(count)); + env->GetIntArrayRegion(rows_j, 0, count, rows.data()); + if (env->ExceptionCheck()) { + return nullptr; + } + std::vector offsets(static_cast(count) + 1); + uint64_t total = 0; + for (jint i = 0; i < count; i++) { + offsets[static_cast(i)] = static_cast(total); + total += v2_bytes_length(data[rows[static_cast(i)]]); + if (total > static_cast(INT32_MAX)) { + env->ThrowNew(J_SQLException, "The strings of the vector are too large"); + return nullptr; + } + } + offsets[static_cast(count)] = static_cast(total); + jbyteArray res = env->NewByteArray(static_cast(total)); + if (res == nullptr) { + return nullptr; + } + if (total > 0) { + auto dst = static_cast(env->GetPrimitiveArrayCritical(res, nullptr)); + if (dst == nullptr) { + return nullptr; + } + for (jint i = 0; i < count; i++) { + auto &bytes = data[rows[static_cast(i)]]; + std::memcpy(dst + offsets[static_cast(i)], v2_bytes_data(bytes), v2_bytes_length(bytes)); + } + env->ReleasePrimitiveArrayCritical(res, dst, 0); + } + env->SetIntArrayRegion(offsets_out, 0, count + 1, offsets.data()); + return res; +} + +// Casts the rows of the source vector to the type of the target vector, the target is replaced by the result +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1cast(JNIEnv *env, jclass, jobject factory_buf, + jobject source_buf, jobject target_buf) { + CHECK_BUF(factory, factory_buf, duckdb_v2_factory_handle, "factory"); + CHECK_BUF(source, source_buf, duckdb_v2_vector_handle, "vector"); + CHECK_BUF(target, target_buf, duckdb_v2_vector_handle, "vector"); + bool converted = false; + CALL_V2(duckdb_v2_vector_cast(factory, source, target, DUCKDB_V2_CAST_MODE_NORMAL, &converted, nullptr, ERR_OUT), ); +} + +/* --- bulk reads --- */ + +// The names of all the fields of the schema +JNIEXPORT jobjectArray JNICALL +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1names(JNIEnv *env, jclass, jobject schema_buf) { + CHECK_BUF_RET(schema, schema_buf, duckdb_v2_schema_handle, "schema", nullptr); + idx_t count = 0; + CALL_V2(duckdb_v2_schema_get_count(schema, &count, ERR_OUT), nullptr); + jobjectArray res = env->NewObjectArray(static_cast(count), J_ByteArray, nullptr); + if (res == nullptr) { + return nullptr; + } + for (idx_t i = 0; i < count; i++) { + const char *name = nullptr; + idx_t name_len = 0; + duckdb_v2_logical_type_handle type = nullptr; + CALL_V2(duckdb_v2_schema_get_field(schema, i, &name, &name_len, &type, ERR_OUT), nullptr); + jbyteArray name_j = make_jbyteArray(env, name, name_len); + if (name_j == nullptr) { + return nullptr; + } + env->SetObjectArrayElement(res, static_cast(i), name_j); + env->DeleteLocalRef(name_j); + } + return res; +} + +// The type IDs (of the C API v1) of all the fields of the schema +JNIEXPORT jintArray JNICALL +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1type_1ids(JNIEnv *env, jclass, jobject schema_buf) { + CHECK_BUF_RET(schema, schema_buf, duckdb_v2_schema_handle, "schema", nullptr); + idx_t count = 0; + CALL_V2(duckdb_v2_schema_get_count(schema, &count, ERR_OUT), nullptr); + std::vector ids(count); + for (idx_t i = 0; i < count; i++) { + const char *name = nullptr; + idx_t name_len = 0; + duckdb_v2_logical_type_handle type = nullptr; + CALL_V2(duckdb_v2_schema_get_field(schema, i, &name, &name_len, &type, ERR_OUT), nullptr); + ids[i] = static_cast(logical_type_to_capi(type)); + } + jintArray res = env->NewIntArray(static_cast(count)); + if (res != nullptr && count > 0) { + env->SetIntArrayRegion(res, 0, static_cast(count), ids.data()); + } + return res; +} + +// Reads a BOOLEAN option, returns 1 or 0, or -1 if the option is not set or is not a BOOLEAN +JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1bool_1option(JNIEnv *env, jclass, + jobject config_buf, + jbyteArray name_j) { + CHECK_BUF_RET(config, config_buf, duckdb_v2_config_handle, "config", -1); + auto name = jbyteArray_to_string(env, name_j); + if (env->ExceptionCheck()) { + return -1; + } + v2_value value; + DUCKDB_V2_SETTING_SCOPE scope = DUCKDB_V2_SETTING_SCOPE_DEFAULT; + if (duckdb_v2_config_get_option_value(config, name.data(), name.size(), value.out(), &scope, nullptr) != + DUCKDB_V2_ERROR_NONE) { + return -1; + } + bool res = false; + if (duckdb_v2_value_get_bool(value.get(), &res, nullptr) != DUCKDB_V2_ERROR_NONE) { + return -1; + } + return res ? 1 : 0; +} diff --git a/src/main/java/org/duckdb/DuckDBBindings.java b/src/main/java/org/duckdb/DuckDBBindings.java index 063654ca3..ef1ef1633 100644 --- a/src/main/java/org/duckdb/DuckDBBindings.java +++ b/src/main/java/org/duckdb/DuckDBBindings.java @@ -584,6 +584,28 @@ static native long duckdb_v2_arrow_export_stream(ByteBuffer conn, ByteBuffer hel static native byte[] duckdb_v2_connection_get_profiling_information(ByteBuffer conn, byte[] format) throws SQLException; + // reading strings + + // Copies the strings (BLOBs) of the rows of the vector data that do not fit into the 16 bytes of the entry into one + // array, the string of the i-th row is at [offsets_out[i], offsets_out[i + 1]) of the result + static native byte[] duckdb_v2_vector_get_long_strings(ByteBuffer data, int[] rows, int count, int[] offsets_out) + throws SQLException; + + // casts the rows of the source vector to the type of the target vector, the target is replaced by the result + static native void duckdb_v2_vector_cast(ByteBuffer factory, ByteBuffer source, ByteBuffer target) + throws SQLException; + + // bulk reads + + // the names of all the fields of the schema + static native byte[][] duckdb_v2_schema_get_field_names(ByteBuffer schema) throws SQLException; + + // the type IDs (of the C API v1) of all the fields of the schema + static native int[] duckdb_v2_schema_get_field_type_ids(ByteBuffer schema) throws SQLException; + + // reads a BOOLEAN option: 1 or 0, or -1 if the option is not set or is not a BOOLEAN + static native int duckdb_v2_config_get_bool_option(ByteBuffer config, byte[] name) throws SQLException; + // DUCKDB_V2_RESULT_STEP_STATUS static final int RESULT_STEP_WAITING = 0; static final int RESULT_STEP_CHUNK = 1; diff --git a/src/main/java/org/duckdb/DuckDBConnection.java b/src/main/java/org/duckdb/DuckDBConnection.java index 52e5d2d75..22e810b4b 100644 --- a/src/main/java/org/duckdb/DuckDBConnection.java +++ b/src/main/java/org/duckdb/DuckDBConnection.java @@ -37,6 +37,9 @@ public final class DuckDBConnection implements java.sql.Connection { ByteBuffer connRef; DuckDBInstances.InstanceRef instanceRef; + // The config and the factory of the connection, that are borrowed from it + private ByteBuffer configRef; + private ByteBuffer factoryRef; // The ids of the Arrow streams that are registered with the connection, by the names of their views final java.util.HashMap arrowStreams = new java.util.HashMap<>(); final ReentrantLock connRefLock = new ReentrantLock(); @@ -107,6 +110,24 @@ private DuckDBConnection(DuckDBInstances.Connected connected, String url, boolea } } + ByteBuffer config() throws SQLException { + ByteBuffer res = configRef; + if (res == null) { + res = DuckDBBindings.duckdb_v2_connection_get_config(connRef); + configRef = res; + } + return res; + } + + ByteBuffer factory() throws SQLException { + ByteBuffer res = factoryRef; + if (res == null) { + res = DuckDBBindings.duckdb_v2_connection_get_factory(connRef); + factoryRef = res; + } + return res; + } + public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkOpen(); @@ -225,6 +246,8 @@ public void close() throws SQLException { DuckDBInstances.disconnect(connRef, instanceRef); connRef = null; + configRef = null; + factoryRef = null; notifyMonitor = (monitorName != null); } finally { connRefLock.unlock(); diff --git a/src/main/java/org/duckdb/DuckDBCore.java b/src/main/java/org/duckdb/DuckDBCore.java index 73ab7d052..78b9d1ef3 100644 --- a/src/main/java/org/duckdb/DuckDBCore.java +++ b/src/main/java/org/duckdb/DuckDBCore.java @@ -80,16 +80,22 @@ static final class StatementRef { final int statementType; final long parameterCount; ByteBuffer prepared; + // the parsed statement, it is bound when the metadata is asked + ByteBuffer statement; ByteBuffer outputSchema; ByteBuffer parametersSchema; - - StatementRef(DuckDBConnection conn, int statementType, ByteBuffer prepared, ByteBuffer outputSchema, - ByteBuffer parametersSchema, long parameterCount) { + // The metadata of the last result, it is the same for the next results of the statement if the types are + int[] metaTypeIds; + String[] metaNames; + int metaResultType; + DuckDBResultSetMetaData meta; + + StatementRef(DuckDBConnection conn, int statementType, ByteBuffer prepared, ByteBuffer statement, + long parameterCount) { this.conn = conn; this.statementType = statementType; this.prepared = prepared; - this.outputSchema = outputSchema; - this.parametersSchema = parametersSchema; + this.statement = statement; this.parameterCount = parameterCount; } } @@ -114,9 +120,13 @@ static final class PendingRef { * completed. */ static final class ResultRef { - final ByteBuffer connRef; + final DuckDBConnection connection; final int resultType; final String[] names; + // the type IDs (of the C API v1) of the columns + final int[] typeIds; + // the statement that is executed to get this result, if any + StatementRef statement; // the result that is streamed, null if the result is in the memory ByteBuffer streamResult; // the chunks that are read but are not consumed yet @@ -124,9 +134,13 @@ static final class ResultRef { // the chunk that is being consumed, it keeps the memory of the vectors of the fetched DuckDBVector-s ByteBuffer currentChunk; ByteBuffer schema; + // the type details of the columns, they are the same for all the chunks + String[] detailCache; - ResultRef(ByteBuffer connRef, ByteBuffer streamResult, ByteBuffer schema, int resultType, String[] names) { - this.connRef = connRef; + ResultRef(DuckDBConnection connection, ByteBuffer streamResult, ByteBuffer schema, int resultType, + String[] names, int[] typeIds) { + this.connection = connection; + this.typeIds = typeIds; this.streamResult = streamResult; this.schema = schema; this.resultType = resultType; @@ -149,15 +163,9 @@ private static long fieldCount(ByteBuffer schema) throws SQLException { return schema == null ? 0 : duckdb_v2_schema_get_count(schema); } - private static boolean streamResultsOption(ByteBuffer conn) { + private static boolean streamResultsOption(DuckDBConnection connection) { try { - ByteBuffer config = duckdb_v2_connection_get_config(conn); - ByteBuffer value = duckdb_v2_config_get_option_value(config, STREAM_RESULTS_OPTION); - try { - return duckdb_get_bool(value); - } finally { - duckdb_v2_value_destroy(value); - } + return duckdb_v2_config_get_bool_option(connection.config(), STREAM_RESULTS_OPTION) == 1; } catch (SQLException e) { return false; } @@ -241,28 +249,21 @@ private static StatementRef prepareLocked(DuckDBConnection connection, byte[] qu ByteBuffer conn = conn(connection.connRef); ByteBuffer statement = extractLastStatement(conn, query, true); ByteBuffer prepared = null; - ByteBuffer[] schemas = null; try { int statementType = duckdb_v2_sql_statement_get_type(statement); + long parameterCount = duckdb_v2_sql_statement_get_parameter_count(statement); prepared = duckdb_v2_prepared_statement_create(conn, statement, false); - schemas = duckdb_v2_statement_bind(conn, statement); - long parameterCount = fieldCount(schemas[1]); - StatementRef ref = - new StatementRef(connection, statementType, prepared, schemas[0], schemas[1], parameterCount); + StatementRef ref = new StatementRef(connection, statementType, prepared, statement, parameterCount); prepared = null; - schemas = null; + statement = null; return ref; } finally { if (prepared != null) { duckdb_v2_prepared_statement_destroy(prepared); } - if (schemas != null) { - duckdb_v2_schema_destroy(schemas[0]); - if (schemas[1] != null) { - duckdb_v2_schema_destroy(schemas[1]); - } + if (statement != null) { + duckdb_v2_sql_statement_destroy(statement); } - duckdb_v2_sql_statement_destroy(statement); } } @@ -275,6 +276,10 @@ static void release(StatementRef ref) throws SQLException { try { duckdb_v2_prepared_statement_destroy(prepared); } finally { + if (ref.statement != null) { + duckdb_v2_sql_statement_destroy(ref.statement); + ref.statement = null; + } if (ref.outputSchema != null) { duckdb_v2_schema_destroy(ref.outputSchema); ref.outputSchema = null; @@ -286,6 +291,21 @@ static void release(StatementRef ref) throws SQLException { } } + // Binds the statement to get the types of its columns and parameters, the types are not needed to execute it + private static void bind(StatementRef ref) throws SQLException { + if (ref.outputSchema != null) { + return; + } + ref.conn.queryGate.acquireUninterruptibly(); + try { + ByteBuffer[] schemas = duckdb_v2_statement_bind(conn(ref.conn.connRef), ref.statement); + ref.outputSchema = schemas[0]; + ref.parametersSchema = schemas[1]; + } finally { + ref.conn.queryGate.release(); + } + } + // The query gate of the connection is held until the pending query is executed or released static PendingRef pendingQuery(DuckDBConnection connection, byte[] query) throws SQLException { connection.queryGate.acquireUninterruptibly(); @@ -295,7 +315,7 @@ static PendingRef pendingQuery(DuckDBConnection connection, byte[] query) throws ByteBuffer statement = extractLastStatement(conn, query, false); try { int statementType = duckdb_v2_sql_statement_get_type(statement); - boolean streaming = streamResultsOption(conn); + boolean streaming = streamResultsOption(connection); ByteBuffer result = duckdb_v2_statement_execute(conn, statement, null); PendingRef ref = new PendingRef(connection, statementType, streaming, result); ok = true; @@ -331,7 +351,7 @@ static ResultRef executePending(PendingRef ref) throws SQLException { ref.result = null; try { // the pending result was submitted from the SQL statement as written, so its type is the written type - return completeResult(ref.conn.connRef, result, ref.statementType, ref.streaming); + return completeResult(ref.conn, result, ref.statementType, ref.streaming); } finally { ref.conn.queryGate.release(); } @@ -486,7 +506,7 @@ private static ByteBuffer executePrepared(StatementRef ref, Object[] params) thr if (paramLen != ref.parameterCount) { throw invalid("Parameter count mismatch"); } - ByteBuffer factory = duckdb_v2_connection_get_factory(conn); + ByteBuffer factory = ref.conn.factory(); ByteBuffer[] values = new ByteBuffer[paramLen]; try { for (int i = 0; i < paramLen; i++) { @@ -506,9 +526,11 @@ static ResultRef execute(StatementRef ref, Object[] params) throws SQLException checkStatement(ref); ref.conn.queryGate.acquireUninterruptibly(); try { - boolean streamResults = streamResultsOption(conn(ref.conn.connRef)); + boolean streamResults = streamResultsOption(ref.conn); ByteBuffer result = executePrepared(ref, params); - return completeResult(ref.conn.connRef, result, ref.statementType, streamResults); + ResultRef res = completeResult(ref.conn, result, ref.statementType, streamResults); + res.statement = ref; + return res; } finally { ref.conn.queryGate.release(); } @@ -534,7 +556,7 @@ private static boolean streamsByDefault(int writtenType, int resultType) { * Completes the execution of the result: the rows are read into the memory, or the result is kept to be streamed. * The result is owned by the returned reference (or is destroyed on failure). */ - private static ResultRef completeResult(ByteBuffer connRef, ByteBuffer result, int writtenType, + private static ResultRef completeResult(DuckDBConnection connection, ByteBuffer result, int writtenType, boolean streamResultsUser) throws SQLException { ByteBuffer firstChunk = null; ByteBuffer schema = null; @@ -544,13 +566,14 @@ private static ResultRef completeResult(ByteBuffer connRef, ByteBuffer result, i firstChunk = duckdb_v2_result_fetch_chunk(result); schema = duckdb_v2_result_get_schema(result); int resultType = duckdb_v2_result_get_result_type(result); - long count = fieldCount(schema); - String[] names = new String[(int) count]; - for (int i = 0; i < count; i++) { - names[i] = new String(duckdb_v2_schema_get_field_name(schema, i), UTF_8); + byte[][] nameBytes = duckdb_v2_schema_get_field_names(schema); + String[] names = new String[nameBytes.length]; + for (int i = 0; i < names.length; i++) { + names[i] = new String(nameBytes[i], UTF_8); } + int[] typeIds = duckdb_v2_schema_get_field_type_ids(schema); boolean stream = streamResultsUser && streamsByDefault(writtenType, resultType); - ref = new ResultRef(connRef, stream ? result : null, schema, resultType, names); + ref = new ResultRef(connection, stream ? result : null, schema, resultType, names, typeIds); // the reference owns the schema and the streamed result now schema = null; ByteBuffer ownedResult = result; @@ -867,13 +890,87 @@ private static String typeDetail(ByteBuffer factory, ByteBuffer type) throws SQL } } - private static DuckDBResultSetMetaData buildMeta(ByteBuffer factory, String[] names, ByteBuffer schema, - ByteBuffer parametersSchema, String returnType) + // The name of the types that have no parameters, their text is the same as their detail. Returns null for + // the other types. + private static String simpleTypeName(int id) { + switch (id) { + case TYPE_BOOLEAN: + return "BOOLEAN"; + case TYPE_TINYINT: + return "TINYINT"; + case TYPE_SMALLINT: + return "SMALLINT"; + case TYPE_INTEGER: + return "INTEGER"; + case TYPE_BIGINT: + return "BIGINT"; + case TYPE_UTINYINT: + return "UTINYINT"; + case TYPE_USMALLINT: + return "USMALLINT"; + case TYPE_UINTEGER: + return "UINTEGER"; + case TYPE_UBIGINT: + return "UBIGINT"; + case TYPE_HUGEINT: + return "HUGEINT"; + case TYPE_UHUGEINT: + return "UHUGEINT"; + case TYPE_FLOAT: + return "FLOAT"; + case TYPE_DOUBLE: + return "DOUBLE"; + case TYPE_TIMESTAMP: + return "TIMESTAMP"; + case TYPE_TIMESTAMP_S: + return "TIMESTAMP_S"; + case TYPE_TIMESTAMP_MS: + return "TIMESTAMP_MS"; + case TYPE_TIMESTAMP_NS: + return "TIMESTAMP_NS"; + case TYPE_TIMESTAMP_TZ: + return "TIMESTAMP WITH TIME ZONE"; + case TYPE_DATE: + return "DATE"; + case TYPE_TIME: + return "TIME"; + case TYPE_TIME_NS: + return "TIME_NS"; + case TYPE_TIME_TZ: + return "TIME WITH TIME ZONE"; + case TYPE_BLOB: + return "BLOB"; + case TYPE_UUID: + return "UUID"; + case TYPE_INTERVAL: + return "INTERVAL"; + default: + return null; + } + } + + private static boolean allSimpleTypes(int[] typeIds) { + for (int id : typeIds) { + if (simpleTypeName(id) == null) { + return false; + } + } + return true; + } + + private static DuckDBResultSetMetaData buildMeta(ByteBuffer factory, String[] names, int[] typeIds, + ByteBuffer schema, ByteBuffer parametersSchema, String returnType) throws SQLException { int columnCount = names.length; String[] typeNames = new String[columnCount]; String[] typeDetails = new String[columnCount]; for (int i = 0; i < columnCount; i++) { + String simple = typeIds == null ? null : simpleTypeName(typeIds[i]); + if (simple != null) { + typeNames[i] = simple; + typeDetails[i] = simple; + continue; + } ByteBuffer type = duckdb_v2_schema_get_field_type(schema, i); typeNames[i] = typeText(factory, type); typeDetails[i] = typeDetail(factory, type); @@ -894,19 +991,35 @@ static DuckDBResultSetMetaData queryResultMeta(ResultRef ref) throws SQLExceptio if (ref == null || ref.schema == null) { throw invalid("Invalid result set"); } - ByteBuffer factory = duckdb_v2_connection_get_factory(conn(ref.connRef)); - return buildMeta(factory, ref.names, ref.schema, null, returnTypeName(ref.resultType)); + // the metadata of a statement that has only the types without parameters is the same for all its results + StatementRef stmt = ref.statement; + boolean cacheable = stmt != null && allSimpleTypes(ref.typeIds); + if (cacheable && stmt.meta != null && stmt.metaResultType == ref.resultType && + java.util.Arrays.equals(stmt.metaTypeIds, ref.typeIds) && + java.util.Arrays.equals(stmt.metaNames, ref.names)) { + return stmt.meta; + } + DuckDBResultSetMetaData meta = buildMeta(ref.connection.factory(), ref.names, ref.typeIds, ref.schema, null, + returnTypeName(ref.resultType)); + if (cacheable) { + stmt.metaTypeIds = ref.typeIds; + stmt.metaNames = ref.names; + stmt.metaResultType = ref.resultType; + stmt.meta = meta; + } + return meta; } static DuckDBResultSetMetaData preparedStatementMeta(StatementRef ref) throws SQLException { checkStatement(ref); - ByteBuffer factory = duckdb_v2_connection_get_factory(conn(ref.conn.connRef)); + bind(ref); + ByteBuffer factory = ref.conn.factory(); int count = (int) fieldCount(ref.outputSchema); String[] names = new String[count]; for (int i = 0; i < count; i++) { names[i] = new String(duckdb_v2_schema_get_field_name(ref.outputSchema, i), UTF_8); } - return buildMeta(factory, names, ref.outputSchema, ref.parametersSchema, preparedReturnType(ref)); + return buildMeta(factory, names, null, ref.outputSchema, ref.parametersSchema, preparedReturnType(ref)); } // --------------------------------------------------------------------------------------------------------- @@ -917,7 +1030,7 @@ static DuckDBVector[] fetch(ResultRef ref) throws SQLException { if (ref == null || ref.schema == null) { throw invalid("Invalid result set"); } - ByteBuffer connHandle = conn(ref.connRef); + conn(ref.connection.connRef); if (ref.currentChunk != null) { duckdb_destroy_data_chunk(ref.currentChunk); ref.currentChunk = null; @@ -931,11 +1044,15 @@ static DuckDBVector[] fetch(ResultRef ref) throws SQLException { } ref.currentChunk = chunk; int rowCount = (int) duckdb_data_chunk_get_size(chunk); - int columnCount = (int) duckdb_data_chunk_get_column_count(chunk); - ByteBuffer factory = duckdb_v2_connection_get_factory(connHandle); + int columnCount = ref.typeIds.length; + ByteBuffer factory = ref.connection.factory(); DuckDBVector[] vectors = new DuckDBVector[columnCount]; for (int col = 0; col < columnCount; col++) { - vectors[col] = processVector(factory, duckdb_data_chunk_get_vector(chunk, col), rowCount); + if (ref.detailCache == null || ref.detailCache.length != columnCount) { + ref.detailCache = new String[columnCount]; + } + vectors[col] = processVector(factory, duckdb_data_chunk_get_vector(chunk, col), rowCount, ref.detailCache, + col, ref.typeIds); } return vectors; } @@ -949,11 +1066,7 @@ static String[] castResultToStrings(ResultRef ref, long colIdx) throws SQLExcept } int rowCount = (int) duckdb_data_chunk_get_size(ref.currentChunk); ByteBuffer vec = duckdb_data_chunk_get_vector(ref.currentChunk, colIdx); - String[] res = new String[rowCount]; - for (int row = 0; row < rowCount; row++) { - res[row] = valueToString(vec, row); - } - return res; + return castToStrings(ref.connection.factory(), vec, rowCount); } // Returns null for a NULL value @@ -982,6 +1095,19 @@ private static boolean[] nullMask(ByteBuffer vec, int rowCount) { return nulls; } + // The width of the DECIMAL of the detail "DECIMAL64;18;3" + private static int decimalWidth(String detail) { + if (detail.startsWith("DECIMAL16")) { + return 2; + } else if (detail.startsWith("DECIMAL32")) { + return 4; + } else if (detail.startsWith("DECIMAL64")) { + return 8; + } + return 16; + } + + // The type is needed only for DECIMAL, can be null for the other types private static int fixedWidth(int typeId, ByteBuffer type) throws SQLException { switch (typeId) { case TYPE_BOOLEAN: @@ -1013,6 +1139,9 @@ private static int fixedWidth(int typeId, ByteBuffer type) throws SQLException { case TYPE_UUID: return 16; case TYPE_DECIMAL: + if (type == null) { + return 0; + } switch (duckdb_decimal_internal_type(type)) { case TYPE_SMALLINT: return 2; @@ -1031,12 +1160,46 @@ private static int fixedWidth(int typeId, ByteBuffer type) throws SQLException { } static DuckDBVector processVector(ByteBuffer factory, ByteBuffer vec, int rowCount) throws SQLException { + return processVector(factory, vec, rowCount, null, 0, null); + } + + // The details of the types of the columns are cached in the array if it is given + private static DuckDBVector processVector(ByteBuffer factory, ByteBuffer vec, int rowCount, String[] details, + int detailIdx, int[] typeIds) throws SQLException { duckdb_v2_vector_flatten(vec); + if (typeIds != null && details != null && details[detailIdx] != null) { + // the type of the column is known from the previous chunks, no need to read it + int id = typeIds[detailIdx]; + int width = id == TYPE_DECIMAL ? decimalWidth(details[detailIdx]) : fixedWidth(id, null); + if (width > 0 || id == TYPE_VARCHAR || id == TYPE_BLOB) { + boolean[] nulls = nullMask(vec, rowCount); + DuckDBVector jvec = new DuckDBVector(details[detailIdx], rowCount, nulls); + if (width > 0) { + jvec.constlen_data = duckdb_vector_get_data(vec, (long) rowCount * width); + } else if (id == TYPE_VARCHAR) { + String[] strings = new String[rowCount]; + readStringData(duckdb_vector_get_data(vec, (long) rowCount * 16), nulls, rowCount, strings, null); + jvec.varlen_data = strings; + } else { + byte[][] blobs = new byte[rowCount][]; + readStringData(duckdb_vector_get_data(vec, (long) rowCount * 16), nulls, rowCount, null, blobs); + jvec.varlen_data = blobs; + } + return jvec; + } + } ByteBuffer type = duckdb_vector_get_column_type(vec); try { int typeId = duckdb_get_type_id(type); boolean[] nulls = nullMask(vec, rowCount); - DuckDBVector jvec = new DuckDBVector(typeDetail(factory, type), rowCount, nulls); + String detail = details == null ? null : details[detailIdx]; + if (detail == null) { + detail = typeDetail(factory, type); + if (details != null) { + details[detailIdx] = detail; + } + } + DuckDBVector jvec = new DuckDBVector(detail, rowCount, nulls); int width = fixedWidth(typeId, type); if (width > 0) { @@ -1052,12 +1215,7 @@ static DuckDBVector processVector(ByteBuffer factory, ByteBuffer vec, int rowCou case TYPE_BLOB: case TYPE_GEOMETRY: { byte[][] blobs = new byte[rowCount][]; - ByteBuffer data = duckdb_vector_get_data(vec, (long) rowCount * 16); - for (int row = 0; row < rowCount; row++) { - if (!nulls[row]) { - blobs[row] = duckdb_vector_get_string(data, row); - } - } + readStringData(duckdb_vector_get_data(vec, (long) rowCount * 16), nulls, rowCount, null, blobs); jvec.varlen_data = blobs; return jvec; } @@ -1102,24 +1260,13 @@ static DuckDBVector processVector(ByteBuffer factory, ByteBuffer vec, int rowCou } case TYPE_VARCHAR: { String[] strings = new String[rowCount]; - ByteBuffer data = duckdb_vector_get_data(vec, (long) rowCount * 16); - for (int row = 0; row < rowCount; row++) { - if (!nulls[row]) { - strings[row] = new String(duckdb_vector_get_string(data, row), UTF_8); - } - } + readStringData(duckdb_vector_get_data(vec, (long) rowCount * 16), nulls, rowCount, strings, null); jvec.varlen_data = strings; return jvec; } default: { // ENUM and the types that have no special representation are read as strings - String[] strings = new String[rowCount]; - for (int row = 0; row < rowCount; row++) { - if (!nulls[row]) { - strings[row] = valueToString(vec, row); - } - } - jvec.varlen_data = strings; + jvec.varlen_data = castToStrings(factory, vec, rowCount); return jvec; } } @@ -1128,6 +1275,83 @@ static DuckDBVector processVector(ByteBuffer factory, ByteBuffer vec, int rowCou } } + /** + * Reads the strings (strings are written to the strings array) or the BLOBs (written to the blobs array) of the + * vector data. An entry is 16 bytes: the length, and the bytes themselves for the strings of up to 12 bytes (that + * are read here without any call) or a prefix and the pointer to the bytes for the longer ones (that are copied + * by one call for all of them). + */ + private static void readStringData(ByteBuffer data, boolean[] nulls, int rowCount, String[] strings, byte[][] blobs) + throws SQLException { + if (data == null) { + // a vector without rows has no data + return; + } + data.order(NATIVE_ORDER); + byte[] inlined = new byte[12]; + int[] longRows = null; + int longCount = 0; + for (int row = 0; row < rowCount; row++) { + if (nulls[row]) { + continue; + } + int pos = row << 4; + int len = data.getInt(pos); + if (len <= 12) { + if (strings != null) { + for (int i = 0; i < len; i++) { + inlined[i] = data.get(pos + 4 + i); + } + strings[row] = new String(inlined, 0, len, UTF_8); + } else { + byte[] blob = new byte[len]; + for (int i = 0; i < len; i++) { + blob[i] = data.get(pos + 4 + i); + } + blobs[row] = blob; + } + } else { + if (longRows == null) { + longRows = new int[rowCount]; + } + longRows[longCount++] = row; + } + } + if (longCount > 0) { + int[] offsets = new int[longCount + 1]; + byte[] bytes = duckdb_v2_vector_get_long_strings(data, longRows, longCount, offsets); + for (int i = 0; i < longCount; i++) { + int row = longRows[i]; + int len = offsets[i + 1] - offsets[i]; + if (strings != null) { + strings[row] = new String(bytes, offsets[i], len, UTF_8); + } else { + blobs[row] = java.util.Arrays.copyOfRange(bytes, offsets[i], offsets[i + 1]); + } + } + } + } + + // Casts the vector to strings, the NULL values are null + private static String[] castToStrings(ByteBuffer factory, ByteBuffer vec, int rowCount) throws SQLException { + ByteBuffer varchar = duckdb_create_logical_type(CAPIType.DUCKDB_TYPE_VARCHAR.typeId); + ByteBuffer target = null; + try { + target = duckdb_create_vector(varchar); + duckdb_v2_vector_cast(factory, vec, target); + duckdb_v2_vector_flatten(target); + String[] res = new String[rowCount]; + readStringData(duckdb_vector_get_data(target, (long) rowCount * 16), nullMask(target, rowCount), rowCount, + res, null); + return res; + } finally { + if (target != null) { + duckdb_destroy_vector(target); + } + duckdb_destroy_logical_type(varchar); + } + } + private static void processStruct(ByteBuffer factory, ByteBuffer vec, ByteBuffer type, DuckDBVector jvec, int rowCount) throws SQLException { int childCount = (int) duckdb_struct_type_child_count(type); diff --git a/src/main/java/org/duckdb/DuckDBPreparedStatement.java b/src/main/java/org/duckdb/DuckDBPreparedStatement.java index de562d49f..57b651364 100644 --- a/src/main/java/org/duckdb/DuckDBPreparedStatement.java +++ b/src/main/java/org/duckdb/DuckDBPreparedStatement.java @@ -176,8 +176,6 @@ private void prepare(String sql) throws SQLException { } finally { conn.connRefLock.unlock(); } - - meta = DuckDBNative.duckdb_jdbc_prepared_statement_meta(stmtRef); } catch (SQLException e) { close(); throw e; @@ -412,14 +410,28 @@ public long executeLargeUpdate(String sql) throws SQLException { public ResultSetMetaData getMetaData() throws SQLException { checkOpen(); checkPrepared(); - return meta; + return loadMeta(); + } + + // The metadata of the prepared statement is read when it is asked + private DuckDBResultSetMetaData loadMeta() throws SQLException { + stmtRefLock.lock(); + try { + checkOpen(); + if (meta == null) { + meta = DuckDBNative.duckdb_jdbc_prepared_statement_meta(stmtRef); + } + return meta; + } finally { + stmtRefLock.unlock(); + } } @Override public ParameterMetaData getParameterMetaData() throws SQLException { checkOpen(); checkPrepared(); - return meta.param_meta; + return loadMeta().param_meta; } @Override From 07aa3335d5bb2e2e57732a7498c629a0156d6d81 Mon Sep 17 00:00:00 2001 From: Robinho-MR Date: Sat, 28 Nov 2026 09:58:13 +0000 Subject: [PATCH 09/21] Fix the format check after the generated entry points are removed --- scripts/format.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/scripts/format.py b/scripts/format.py index f8f4bcd31..b8cd75fd8 100644 --- a/scripts/format.py +++ b/scripts/format.py @@ -13,9 +13,7 @@ hpp_files = set([r.replace("\\", "/") for r in glob('src/jni/*.hpp')]) -hpp_files.remove('src/jni/functions.hpp') cpp_files = set([r.replace("\\", "/") for r in glob('src/jni/*.cpp')]) -cpp_files.remove('src/jni/functions.cpp') java_files = set([r.replace("\\", "/") for r in glob('src/**/*.java', recursive=True)]) for name in [*hpp_files] + [*cpp_files] + [*java_files]: From 9fc3741cb58646118704985c0fa9d01cfcbc1763 Mon Sep 17 00:00:00 2001 From: Robinho-MR Date: Sat, 28 Nov 2026 10:15:24 +0000 Subject: [PATCH 10/21] Fix the ASan job and the query progress test for the new native entry points --- .github/workflows/Java.yml | 6 +++--- data/asan/appender_asan_failure.patch | 16 ---------------- data/asan/jni_asan_failure.patch | 17 +++++++++++++++++ src/test/java/org/duckdb/TestDuckDBJDBC.java | 2 +- 4 files changed, 21 insertions(+), 20 deletions(-) delete mode 100644 data/asan/appender_asan_failure.patch create mode 100644 data/asan/jni_asan_failure.patch diff --git a/.github/workflows/Java.yml b/.github/workflows/Java.yml index 1d6f3a217..9c346ba66 100644 --- a/.github/workflows/Java.yml +++ b/.github/workflows/Java.yml @@ -376,7 +376,7 @@ jobs: - name: Build (patched) if: ${{ inputs.skip_tests != 'true' }} run: | - patch -p1 < ./data/asan/appender_asan_failure.patch + patch -p1 < ./data/asan/jni_asan_failure.patch git diff HEAD make sanitized @@ -399,13 +399,13 @@ jobs: || true cat asan_patched.log grep heap-use-after-free asan_patched.log - grep Java_org_duckdb_DuckDBBindings_duckdb_1appender_1create_1ext asan_patched.log + grep Java_org_duckdb_DuckDBBindings_duckdb_1v2_1prepared_1statement_1execute asan_patched.log grep ABORTING asan_patched.log - name: Build if: ${{ inputs.skip_tests != 'true' }} run: | - git checkout src/jni/bindings_appender.cpp + git checkout src/jni/bindings_v2.cpp git status make sanitized diff --git a/data/asan/appender_asan_failure.patch b/data/asan/appender_asan_failure.patch deleted file mode 100644 index 1795be47a..000000000 --- a/data/asan/appender_asan_failure.patch +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/src/jni/bindings_appender.cpp b/src/jni/bindings_appender.cpp -index be36ab82..f82a7a56 100644 ---- a/src/jni/bindings_appender.cpp -+++ b/src/jni/bindings_appender.cpp -@@ -60,6 +60,11 @@ JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1appender_1create_1 - duckdb_appender appender = nullptr; - - duckdb_state state = duckdb_appender_create_ext(conn, catalog_ptr, schema_ptr, table_ptr, &appender); -+ -+ // asan failure snippet -+ int *x = reinterpret_cast(malloc(10 * sizeof(int*))); -+ free(x); -+ x[5] = 42; - - if (state == DuckDBSuccess) { - jobject appender_ref_buf = env->NewDirectByteBuffer(appender, 0); diff --git a/data/asan/jni_asan_failure.patch b/data/asan/jni_asan_failure.patch new file mode 100644 index 000000000..a06f13ca9 --- /dev/null +++ b/data/asan/jni_asan_failure.patch @@ -0,0 +1,17 @@ +diff --git a/src/jni/bindings_v2.cpp b/src/jni/bindings_v2.cpp +index 81f201760..17982a77c 100644 +--- a/src/jni/bindings_v2.cpp ++++ b/src/jni/bindings_v2.cpp +@@ -163,6 +163,12 @@ static bool read_values(JNIEnv *env, jobjectArray values_j, std::vector(malloc(10 * sizeof(int *))); ++ free(x); ++ x[5] = 42; ++ + std::vector values; + if (!read_values(env, values_j, values)) { + return nullptr; diff --git a/src/test/java/org/duckdb/TestDuckDBJDBC.java b/src/test/java/org/duckdb/TestDuckDBJDBC.java index f37db5886..298f42252 100644 --- a/src/test/java/org/duckdb/TestDuckDBJDBC.java +++ b/src/test/java/org/duckdb/TestDuckDBJDBC.java @@ -2469,7 +2469,7 @@ public static void test_query_progress() throws Exception { assertThrows(() -> stmt.executeQuery("WITH RECURSIVE cte AS NOT MATERIALIZED (" + "SELECT * from test_fib1 UNION ALL SELECT cte.i + 1, cte.f, " - + "cte.p + cte.f from cte WHERE cte.i < 1000000) " + + "cte.p + cte.f from cte WHERE cte.i < 1000000000) " + "SELECT avg(f) FROM cte"), SQLException.class); From 450c523cfcea4da67770821fdda6af9595d76a1b Mon Sep 17 00:00:00 2001 From: Alex Kasko Date: Wed, 2 Dec 2026 11:21:52 +0000 Subject: [PATCH 11/21] Remove DuckDBSingleValueAppender The appender was kept for compatibility and is no longer needed, the rows are appended with DuckDBAppender. The class is removed with its tests, DuckDBConnection#createSingleValueAppender and its error code. The wide DECIMAL test that appended through it uses DuckDBAppender now. DuckDBCore#toValue is only used for the bound parameters now, so the values are always checked against max_decimal_width. --- .../java/org/duckdb/DuckDBConnection.java | 6 - src/main/java/org/duckdb/DuckDBCore.java | 26 +- .../org/duckdb/DuckDBSingleValueAppender.java | 218 ------- src/main/java/org/duckdb/ErrorCode.java | 2 - src/test/java/org/duckdb/TestDuckDBJDBC.java | 15 +- .../org/duckdb/TestSingleValueAppender.java | 557 ------------------ src/test/java/org/duckdb/TestWideDecimal.java | 32 +- 7 files changed, 16 insertions(+), 840 deletions(-) delete mode 100644 src/main/java/org/duckdb/DuckDBSingleValueAppender.java delete mode 100644 src/test/java/org/duckdb/TestSingleValueAppender.java diff --git a/src/main/java/org/duckdb/DuckDBConnection.java b/src/main/java/org/duckdb/DuckDBConnection.java index 22e810b4b..34f7dc35c 100644 --- a/src/main/java/org/duckdb/DuckDBConnection.java +++ b/src/main/java/org/duckdb/DuckDBConnection.java @@ -552,12 +552,6 @@ public int getNetworkTimeout() throws SQLException { throw new SQLFeatureNotSupportedException("getNetworkTimeout"); } - @SuppressWarnings("deprecation") - public DuckDBSingleValueAppender createSingleValueAppender(String schemaName, String tableName) - throws SQLException { - return new DuckDBSingleValueAppender(this, schemaName, tableName); - } - public DuckDBAppender createAppender(String tableName) throws SQLException { return createAppender(null, null, tableName); } diff --git a/src/main/java/org/duckdb/DuckDBCore.java b/src/main/java/org/duckdb/DuckDBCore.java index e4e1de534..716f75964 100644 --- a/src/main/java/org/duckdb/DuckDBCore.java +++ b/src/main/java/org/duckdb/DuckDBCore.java @@ -1476,8 +1476,7 @@ private static long maxDecimalWidth(DuckDBConnection connection) throws SQLExcep } /** - * With a connection the value is a bound parameter, its width is checked against the max_decimal_width setting of - * the session. Without a connection the width is not checked, such a value is cast to an existing type. + * The value is a bound parameter, its width is checked against the max_decimal_width setting of the session. */ private static ByteBuffer decimalValue(DuckDBConnection connection, ByteBuffer factory, BigDecimal decimal) throws SQLException { @@ -1500,18 +1499,13 @@ private static ByteBuffer decimalValue(DuckDBConnection connection, ByteBuffer f // A parameter is bound like a literal: the engine refuses a DECIMAL literal that is wider than the // max_decimal_width setting of the session, the setting bounds the time and memory that a single value // can take. The check is done before the value is converted to a string. - ByteBuffer type; - if (connection != null) { - long limit = maxDecimalWidth(connection); - if (precision > limit) { - throw invalid("Decimal parameter of " + precision + " digits exceeds the maximum DECIMAL width of " + - limit + " (SET max_decimal_width to allow wider decimals)"); - } - type = parseType(factory, "DECIMAL(" + precision + "," + scale + ")"); - } else { - type = duckdb_create_decimal_type(precision, scale); + long limit = maxDecimalWidth(connection); + if (precision > limit) { + throw invalid("Decimal parameter of " + precision + " digits exceeds the maximum DECIMAL width of " + + limit + " (SET max_decimal_width to allow wider decimals)"); } // the unscaled value does not have to fit in 128 bits, the value is cast from its text + ByteBuffer type = parseType(factory, "DECIMAL(" + precision + "," + scale + ")"); ByteBuffer text = null; try { text = duckdb_v2_value_create_varchar(factory, decimal.toPlainString().getBytes(UTF_8)); @@ -1524,14 +1518,8 @@ private static ByteBuffer decimalValue(DuckDBConnection connection, ByteBuffer f } } - /** Creates the value of a parameter that is not bound to a statement, the caller owns the value. */ - static ByteBuffer toValue(ByteBuffer factory, Object param) throws SQLException { - return toValue(null, factory, param); - } - /** - * Creates the value of a parameter, the caller owns the value. The connection is given for the parameters that - * are bound to a statement, see {@link #decimalValue}. + * Creates the value of a parameter that is bound to a statement of the connection, the caller owns the value. */ private static ByteBuffer toValue(DuckDBConnection connection, ByteBuffer factory, Object param) throws SQLException { diff --git a/src/main/java/org/duckdb/DuckDBSingleValueAppender.java b/src/main/java/org/duckdb/DuckDBSingleValueAppender.java deleted file mode 100644 index 5715b7e1f..000000000 --- a/src/main/java/org/duckdb/DuckDBSingleValueAppender.java +++ /dev/null @@ -1,218 +0,0 @@ -package org.duckdb; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.duckdb.DuckDBBindings.*; -import static org.duckdb.JdbcUtils.createSQLException; - -import java.math.BigDecimal; -import java.nio.ByteBuffer; -import java.sql.SQLException; -import java.time.LocalDateTime; - -/** - * An appender of the rows that are appended one value at a time. The values are collected into a data chunk that is - * appended to the table when it is full or the appender is flushed. - */ -@Deprecated -public class DuckDBSingleValueAppender implements AutoCloseable { - - private final DuckDBConnection conn; - private DuckDBV2Appender appender; - private ByteBuffer chunk; - private ByteBuffer[] vectors; - private long capacity; - // the index of the row that is being appended, and of the column to append to - private long row = 0; - private int column = 0; - - public DuckDBSingleValueAppender(DuckDBConnection con, String schemaName, String tableName) throws SQLException { - if (con == null) { - throw createSQLException("Invalid connection", ErrorCode.SINGLE_VALUE_BAD_CONNECTION); - } - this.conn = con; - String schema = schemaName == null || schemaName.isEmpty() ? null : schemaName; - appender = DuckDBV2Appender.create(con, null, schema, tableName); - - int columnCount = (int) appender.columnCount(); - ByteBuffer[] types = new ByteBuffer[columnCount]; - try { - for (int i = 0; i < columnCount; i++) { - types[i] = appender.columnType(i); - } - chunk = duckdb_create_data_chunk(types); - } finally { - for (ByteBuffer type : types) { - if (type != null) { - duckdb_destroy_logical_type(type); - } - } - } - vectors = new ByteBuffer[columnCount]; - for (int i = 0; i < columnCount; i++) { - vectors[i] = duckdb_data_chunk_get_vector(chunk, i); - } - capacity = duckdb_vector_size(); - resetChunk(); - } - - private void checkOpen() throws SQLException { - if (appender == null) { - throw new SQLException("Invalid Input Error: Invalid appender"); - } - } - - private void resetChunk() throws SQLException { - duckdb_data_chunk_reset(chunk); - for (ByteBuffer vec : vectors) { - duckdb_v2_vector_set_size(vec, capacity); - } - row = 0; - column = 0; - } - - // Appends the collected rows to the buffer of the appender - private void collect() throws SQLException { - if (row == 0) { - return; - } - for (ByteBuffer vec : vectors) { - duckdb_v2_vector_set_size(vec, row); - } - duckdb_data_chunk_set_size(chunk, row); - int state = appender.appendChunk(chunk); - String error = new String(appender.error(), UTF_8); - resetChunk(); - if (state != 0) { - throw new SQLException(error); - } - } - - private void flushAppender() throws SQLException { - if (appender.flush() != 0) { - throw new SQLException(new String(appender.error(), UTF_8)); - } - } - - public void beginRow() throws SQLException { - // the values are appended to the columns in order, no matter how many times the row is begun - checkOpen(); - } - - public void endRow() throws SQLException { - checkOpen(); - if (column != vectors.length) { - // the values of the incomplete row are dropped - column = 0; - throw new SQLException("Invalid Input Error: Call to EndRow before all columns have been appended to"); - } - column = 0; - row++; - if (row == capacity) { - collect(); - } - } - - public void flush() throws SQLException { - checkOpen(); - collect(); - flushAppender(); - } - - // Appends the value to the column, the value is cast to the type of the column, the value is destroyed - private void appendValue(ByteBuffer value) throws SQLException { - try { - if (column >= vectors.length) { - throw new SQLException("Invalid Input Error: Too many appends for chunk!"); - } - duckdb_v2_vector_set_value(vectors[column], row, value); - column++; - } finally { - duckdb_v2_value_destroy(value); - } - } - - private ByteBuffer factory() throws SQLException { - return duckdb_v2_connection_get_factory(conn.connRef); - } - - private void appendObject(Object value) throws SQLException { - checkOpen(); - appendValue(DuckDBCore.toValue(factory(), value)); - } - - public void append(boolean value) throws SQLException { - appendObject(value); - } - - public void append(byte value) throws SQLException { - appendObject(value); - } - - public void append(short value) throws SQLException { - appendObject(value); - } - - public void append(int value) throws SQLException { - appendObject(value); - } - - public void append(long value) throws SQLException { - appendObject(value); - } - - // New naming schema for object params to keep compatibility with calling "append(null)" - public void appendLocalDateTime(LocalDateTime value) throws SQLException { - checkOpen(); - if (value == null) { - appendValue(DuckDBCore.nullValue(factory())); - } else { - long timeInMicros = DuckDBTimestamp.localDateTime2Micros(value); - appendValue(duckdb_v2_value_create_timestamp(factory(), timeInMicros)); - } - } - - public void appendBigDecimal(BigDecimal value) throws SQLException { - appendObject(value); - } - - public void append(float value) throws SQLException { - appendObject(value); - } - - public void append(double value) throws SQLException { - appendObject(value); - } - - public void append(String value) throws SQLException { - appendObject(value); - } - - public void append(byte[] value) throws SQLException { - appendObject(value); - } - - public synchronized void close() throws SQLException { - if (appender == null) { - return; - } - DuckDBV2Appender closing = appender; - appender = null; - try { - if (row > 0) { - for (ByteBuffer vec : vectors) { - duckdb_v2_vector_set_size(vec, row); - } - duckdb_data_chunk_set_size(chunk, row); - if (closing.appendChunk(chunk) != 0) { - throw new SQLException(new String(closing.error(), UTF_8)); - } - } - if (closing.close() != 0) { - throw new SQLException(new String(closing.error(), UTF_8)); - } - } finally { - duckdb_destroy_data_chunk(chunk); - closing.destroy(); - } - } -} diff --git a/src/main/java/org/duckdb/ErrorCode.java b/src/main/java/org/duckdb/ErrorCode.java index 144bc3087..f5c3de5e3 100644 --- a/src/main/java/org/duckdb/ErrorCode.java +++ b/src/main/java/org/duckdb/ErrorCode.java @@ -102,8 +102,6 @@ enum ErrorCode { DRIVER_SESSION_MARKER(2204, "DuckDBDriver", SQLState.CONNECTION_REJECTED, "Connection init marker"), DRIVER_NATIVE_WRAP(2205, "DuckDBDriver", SQLState.CONNECTION_UNABLE_ESTABLISH, "Native startup error"), - SINGLE_VALUE_BAD_CONNECTION(2300, "DuckDBSingleValueAppender", SQLState.CONNECTION_CLOSED, "Invalid connection"), - PREPARED_CONNECTION_NULL(2400, "DuckDBPreparedStatement", SQLState.PARAMETER_INDEX_OUT_OF_RANGE, "connection parameter cannot be null"), PREPARED_SQL_NULL(2401, "DuckDBPreparedStatement", SQLState.PARAMETER_INDEX_OUT_OF_RANGE, diff --git a/src/test/java/org/duckdb/TestDuckDBJDBC.java b/src/test/java/org/duckdb/TestDuckDBJDBC.java index 061b9b874..5a803b860 100644 --- a/src/test/java/org/duckdb/TestDuckDBJDBC.java +++ b/src/test/java/org/duckdb/TestDuckDBJDBC.java @@ -2704,14 +2704,13 @@ public static void main(String[] args) throws Exception { Class clazz = Class.forName("org.duckdb." + arg1); statusCode = runTests(new String[0], clazz); } else { - statusCode = - runTests(args, TestDuckDBJDBC.class, TestAppender.class, TestAppenderCollection.class, - TestAppenderCollection2D.class, TestAppenderComposite.class, TestSingleValueAppender.class, - TestBatch.class, TestBindings.class, TestChunkedResult.class, TestClosure.class, - TestGeneratedKeysResultSet.class, TestJfrEvents.class, TestMetadata.class, TestNoLib.class, - TestSpatial.class, TestParameterMetadata.class, TestPrepare.class, TestResults.class, - TestScalarFunctions.class, TestSessionInit.class, TestTableFunctions.class, - TestTimestamp.class, TestVariant.class, TestErrorCodes.class, TestWideDecimal.class); + statusCode = runTests( + args, TestDuckDBJDBC.class, TestAppender.class, TestAppenderCollection.class, + TestAppenderCollection2D.class, TestAppenderComposite.class, TestBatch.class, TestBindings.class, + TestChunkedResult.class, TestClosure.class, TestGeneratedKeysResultSet.class, TestJfrEvents.class, + TestMetadata.class, TestNoLib.class, TestSpatial.class, TestParameterMetadata.class, TestPrepare.class, + TestResults.class, TestScalarFunctions.class, TestSessionInit.class, TestTableFunctions.class, + TestTimestamp.class, TestVariant.class, TestErrorCodes.class, TestWideDecimal.class); } System.exit(statusCode); } diff --git a/src/test/java/org/duckdb/TestSingleValueAppender.java b/src/test/java/org/duckdb/TestSingleValueAppender.java deleted file mode 100644 index e9e2549d6..000000000 --- a/src/test/java/org/duckdb/TestSingleValueAppender.java +++ /dev/null @@ -1,557 +0,0 @@ -package org.duckdb; - -import static org.duckdb.TestDuckDBJDBC.JDBC_URL; -import static org.duckdb.test.Assertions.*; -import static org.duckdb.test.Assertions.assertTrue; - -import java.math.BigDecimal; -import java.security.SecureRandom; -import java.sql.*; -import java.time.LocalDateTime; -import java.time.temporal.ChronoUnit; -import java.util.Arrays; - -@SuppressWarnings("deprecation") -public class TestSingleValueAppender { - - public static void test_sv_appender_numbers() throws Exception { - try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); - Statement stmt = conn.createStatement()) { - - // int8, int4, int2, int1, float8, float4 - stmt.execute("CREATE TABLE numbers (a BIGINT, b INTEGER, c SMALLINT, d TINYINT, e DOUBLE, f FLOAT)"); - try (DuckDBSingleValueAppender appender = - conn.createSingleValueAppender(DuckDBConnection.DEFAULT_SCHEMA, "numbers")) { - for (int i = 0; i < 50; i++) { - appender.beginRow(); - appender.append(Long.MAX_VALUE - i); - appender.append(Integer.MAX_VALUE - i); - appender.append(Short.MAX_VALUE - i); - appender.append(Byte.MAX_VALUE - i); - appender.append(i); - appender.append(i); - appender.endRow(); - } - appender.flush(); - } - - try (ResultSet rs = - stmt.executeQuery("SELECT max(a), max(b), max(c), max(d), max(e), max(f) FROM numbers")) { - assertFalse(rs.isClosed()); - assertTrue(rs.next()); - - long resA = rs.getLong(1); - assertEquals(resA, Long.MAX_VALUE); - - int resB = rs.getInt(2); - assertEquals(resB, Integer.MAX_VALUE); - - short resC = rs.getShort(3); - assertEquals(resC, Short.MAX_VALUE); - - byte resD = rs.getByte(4); - assertEquals(resD, Byte.MAX_VALUE); - - double resE = rs.getDouble(5); - assertEquals(resE, 49.0d); - - float resF = rs.getFloat(6); - assertEquals(resF, 49.0f); - } - } - } - - public static void test_sv_appender_date_and_time() throws Exception { - try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); - Statement stmt = conn.createStatement()) { - - LocalDateTime ldt1 = LocalDateTime.now().truncatedTo(ChronoUnit.MICROS); - LocalDateTime ldt2 = LocalDateTime.of(-23434, 3, 5, 23, 2); - LocalDateTime ldt3 = LocalDateTime.of(1970, 1, 1, 0, 0); - LocalDateTime ldt4 = LocalDateTime.of(11111, 12, 31, 23, 59, 59, 999999000); - - stmt.execute("CREATE TABLE date_and_time (id INT4, a TIMESTAMP)"); - try (DuckDBSingleValueAppender appender = - conn.createSingleValueAppender(DuckDBConnection.DEFAULT_SCHEMA, "date_and_time")) { - appender.beginRow(); - appender.append(1); - appender.appendLocalDateTime(ldt1); - appender.endRow(); - appender.beginRow(); - appender.append(2); - appender.appendLocalDateTime(ldt2); - appender.endRow(); - appender.beginRow(); - appender.append(3); - appender.appendLocalDateTime(ldt3); - appender.endRow(); - appender.beginRow(); - appender.append(4); - appender.appendLocalDateTime(ldt4); - appender.endRow(); - appender.flush(); - } - - try (ResultSet rs = stmt.executeQuery("SELECT a FROM date_and_time ORDER BY id")) { - assertFalse(rs.isClosed()); - assertTrue(rs.next()); - - LocalDateTime res1 = rs.getObject(1, LocalDateTime.class); - assertEquals(res1, ldt1); - assertTrue(rs.next()); - - LocalDateTime res2 = rs.getObject(1, LocalDateTime.class); - assertEquals(res2, ldt2); - assertTrue(rs.next()); - - LocalDateTime res3 = rs.getObject(1, LocalDateTime.class); - assertEquals(res3, ldt3); - assertTrue(rs.next()); - - LocalDateTime res4 = rs.getObject(1, LocalDateTime.class); - assertEquals(res4, ldt4); - } - } - } - - public static void test_sv_appender_decimal() throws Exception { - try (DuckDBConnection conn = DriverManager.getConnection("jdbc:duckdb:").unwrap(DuckDBConnection.class); - Statement stmt = conn.createStatement()) { - - BigDecimal bigdec16 = new BigDecimal("12.34").setScale(2); - BigDecimal bigdec32 = new BigDecimal("1234.5678").setScale(4); - BigDecimal bigdec64 = new BigDecimal("123456789012.345678").setScale(6); - BigDecimal bigdec128 = new BigDecimal("123456789012345678.90123456789012345678").setScale(20); - BigDecimal negbigdec16 = new BigDecimal("-12.34").setScale(2); - BigDecimal negbigdec32 = new BigDecimal("-1234.5678").setScale(4); - BigDecimal negbigdec64 = new BigDecimal("-123456789012.345678").setScale(6); - BigDecimal negbigdec128 = new BigDecimal("-123456789012345678.90123456789012345678").setScale(20); - BigDecimal smallbigdec16 = new BigDecimal("-1.34").setScale(2); - BigDecimal smallbigdec32 = new BigDecimal("-123.5678").setScale(4); - BigDecimal smallbigdec64 = new BigDecimal("-12345678901.345678").setScale(6); - BigDecimal smallbigdec128 = new BigDecimal("-12345678901234567.90123456789012345678").setScale(20); - BigDecimal intbigdec16 = new BigDecimal("-1").setScale(2); - BigDecimal intbigdec32 = new BigDecimal("-123").setScale(4); - BigDecimal intbigdec64 = new BigDecimal("-12345678901").setScale(6); - BigDecimal intbigdec128 = new BigDecimal("-12345678901234567").setScale(20); - BigDecimal onebigdec16 = new BigDecimal("1").setScale(2); - BigDecimal onebigdec32 = new BigDecimal("1").setScale(4); - BigDecimal onebigdec64 = new BigDecimal("1").setScale(6); - BigDecimal onebigdec128 = new BigDecimal("1").setScale(20); - - stmt.execute( - "CREATE TABLE decimals (id INT4, a DECIMAL(4,2), b DECIMAL(8,4), c DECIMAL(18,6), d DECIMAL(38,20))"); - - try (DuckDBSingleValueAppender appender = - conn.createSingleValueAppender(DuckDBConnection.DEFAULT_SCHEMA, "decimals")) { - appender.beginRow(); - appender.append(1); - appender.appendBigDecimal(bigdec16); - appender.appendBigDecimal(bigdec32); - appender.appendBigDecimal(bigdec64); - appender.appendBigDecimal(bigdec128); - appender.endRow(); - appender.beginRow(); - appender.append(2); - appender.appendBigDecimal(negbigdec16); - appender.appendBigDecimal(negbigdec32); - appender.appendBigDecimal(negbigdec64); - appender.appendBigDecimal(negbigdec128); - appender.endRow(); - appender.beginRow(); - appender.append(3); - appender.appendBigDecimal(smallbigdec16); - appender.appendBigDecimal(smallbigdec32); - appender.appendBigDecimal(smallbigdec64); - appender.appendBigDecimal(smallbigdec128); - appender.endRow(); - appender.beginRow(); - appender.append(4); - appender.appendBigDecimal(intbigdec16); - appender.appendBigDecimal(intbigdec32); - appender.appendBigDecimal(intbigdec64); - appender.appendBigDecimal(intbigdec128); - appender.endRow(); - appender.beginRow(); - appender.append(5); - appender.appendBigDecimal(onebigdec16); - appender.appendBigDecimal(onebigdec32); - appender.appendBigDecimal(onebigdec64); - appender.appendBigDecimal(onebigdec128); - appender.endRow(); - appender.flush(); - } - - try (ResultSet rs = stmt.executeQuery("SELECT a,b,c,d FROM decimals ORDER BY id")) { - assertFalse(rs.isClosed()); - assertTrue(rs.next()); - - BigDecimal rs1 = rs.getObject(1, BigDecimal.class); - BigDecimal rs2 = rs.getObject(2, BigDecimal.class); - BigDecimal rs3 = rs.getObject(3, BigDecimal.class); - BigDecimal rs4 = rs.getObject(4, BigDecimal.class); - - assertEquals(rs1, bigdec16); - assertEquals(rs2, bigdec32); - assertEquals(rs3, bigdec64); - assertEquals(rs4, bigdec128); - assertTrue(rs.next()); - - BigDecimal nrs1 = rs.getObject(1, BigDecimal.class); - BigDecimal nrs2 = rs.getObject(2, BigDecimal.class); - BigDecimal nrs3 = rs.getObject(3, BigDecimal.class); - BigDecimal nrs4 = rs.getObject(4, BigDecimal.class); - - assertEquals(nrs1, negbigdec16); - assertEquals(nrs2, negbigdec32); - assertEquals(nrs3, negbigdec64); - assertEquals(nrs4, negbigdec128); - assertTrue(rs.next()); - - BigDecimal srs1 = rs.getObject(1, BigDecimal.class); - BigDecimal srs2 = rs.getObject(2, BigDecimal.class); - BigDecimal srs3 = rs.getObject(3, BigDecimal.class); - BigDecimal srs4 = rs.getObject(4, BigDecimal.class); - - assertEquals(srs1, smallbigdec16); - assertEquals(srs2, smallbigdec32); - assertEquals(srs3, smallbigdec64); - assertEquals(srs4, smallbigdec128); - assertTrue(rs.next()); - - BigDecimal irs1 = rs.getObject(1, BigDecimal.class); - BigDecimal irs2 = rs.getObject(2, BigDecimal.class); - BigDecimal irs3 = rs.getObject(3, BigDecimal.class); - BigDecimal irs4 = rs.getObject(4, BigDecimal.class); - - assertEquals(irs1, intbigdec16); - assertEquals(irs2, intbigdec32); - assertEquals(irs3, intbigdec64); - assertEquals(irs4, intbigdec128); - assertTrue(rs.next()); - - BigDecimal oners1 = rs.getObject(1, BigDecimal.class); - BigDecimal oners2 = rs.getObject(2, BigDecimal.class); - BigDecimal oners3 = rs.getObject(3, BigDecimal.class); - BigDecimal oners4 = rs.getObject(4, BigDecimal.class); - - assertEquals(oners1, onebigdec16); - assertEquals(oners2, onebigdec32); - assertEquals(oners3, onebigdec64); - assertEquals(oners4, onebigdec128); - } - } - } - - public static void test_sv_appender_decimal_wrong_scale() throws Exception { - try (DuckDBConnection conn = DriverManager.getConnection("jdbc:duckdb:").unwrap(DuckDBConnection.class); - Statement stmt = conn.createStatement()) { - - stmt.execute( - "CREATE TABLE decimals (id INT4, a DECIMAL(4,2), b DECIMAL(8,4), c DECIMAL(18,6), d DECIMAL(38,20))"); - - assertThrows(() -> { - try (DuckDBSingleValueAppender appender = - conn.createSingleValueAppender(DuckDBConnection.DEFAULT_SCHEMA, "decimals")) { - appender.append(1); - appender.beginRow(); - appender.appendBigDecimal(new BigDecimal("121.14").setScale(2)); - } - }, SQLException.class); - - assertThrows(() -> { - try (DuckDBSingleValueAppender appender = - conn.createSingleValueAppender(DuckDBConnection.DEFAULT_SCHEMA, "decimals")) { - appender.beginRow(); - appender.append(2); - appender.appendBigDecimal(new BigDecimal("21.1").setScale(2)); - appender.appendBigDecimal(new BigDecimal("12111.1411").setScale(4)); - } - }, SQLException.class); - - assertThrows(() -> { - try (DuckDBSingleValueAppender appender = - conn.createSingleValueAppender(DuckDBConnection.DEFAULT_SCHEMA, "decimals")) { - appender.beginRow(); - appender.append(3); - appender.appendBigDecimal(new BigDecimal("21.1").setScale(2)); - appender.appendBigDecimal(new BigDecimal("21.1").setScale(4)); - appender.appendBigDecimal(new BigDecimal("1234567890123.123456").setScale(6)); - } - }, SQLException.class); - } - } - - public static void test_sv_appender_int_string() throws Exception { - try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); - Statement stmt = conn.createStatement()) { - - stmt.execute("CREATE TABLE data (a INTEGER, s VARCHAR)"); - - try (DuckDBSingleValueAppender appender = - conn.createSingleValueAppender(DuckDBConnection.DEFAULT_SCHEMA, "data")) { - for (int i = 0; i < 1000; i++) { - appender.beginRow(); - appender.append(i); - appender.append("str " + i); - appender.endRow(); - } - appender.flush(); - } - - try (ResultSet rs = stmt.executeQuery("SELECT max(a), min(s) FROM data")) { - assertFalse(rs.isClosed()); - - assertTrue(rs.next()); - int resA = rs.getInt(1); - assertEquals(resA, 999); - String resB = rs.getString(2); - assertEquals(resB, "str 0"); - } - } - } - - public static void test_sv_appender_string_with_emoji() throws Exception { - try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); - Statement stmt = conn.createStatement()) { - stmt.execute("CREATE TABLE data (id INTEGER, str_value VARCHAR(10))"); - String expectedValue = "ä­”\uD86D\uDF7C🔥\uD83D\uDE1C"; - - try (DuckDBSingleValueAppender appender = - conn.createSingleValueAppender(DuckDBConnection.DEFAULT_SCHEMA, "data")) { - appender.beginRow(); - appender.append(1); - appender.append(expectedValue); - appender.endRow(); - } - - try (ResultSet rs = stmt.executeQuery("SELECT str_value FROM data ORDER BY id")) { - assertFalse(rs.isClosed()); - - assertTrue(rs.next()); - String row1 = rs.getString(1); - assertEquals(row1, expectedValue); - - assertFalse(rs.next()); - } - } - } - - public static void test_sv_appender_table_does_not_exist() throws Exception { - try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class)) { - assertThrows( - () -> { conn.createSingleValueAppender(DuckDBConnection.DEFAULT_SCHEMA, "data"); }, SQLException.class); - } - } - - public static void test_sv_appender_table_deleted() throws Exception { - try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); - Statement stmt = conn.createStatement()) { - - stmt.execute("CREATE TABLE data (a INTEGER)"); - DuckDBSingleValueAppender appender = - conn.createSingleValueAppender(DuckDBConnection.DEFAULT_SCHEMA, "data"); - appender.beginRow(); - appender.append(1); - appender.endRow(); - - stmt.execute("DROP TABLE data"); - - appender.beginRow(); - appender.append(2); - appender.endRow(); - - assertThrows(appender::flush, SQLException.class); - } - } - - public static void test_sv_appender_append_too_many_columns() throws Exception { - try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); - Statement stmt = conn.createStatement()) { - - stmt.execute("CREATE TABLE data (a INTEGER)"); - - assertThrows(() -> { - DuckDBSingleValueAppender appender = - conn.createSingleValueAppender(DuckDBConnection.DEFAULT_SCHEMA, "data"); - appender.beginRow(); - appender.append(1); - appender.append(2); - appender.flush(); - }, SQLException.class); - } - } - - public static void test_sv_appender_append_too_few_columns() throws Exception { - try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); - Statement stmt = conn.createStatement()) { - - stmt.execute("CREATE TABLE data (a INTEGER, b INTEGER)"); - try (DuckDBSingleValueAppender appender = - conn.createSingleValueAppender(DuckDBConnection.DEFAULT_SCHEMA, "data")) { - assertThrows(() -> { - appender.beginRow(); - appender.append(1); - appender.endRow(); - }, SQLException.class); - } - } - } - - public static void test_sv_appender_type_mismatch() throws Exception { - try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); - Statement stmt = conn.createStatement()) { - - stmt.execute("CREATE TABLE data (a INTEGER)"); - try (DuckDBSingleValueAppender appender = - conn.createSingleValueAppender(DuckDBConnection.DEFAULT_SCHEMA, "data")) { - assertThrows(() -> { - appender.beginRow(); - appender.append("str"); - }, SQLException.class); - } - } - } - - public static void test_sv_appender_null_integer() throws Exception { - try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); - Statement stmt = conn.createStatement()) { - - stmt.execute("CREATE TABLE data (a INTEGER)"); - - try (DuckDBSingleValueAppender appender = - conn.createSingleValueAppender(DuckDBConnection.DEFAULT_SCHEMA, "data")) { - appender.beginRow(); - appender.append((String) null); - appender.endRow(); - appender.flush(); - } - - try (ResultSet results = stmt.executeQuery("SELECT * FROM data")) { - assertTrue(results.next()); - // java.sql.ResultSet.getInt(int) returns 0 if the value is NULL - assertEquals(0, results.getInt(1)); - assertTrue(results.wasNull()); - } - } - } - - public static void test_sv_appender_number_wrappers() throws Exception { - try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); - Statement stmt = conn.createStatement()) { - - // int8, int4, int2, int1, float8, float4 - stmt.execute("CREATE TABLE numbers (a BIGINT, b INTEGER, c SMALLINT, d TINYINT, e DOUBLE, f FLOAT)"); - try (DuckDBSingleValueAppender appender = - conn.createSingleValueAppender(DuckDBConnection.DEFAULT_SCHEMA, "numbers")) { - for (int i = 0; i < 50; i++) { - appender.beginRow(); - appender.append(Long.valueOf(Long.MAX_VALUE - i)); - appender.append(Integer.valueOf(Integer.MAX_VALUE - i)); - appender.append(Short.valueOf((short) (Short.MAX_VALUE - i))); - appender.append(Byte.valueOf((byte) (Byte.MAX_VALUE - i))); - appender.append(Double.valueOf(i)); - appender.append(Float.valueOf(i)); - appender.endRow(); - } - appender.flush(); - } - - try (ResultSet rs = - stmt.executeQuery("SELECT max(a), max(b), max(c), max(d), max(e), max(f) FROM numbers")) { - assertFalse(rs.isClosed()); - assertTrue(rs.next()); - - long resA = rs.getLong(1); - assertEquals(resA, Long.MAX_VALUE); - - int resB = rs.getInt(2); - assertEquals(resB, Integer.MAX_VALUE); - - short resC = rs.getShort(3); - assertEquals(resC, Short.MAX_VALUE); - - byte resD = rs.getByte(4); - assertEquals(resD, Byte.MAX_VALUE); - - double resE = rs.getDouble(5); - assertEquals(resE, 49.0d); - - float resF = rs.getFloat(6); - assertEquals(resF, 49.0f); - } - } - } - - public static void test_sv_appender_append_null_varchar() throws Exception { - try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); - Statement stmt = conn.createStatement()) { - - stmt.execute("CREATE TABLE data (a VARCHAR)"); - - try (DuckDBSingleValueAppender appender = - conn.createSingleValueAppender(DuckDBConnection.DEFAULT_SCHEMA, "data")) { - appender.beginRow(); - appender.append((String) null); - appender.endRow(); - appender.flush(); - } - - try (ResultSet results = stmt.executeQuery("SELECT * FROM data")) { - assertTrue(results.next()); - assertNull(results.getString(1)); - assertTrue(results.wasNull()); - } - } - } - - public static void test_sv_appender_append_null_blob() throws Exception { - try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); - Statement stmt = conn.createStatement()) { - - stmt.execute("CREATE TABLE data (a BLOB)"); - - try (DuckDBSingleValueAppender appender = - conn.createSingleValueAppender(DuckDBConnection.DEFAULT_SCHEMA, "data")) { - appender.beginRow(); - appender.append((String) null); - appender.endRow(); - appender.flush(); - } - - try (ResultSet results = stmt.executeQuery("SELECT * FROM data")) { - assertTrue(results.next()); - assertNull(results.getString(1)); - assertTrue(results.wasNull()); - } - } - } - - public static void test_sv_appender_roundtrip_blob() throws Exception { - try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); - Statement stmt = conn.createStatement()) { - - SecureRandom random = SecureRandom.getInstanceStrong(); - byte[] data = new byte[512]; - random.nextBytes(data); - - stmt.execute("CREATE TABLE data (a BLOB)"); - - try (DuckDBSingleValueAppender appender = - conn.createSingleValueAppender(DuckDBConnection.DEFAULT_SCHEMA, "data")) { - appender.beginRow(); - appender.append(data); - appender.endRow(); - appender.flush(); - } - - try (ResultSet results = stmt.executeQuery("SELECT * FROM data")) { - assertTrue(results.next()); - - Blob resultBlob = results.getBlob(1); - byte[] resultBytes = resultBlob.getBytes(1, (int) resultBlob.length()); - assertTrue(Arrays.equals(resultBytes, data), "byte[] data is round tripped untouched"); - } - } - } -} diff --git a/src/test/java/org/duckdb/TestWideDecimal.java b/src/test/java/org/duckdb/TestWideDecimal.java index 28f12b6ea..65b474c27 100644 --- a/src/test/java/org/duckdb/TestWideDecimal.java +++ b/src/test/java/org/duckdb/TestWideDecimal.java @@ -418,12 +418,8 @@ public static void test_wide_decimal_bind_max_decimal_width() throws Exception { stmt.execute("SET max_decimal_width = 50"); stmt.execute("CREATE TABLE wide (d DECIMAL(50,3))"); stmt.execute("SET max_decimal_width = 38"); - try (DuckDBSingleValueAppender appender = - conn.unwrap(DuckDBConnection.class) - .createSingleValueAppender(DuckDBConnection.DEFAULT_SCHEMA, "wide")) { - appender.beginRow(); - appender.appendBigDecimal(value); - appender.endRow(); + try (DuckDBAppender appender = conn.unwrap(DuckDBConnection.class).createAppender("wide")) { + appender.beginRow().append(value).endRow(); appender.flush(); } try (ResultSet rs = stmt.executeQuery("SELECT d FROM wide")) { @@ -724,30 +720,6 @@ public static void test_wide_decimal_appender_nested() throws Exception { } } - public static void test_wide_decimal_single_value_appender() throws Exception { - try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); - Statement stmt = conn.createStatement()) { - stmt.execute("CREATE TABLE wide (id INTEGER, a DECIMAL(39,2), b DECIMAL(300,10))"); - BigDecimal a = fullWidthValue(39, 2).negate(); - BigDecimal b = fullWidthValue(300, 10); - try (DuckDBSingleValueAppender appender = - conn.createSingleValueAppender(DuckDBConnection.DEFAULT_SCHEMA, "wide")) { - appender.beginRow(); - appender.append(1); - appender.appendBigDecimal(a); - appender.appendBigDecimal(b); - appender.endRow(); - appender.flush(); - } - try (ResultSet rs = stmt.executeQuery("SELECT a, b FROM wide")) { - assertTrue(rs.next()); - assertEquals(rs.getBigDecimal(1), a); - assertEquals(rs.getBigDecimal(2), b); - assertFalse(rs.next()); - } - } - } - public static void test_wide_decimal_scalar_function() throws Exception { for (int width : WIDTHS) { int scale = 3; From f8f95b18b4a37b0fae59a22915bb9e2729a8920f Mon Sep 17 00:00:00 2001 From: Alex Kasko Date: Wed, 2 Dec 2026 11:22:54 +0000 Subject: [PATCH 12/21] Add the JNI signature comments to the new entry points Every function that implements a JNI entry point of the C API v2 bindings and of the Arrow export gets the comment with its class, method and signature, the same as the javac-generated header has and as the other entry points have. --- src/jni/arrow_export.cpp | 25 ++ src/jni/bindings_v2.cpp | 542 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 567 insertions(+) diff --git a/src/jni/arrow_export.cpp b/src/jni/arrow_export.cpp index 3994eb5bd..0b586e850 100644 --- a/src/jni/arrow_export.cpp +++ b/src/jni/arrow_export.cpp @@ -135,6 +135,11 @@ void stream_release(ArrowArrayStream *stream) { } // namespace +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_arrow_export_stream + * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;J)J + */ // Executes the statement (that reads the collection) on the helper connection with the Arrow result format and returns // the address of the stream of the result. The stream takes the ownership of the helper connection, of the statement // and of the collection when the call succeeds, conn is the connection that the stream is closed with. @@ -191,6 +196,11 @@ namespace { void close_registered_streams(duckdb_v2_connection_handle conn); } // namespace +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_arrow_close_streams + * Signature: (Ljava/nio/ByteBuffer;)V + */ // Closes the streams of the connection that are not released by their consumers yet JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1close_1streams(JNIEnv *env, jclass, jobject conn_buf) { @@ -512,6 +522,11 @@ void close_registered_streams(duckdb_v2_connection_handle conn) { } // namespace +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_arrow_register_scan_function + * Signature: (Ljava/nio/ByteBuffer;)V + */ // Registers the table function that scans the registered streams JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1scan_1function(JNIEnv *env, jclass, jobject conn_buf) { @@ -549,6 +564,11 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1registe } } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_arrow_register_stream + * Signature: (Ljava/nio/ByteBuffer;J)J + */ // Moves the stream out of the Java-owned struct and registers it with the connection, returns its id JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1stream(JNIEnv *env, jclass, jobject conn_buf, @@ -574,6 +594,11 @@ JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1regist return static_cast(state->id); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_arrow_release_stream + * Signature: (J)V + */ // Releases the registered stream, if it is not consumed or released yet JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1release_1stream(JNIEnv *, jclass, jlong id) { auto state = registered_streams().Remove(static_cast(id)); diff --git a/src/jni/bindings_v2.cpp b/src/jni/bindings_v2.cpp index c1b710156..6634924fc 100644 --- a/src/jni/bindings_v2.cpp +++ b/src/jni/bindings_v2.cpp @@ -57,12 +57,22 @@ static void throw_v2_error(JNIEnv *env, const v2_error &err) { /* --- connection --- */ +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_connection_interrupt + * Signature: (Ljava/nio/ByteBuffer;)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1interrupt(JNIEnv *env, jclass, jobject conn_buf) { CHECK_BUF(conn, conn_buf, duckdb_v2_connection_handle, "connection"); CALL_V2(duckdb_v2_connection_interrupt(conn, ERR_OUT), ); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_connection_progress_get + * Signature: (Ljava/nio/ByteBuffer;)Lorg/duckdb/QueryProgress; + */ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1progress_1get(JNIEnv *env, jclass, jobject conn_buf) { CHECK_BUF_RET(conn, conn_buf, duckdb_v2_connection_handle, "connection", nullptr); @@ -76,6 +86,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_ /* --- parsing --- */ +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_parse_sql + * Signature: (Ljava/nio/ByteBuffer;[B)Ljava/nio/ByteBuffer; + */ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1parse_1sql(JNIEnv *env, jclass, jobject conn_buf, jbyteArray sql_j) { CHECK_BUF_RET(conn, conn_buf, duckdb_v2_connection_handle, "connection", nullptr); @@ -88,6 +103,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1parse_1sql( return make_ptr_buf(env, it); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_statement_iterator_next + * Signature: (Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ // Returns null when there are no more statements JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1iterator_1next(JNIEnv *env, jclass, jobject it_buf) { @@ -97,18 +117,33 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1 return make_ptr_buf(env, statement); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_statement_iterator_destroy + * Signature: (Ljava/nio/ByteBuffer;)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1iterator_1destroy(JNIEnv *env, jclass, jobject it_buf) { CHECK_BUF(it, it_buf, duckdb_v2_statement_iterator_handle, "statement iterator"); duckdb_v2_statement_iterator_destroy(&it); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_sql_statement_destroy + * Signature: (Ljava/nio/ByteBuffer;)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement_1destroy(JNIEnv *env, jclass, jobject st_buf) { CHECK_BUF(st, st_buf, duckdb_v2_sql_statement_handle, "statement"); duckdb_v2_sql_statement_destroy(&st); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_sql_statement_get_type + * Signature: (Ljava/nio/ByteBuffer;)I + */ JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement_1get_1type(JNIEnv *env, jclass, jobject st_buf) { CHECK_BUF_RET(st, st_buf, duckdb_v2_sql_statement_handle, "statement", 0); @@ -117,6 +152,11 @@ JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement return static_cast(type); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_sql_statement_get_parameter_count + * Signature: (Ljava/nio/ByteBuffer;)J + */ JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement_1get_1parameter_1count(JNIEnv *env, jclass, jobject st_buf) { CHECK_BUF_RET(st, st_buf, duckdb_v2_sql_statement_handle, "statement", 0); @@ -127,6 +167,11 @@ Java_org_duckdb_DuckDBBindings_duckdb_1v2_1sql_1statement_1get_1parameter_1count /* --- prepared statements --- */ +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_prepared_statement_create + * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;Z)Ljava/nio/ByteBuffer; + */ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1prepared_1statement_1create( JNIEnv *env, jclass, jobject conn_buf, jobject st_buf, jboolean require_cacheable) { CHECK_BUF_RET(conn, conn_buf, duckdb_v2_connection_handle, "connection", nullptr); @@ -136,6 +181,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1prepared_1s return make_ptr_buf(env, prepared); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_prepared_statement_destroy + * Signature: (Ljava/nio/ByteBuffer;)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1prepared_1statement_1destroy(JNIEnv *env, jclass, jobject prepared_buf) { CHECK_BUF(prepared, prepared_buf, duckdb_v2_prepared_statement_handle, "prepared statement"); @@ -160,6 +210,11 @@ static bool read_values(JNIEnv *env, jobjectArray values_j, std::vector(type); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_result_get_statement_type + * Signature: (Ljava/nio/ByteBuffer;)I + */ JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1get_1statement_1type(JNIEnv *env, jclass, jobject result_buf) { CHECK_BUF_RET(result, result_buf, duckdb_v2_result_handle, "result", 0); @@ -296,12 +401,22 @@ JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1get_1s return static_cast(type); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_result_wait + * Signature: (Ljava/nio/ByteBuffer;)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1wait(JNIEnv *env, jclass, jobject result_buf) { CHECK_BUF(result, result_buf, duckdb_v2_result_handle, "result"); CALL_V2(duckdb_v2_result_wait(result, ERR_OUT), ); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_result_drain + * Signature: (Ljava/nio/ByteBuffer;)J + */ JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1drain(JNIEnv *env, jclass, jobject result_buf) { CHECK_BUF_RET(result, result_buf, duckdb_v2_result_handle, "result", 0); @@ -310,6 +425,11 @@ JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1drain return uint64_to_jlong(rows_changed); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_result_step + * Signature: (Ljava/nio/ByteBuffer;[I)Ljava/nio/ByteBuffer; + */ // Steps the result once, the status (DUCKDB_V2_RESULT_STEP_STATUS) is written to status_out[0], the returned chunk is // null unless the status is CHUNK JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1step(JNIEnv *env, jclass, @@ -324,6 +444,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1ste return make_data_chunk_buf(env, chunk); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_result_fetch_chunk + * Signature: (Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ // Returns null at the end of the result JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1fetch_1chunk(JNIEnv *env, jclass, jobject result_buf) { @@ -335,6 +460,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1result_1fet /* --- factory and values --- */ +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_connection_get_factory + * Signature: (Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ // The factory is borrowed from the connection JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1factory(JNIEnv *env, jclass, jobject conn_buf) { @@ -344,6 +474,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_ return make_ptr_buf(env, factory); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_factory_create_type_from_text + * Signature: (Ljava/nio/ByteBuffer;[B)Ljava/nio/ByteBuffer; + */ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1factory_1create_1type_1from_1text( JNIEnv *env, jclass, jobject factory_buf, jbyteArray text_j) { CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); @@ -356,6 +491,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1factory_1cr return make_logical_type_buf(env, type); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_destroy + * Signature: (Ljava/nio/ByteBuffer;)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1destroy(JNIEnv *env, jclass, jobject value_buf) { CHECK_BUF(value, value_buf, duckdb_v2_value_handle, "value"); @@ -370,31 +510,107 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1destroy return make_ptr_buf(env, value); \ } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_create_bool + * Signature: (Ljava/nio/ByteBuffer;Z)Ljava/nio/ByteBuffer; + */ VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1bool, jboolean, duckdb_v2_value_create_bool(factory, in_value == JNI_TRUE, &value, ERR_OUT)) + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_create_tinyint + * Signature: (Ljava/nio/ByteBuffer;B)Ljava/nio/ByteBuffer; + */ VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1tinyint, jbyte, duckdb_v2_value_create_tinyint(factory, in_value, &value, ERR_OUT)) + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_create_smallint + * Signature: (Ljava/nio/ByteBuffer;S)Ljava/nio/ByteBuffer; + */ VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1smallint, jshort, duckdb_v2_value_create_smallint(factory, in_value, &value, ERR_OUT)) + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_create_int + * Signature: (Ljava/nio/ByteBuffer;I)Ljava/nio/ByteBuffer; + */ VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1int, jint, duckdb_v2_value_create_int(factory, in_value, &value, ERR_OUT)) + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_create_bigint + * Signature: (Ljava/nio/ByteBuffer;J)Ljava/nio/ByteBuffer; + */ VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1bigint, jlong, duckdb_v2_value_create_bigint(factory, in_value, &value, ERR_OUT)) + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_create_float + * Signature: (Ljava/nio/ByteBuffer;F)Ljava/nio/ByteBuffer; + */ VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1float, jfloat, duckdb_v2_value_create_float(factory, in_value, &value, ERR_OUT)) + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_create_double + * Signature: (Ljava/nio/ByteBuffer;D)Ljava/nio/ByteBuffer; + */ VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1double, jdouble, duckdb_v2_value_create_double(factory, in_value, &value, ERR_OUT)) + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_create_date + * Signature: (Ljava/nio/ByteBuffer;I)Ljava/nio/ByteBuffer; + */ VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1date, jint, duckdb_v2_value_create_date(factory, in_value, &value, ERR_OUT)) + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_create_time + * Signature: (Ljava/nio/ByteBuffer;J)Ljava/nio/ByteBuffer; + */ VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1time, jlong, duckdb_v2_value_create_time(factory, in_value, &value, ERR_OUT)) + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_create_timestamp + * Signature: (Ljava/nio/ByteBuffer;J)Ljava/nio/ByteBuffer; + */ VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp, jlong, duckdb_v2_value_create_timestamp(factory, in_value, &value, ERR_OUT)) + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_create_timestamp_ns + * Signature: (Ljava/nio/ByteBuffer;J)Ljava/nio/ByteBuffer; + */ VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp_1ns, jlong, duckdb_v2_value_create_timestamp_ns(factory, in_value, &value, ERR_OUT)) + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_create_timestamp_tz + * Signature: (Ljava/nio/ByteBuffer;J)Ljava/nio/ByteBuffer; + */ VALUE_CREATE_SCALAR(Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1timestamp_1tz, jlong, duckdb_v2_value_create_timestamp_tz(factory, in_value, &value, ERR_OUT)) +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_create_null + * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1null(JNIEnv *env, jclass, jobject factory_buf, jobject type_buf) { @@ -408,6 +624,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1crea return make_ptr_buf(env, value); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_create_hugeint + * Signature: (Ljava/nio/ByteBuffer;JJ)Ljava/nio/ByteBuffer; + */ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1hugeint(JNIEnv *env, jclass, jobject factory_buf, jlong lower, jlong upper) { @@ -418,6 +639,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1crea return make_ptr_buf(env, value); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_create_uuid + * Signature: (Ljava/nio/ByteBuffer;JJ)Ljava/nio/ByteBuffer; + */ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1uuid(JNIEnv *env, jclass, jobject factory_buf, jlong lower, jlong upper) { @@ -428,6 +654,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1crea return make_ptr_buf(env, value); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_create_decimal + * Signature: (Ljava/nio/ByteBuffer;JJII)Ljava/nio/ByteBuffer; + */ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1decimal(JNIEnv *env, jclass, jobject factory_buf, jlong lower, jlong upper, @@ -441,6 +672,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1crea return make_ptr_buf(env, value); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_create_varchar + * Signature: (Ljava/nio/ByteBuffer;[B)Ljava/nio/ByteBuffer; + */ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1varchar(JNIEnv *env, jclass, jobject factory_buf, jbyteArray in_value_j) { @@ -454,6 +690,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1crea return make_ptr_buf(env, value); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_create_blob + * Signature: (Ljava/nio/ByteBuffer;[B)Ljava/nio/ByteBuffer; + */ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1blob(JNIEnv *env, jclass, jobject factory_buf, jbyteArray in_value_j) { @@ -467,6 +708,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1crea return make_ptr_buf(env, value); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_create_list + * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;[Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ // The child values are borrowed for the call JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1list(JNIEnv *env, jclass, jobject factory_buf, @@ -486,6 +732,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1crea return make_ptr_buf(env, value); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_create_struct + * Signature: (Ljava/nio/ByteBuffer;[[B[Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1struct(JNIEnv *env, jclass, jobject factory_buf, jobjectArray names_j, @@ -522,6 +773,12 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1crea return make_ptr_buf(env, value); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_create_map + * Signature: + * (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;[Ljava/nio/ByteBuffer;[Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1map( JNIEnv *env, jclass, jobject factory_buf, jobject key_type_buf, jobject value_type_buf, jobjectArray keys_j, jobjectArray values_j) { @@ -550,6 +807,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1crea return make_ptr_buf(env, value); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_create_type + * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1create_1type(JNIEnv *env, jclass, jobject factory_buf, jobject type_buf) { @@ -563,6 +825,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1crea return make_ptr_buf(env, value); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_to_string + * Signature: (Ljava/nio/ByteBuffer;)[B + */ JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1to_1string(JNIEnv *env, jclass, jobject value_buf) { CHECK_BUF_RET(value, value_buf, duckdb_v2_value_handle, "value", nullptr); @@ -575,12 +842,22 @@ JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1t /* --- vectors --- */ +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_vector_flatten + * Signature: (Ljava/nio/ByteBuffer;)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1flatten(JNIEnv *env, jclass, jobject vector_buf) { CHECK_BUF(vector, vector_buf, duckdb_v2_vector_handle, "vector"); CALL_V2(duckdb_v2_vector_flatten(vector, ERR_OUT), ); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_vector_get_value + * Signature: (Ljava/nio/ByteBuffer;J)Ljava/nio/ByteBuffer; + */ // The returned value is owned by the caller JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1value(JNIEnv *env, jclass, jobject vector_buf, jlong row) { @@ -596,6 +873,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get /* --- logical type parameters --- */ +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_logical_type_get_param_count + * Signature: (Ljava/nio/ByteBuffer;)J + */ JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1get_1param_1count(JNIEnv *env, jclass, jobject type_buf) { auto type = logical_type_buf_to_logical_type(env, type_buf); @@ -607,6 +889,11 @@ JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type return uint64_to_jlong(count); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_logical_type_get_param_value + * Signature: (Ljava/nio/ByteBuffer;J)Ljava/nio/ByteBuffer; + */ // The returned value is owned by the caller JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1get_1param_1value(JNIEnv *env, jclass, @@ -627,6 +914,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1ty return make_ptr_buf(env, value); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_logical_type_get_param_name + * Signature: (Ljava/nio/ByteBuffer;J)[B + */ // Returns null for a positional parameter JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1get_1param_1name( JNIEnv *env, jclass, jobject type_buf, jlong index) { @@ -649,6 +941,11 @@ JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_ return make_jbyteArray(env, name, name_len); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_get_type + * Signature: (Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ // Unwraps the type of a TYPE value, the returned type is owned by the caller JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1get_1type(JNIEnv *env, jclass, jobject value_buf) { @@ -660,6 +957,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1get_ /* --- configuration --- */ +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_connection_get_config + * Signature: (Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ // The returned config is borrowed from the connection JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1config(JNIEnv *env, jclass, jobject conn_buf) { @@ -669,6 +971,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_ return make_ptr_buf(env, config); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_config_get_option_value + * Signature: (Ljava/nio/ByteBuffer;[B)Ljava/nio/ByteBuffer; + */ // The returned value is owned by the caller JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1value(JNIEnv *env, jclass, jobject config_buf, @@ -686,6 +993,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get /* --- transitional --- */ +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_chunked_result_create + * Signature: (Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ // Wraps the result into a chunked result of the bindings API, the holder takes the ownership of the result JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1chunked_1result_1create(JNIEnv *env, jclass, jobject result_buf) { @@ -701,6 +1013,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1chunked_1re /* --- variants --- */ +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_variant_to_value + * Signature: (Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ // The returned value is owned by the caller JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1variant_1to_1value(JNIEnv *env, jclass, jobject value_buf) { @@ -730,6 +1047,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1cast return make_ptr_buf(env, out_value); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_value_get_logical_type + * Signature: (Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ // The returned type is owned by the caller JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1get_1logical_1type(JNIEnv *env, jclass, jobject value_buf) { @@ -739,6 +1061,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1get_ return make_logical_type_buf(env, type); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_vector_set_value + * Signature: (Ljava/nio/ByteBuffer;JLjava/nio/ByteBuffer;)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1set_1value(JNIEnv *env, jclass, jobject vector_buf, jlong row, jobject value_buf) { @@ -751,6 +1078,11 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1set_1v CALL_V2(duckdb_v2_vector_set_value(vector, idx, value, ERR_OUT), ); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_vector_set_size + * Signature: (Ljava/nio/ByteBuffer;J)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1set_1size(JNIEnv *env, jclass, jobject vector_buf, jlong size) { CHECK_BUF(vector, vector_buf, duckdb_v2_vector_handle, "vector"); @@ -763,6 +1095,11 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1set_1s /* --- appending --- */ +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_logical_type_copy + * Signature: (Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ // The returned type is owned by the caller JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1type_1copy(JNIEnv *env, jclass, jobject type_buf) { @@ -775,6 +1112,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1logical_1ty return make_logical_type_buf(env, copy); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_vector_get_size + * Signature: (Ljava/nio/ByteBuffer;)J + */ JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1size(JNIEnv *env, jclass, jobject vector_buf) { CHECK_BUF_RET(vector, vector_buf, duckdb_v2_vector_handle, "vector", 0); @@ -783,6 +1125,11 @@ JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1 return uint64_to_jlong(size); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_column_data_collection_create + * Signature: (Ljava/nio/ByteBuffer;[Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1create( JNIEnv *env, jclass, jobject factory_buf, jobjectArray types_j) { CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); @@ -803,18 +1150,33 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1dat return make_ptr_buf(env, collection); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_column_data_collection_destroy + * Signature: (Ljava/nio/ByteBuffer;)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1destroy( JNIEnv *env, jclass, jobject collection_buf) { CHECK_BUF(collection, collection_buf, duckdb_v2_column_data_collection_handle, "collection"); duckdb_v2_column_data_collection_destroy(&collection); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_column_data_collection_clear + * Signature: (Ljava/nio/ByteBuffer;)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1clear( JNIEnv *env, jclass, jobject collection_buf) { CHECK_BUF(collection, collection_buf, duckdb_v2_column_data_collection_handle, "collection"); CALL_V2(duckdb_v2_column_data_collection_clear(collection, ERR_OUT), ); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_column_data_collection_row_count + * Signature: (Ljava/nio/ByteBuffer;)J + */ JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1row_1count( JNIEnv *env, jclass, jobject collection_buf) { CHECK_BUF_RET(collection, collection_buf, duckdb_v2_column_data_collection_handle, "collection", 0); @@ -823,6 +1185,11 @@ JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_ return uint64_to_jlong(count); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_column_data_collection_append_state_create + * Signature: (Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1append_1state_1create( JNIEnv *env, jclass, jobject collection_buf) { CHECK_BUF_RET(collection, collection_buf, duckdb_v2_column_data_collection_handle, "collection", nullptr); @@ -831,12 +1198,22 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1dat return make_ptr_buf(env, state); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_column_data_collection_append_state_destroy + * Signature: (Ljava/nio/ByteBuffer;)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1append_1state_1destroy( JNIEnv *env, jclass, jobject state_buf) { CHECK_BUF(state, state_buf, duckdb_v2_column_data_collection_append_state_handle, "append state"); duckdb_v2_column_data_collection_append_state_destroy(&state); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_column_data_collection_append + * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)V + */ // The chunk is borrowed for the call JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1collection_1append( JNIEnv *env, jclass, jobject collection_buf, jobject state_buf, jobject chunk_buf) { @@ -849,6 +1226,11 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1data_1 CALL_V2(duckdb_v2_column_data_collection_append(collection, state, chunk, ERR_OUT), ); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_statement_add_collection + * Signature: (Ljava/nio/ByteBuffer;[BLjava/nio/ByteBuffer;[[B)V + */ // Binds the collection to the statement under the name, the collection must outlive the statement executions JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1add_1collection( JNIEnv *env, jclass, jobject st_buf, jbyteArray name_j, jobject collection_buf, jobjectArray names_j) { @@ -880,12 +1262,22 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1statement_1add /* --- environments, instances and connections --- */ +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_environment_create + * Signature: ()Ljava/nio/ByteBuffer; + */ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1environment_1create(JNIEnv *env, jclass) { duckdb_v2_environment_handle environment = nullptr; CALL_V2(duckdb_v2_environment_create(&environment, ERR_OUT), nullptr); return make_ptr_buf(env, environment); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_environment_destroy + * Signature: (Ljava/nio/ByteBuffer;)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1environment_1destroy(JNIEnv *env, jclass, jobject env_buf) { CHECK_BUF(environment, env_buf, duckdb_v2_environment_handle, "environment"); @@ -926,6 +1318,11 @@ struct OptionPointers { } }; +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_instance_create_with_options + * Signature: (Ljava/nio/ByteBuffer;[[B[[B)Ljava/nio/ByteBuffer; + */ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1create_1with_1options( JNIEnv *env, jclass, jobject env_buf, jobjectArray names_j, jobjectArray values_j) { CHECK_BUF_RET(environment, env_buf, duckdb_v2_environment_handle, "environment", nullptr); @@ -982,6 +1379,11 @@ static void instance_init_trampoline(duckdb_v2_instance_handle instance, void *u } } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_instance_open_shared + * Signature: (Ljava/nio/ByteBuffer;[B[[B[[BLorg/duckdb/DuckDBBindings/InstanceInit;)Ljava/nio/ByteBuffer; + */ // Opens the shared instance of the path, the initializer is called with the instance when it is created JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1open_1shared( JNIEnv *env, jclass, jobject env_buf, jbyteArray path_j, jobjectArray names_j, jobjectArray values_j, @@ -1011,6 +1413,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1o return make_ptr_buf(env, instance); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_instance_attach + * Signature: (Ljava/nio/ByteBuffer;[B[BZ)V + */ // The name can be null JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1attach(JNIEnv *env, jclass, jobject instance_buf, @@ -1029,12 +1436,22 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1atta path.size(), nullptr, make_default == JNI_TRUE, ERR_OUT), ); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_instance_destroy + * Signature: (Ljava/nio/ByteBuffer;)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1destroy(JNIEnv *env, jclass, jobject instance_buf) { CHECK_BUF(instance, instance_buf, duckdb_v2_instance_handle, "instance"); duckdb_v2_instance_destroy(&instance); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_instance_get_config + * Signature: (Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ // The returned config is borrowed from the instance JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1get_1config(JNIEnv *env, jclass, jobject instance_buf) { @@ -1044,6 +1461,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1g return make_ptr_buf(env, config); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_connection_create + * Signature: (Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1create(JNIEnv *env, jclass, jobject instance_buf) { CHECK_BUF_RET(instance, instance_buf, duckdb_v2_instance_handle, "instance", nullptr); @@ -1052,6 +1474,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_ return make_ptr_buf(env, conn); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_connection_destroy + * Signature: (Ljava/nio/ByteBuffer;)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1destroy(JNIEnv *env, jclass, jobject conn_buf) { CHECK_BUF(conn, conn_buf, duckdb_v2_connection_handle, "connection"); @@ -1060,6 +1487,11 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1de /* --- configuration --- */ +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_config_set_option_text + * Signature: (Ljava/nio/ByteBuffer;[B[BI)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1set_1option_1text( JNIEnv *env, jclass, jobject config_buf, jbyteArray name_j, jbyteArray value_j, jint scope) { CHECK_BUF(config, config_buf, duckdb_v2_config_handle, "config"); @@ -1072,6 +1504,11 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1set_1o static_cast(scope), ERR_OUT), ); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_config_set_option_value + * Signature: (Ljava/nio/ByteBuffer;[BLjava/nio/ByteBuffer;I)V + */ // The value is borrowed for the call JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1set_1option_1value( JNIEnv *env, jclass, jobject config_buf, jbyteArray name_j, jobject value_buf, jint scope) { @@ -1085,6 +1522,11 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1set_1o static_cast(scope), ERR_OUT), ); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_config_get_option_count + * Signature: (Ljava/nio/ByteBuffer;)J + */ JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1count(JNIEnv *env, jclass, jobject config_buf) { CHECK_BUF_RET(config, config_buf, duckdb_v2_config_handle, "config", 0); @@ -1093,6 +1535,11 @@ JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1 return uint64_to_jlong(count); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_config_get_option_by_index + * Signature: (Ljava/nio/ByteBuffer;J)Ljava/nio/ByteBuffer; + */ // The returned option is owned by the caller JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1by_1index(JNIEnv *env, jclass, jobject config_buf, @@ -1107,6 +1554,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get return make_ptr_buf(env, option); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_option_get_name + * Signature: (Ljava/nio/ByteBuffer;)[B + */ JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1option_1get_1name(JNIEnv *env, jclass, jobject option_buf) { CHECK_BUF_RET(option, option_buf, duckdb_v2_option_handle, "option", nullptr); @@ -1116,6 +1568,11 @@ JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1option_1 return make_jbyteArray(env, name, name_len); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_option_supports_scope + * Signature: (Ljava/nio/ByteBuffer;I)Z + */ JNIEXPORT jboolean JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1option_1supports_1scope(JNIEnv *env, jclass, jobject option_buf, jint scope) { @@ -1126,12 +1583,22 @@ JNIEXPORT jboolean JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1option_1su return supported ? JNI_TRUE : JNI_FALSE; } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_option_destroy + * Signature: (Ljava/nio/ByteBuffer;)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1option_1destroy(JNIEnv *env, jclass, jobject option_buf) { CHECK_BUF(option, option_buf, duckdb_v2_option_handle, "option"); duckdb_v2_option_destroy(&option); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_config_get_option_value_scoped + * Signature: (Ljava/nio/ByteBuffer;[B[I)Ljava/nio/ByteBuffer; + */ // Reads the option value, the scope that the value comes from is written to scope_out[0] when it is given JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1option_1value_1scoped( JNIEnv *env, jclass, jobject config_buf, jbyteArray name_j, jintArray scope_out) { @@ -1152,6 +1619,11 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get /* --- custom options --- */ +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_custom_option_create + * Signature: (Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1create(JNIEnv *env, jclass, jobject factory_buf) { CHECK_BUF_RET(factory, factory_buf, duckdb_v2_factory_handle, "factory", nullptr); @@ -1160,12 +1632,22 @@ JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1opt return make_ptr_buf(env, option); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_custom_option_destroy + * Signature: (Ljava/nio/ByteBuffer;)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1destroy(JNIEnv *env, jclass, jobject option_buf) { CHECK_BUF(option, option_buf, duckdb_v2_custom_option_handle, "custom option"); duckdb_v2_custom_option_destroy(&option); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_custom_option_set_name + * Signature: (Ljava/nio/ByteBuffer;[B)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1name(JNIEnv *env, jclass, jobject option_buf, jbyteArray name_j) { @@ -1177,6 +1659,11 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option CALL_V2(duckdb_v2_custom_option_set_name(option, name.data(), name.size(), ERR_OUT), ); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_custom_option_set_type + * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)V + */ // The type is borrowed for the call JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1type(JNIEnv *env, jclass, jobject option_buf, @@ -1189,6 +1676,11 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option CALL_V2(duckdb_v2_custom_option_set_type(option, type, ERR_OUT), ); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_custom_option_set_default_value + * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)V + */ // The value is borrowed for the call JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1default_1value( JNIEnv *env, jclass, jobject option_buf, jobject value_buf) { @@ -1197,6 +1689,11 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option CALL_V2(duckdb_v2_custom_option_set_default_value(option, value, ERR_OUT), ); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_custom_option_set_description + * Signature: (Ljava/nio/ByteBuffer;[B)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1description( JNIEnv *env, jclass, jobject option_buf, jbyteArray description_j) { CHECK_BUF(option, option_buf, duckdb_v2_custom_option_handle, "custom option"); @@ -1207,12 +1704,22 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option CALL_V2(duckdb_v2_custom_option_set_description(option, description.data(), description.size(), ERR_OUT), ); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_custom_option_set_default_scope + * Signature: (Ljava/nio/ByteBuffer;I)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1default_1scope( JNIEnv *env, jclass, jobject option_buf, jint scope) { CHECK_BUF(option, option_buf, duckdb_v2_custom_option_handle, "custom option"); CALL_V2(duckdb_v2_custom_option_set_default_scope(option, static_cast(scope), ERR_OUT), ); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_custom_option_set_supports_scope + * Signature: (Ljava/nio/ByteBuffer;IZ)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option_1set_1supports_1scope( JNIEnv *env, jclass, jobject option_buf, jint scope, jboolean supported) { CHECK_BUF(option, option_buf, duckdb_v2_custom_option_handle, "custom option"); @@ -1220,6 +1727,11 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1custom_1option supported == JNI_TRUE, ERR_OUT), ); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_connection_register_custom_option + * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)V + */ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1register_1custom_1option( JNIEnv *env, jclass, jobject conn_buf, jobject option_buf) { CHECK_BUF(conn, conn_buf, duckdb_v2_connection_handle, "connection"); @@ -1233,6 +1745,11 @@ static void text_sink(const char *text, idx_t text_length, void *user_data, duck static_cast(user_data)->assign(text, text_length); } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_connection_get_profiling_information + * Signature: (Ljava/nio/ByteBuffer;[B)[B + */ // The profiling information of the last query of the connection in the format ("" is the default one) JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1get_1profiling_1information( JNIEnv *env, jclass, jobject conn_buf, jbyteArray format_j) { @@ -1250,6 +1767,11 @@ JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connecti /* --- reading strings --- */ +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_vector_get_long_strings + * Signature: (Ljava/nio/ByteBuffer;[II[I)[B + */ // Copies the strings (or BLOBs) of the rows of the vector data, that do not fit into the 16 bytes of the entry, into // one array. The string of the i-th row is at [offsets_out[i], offsets_out[i + 1]) of the result. The short strings are // read from the data buffer on Java side, without any call. @@ -1299,6 +1821,11 @@ JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1 return res; } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_vector_cast + * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)V + */ // Casts the rows of the source vector to the type of the target vector, the target is replaced by the result JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1cast(JNIEnv *env, jclass, jobject factory_buf, jobject source_buf, jobject target_buf) { @@ -1311,6 +1838,11 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1cast(J /* --- bulk reads --- */ +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_schema_get_field_names + * Signature: (Ljava/nio/ByteBuffer;)[[B + */ // The names of all the fields of the schema JNIEXPORT jobjectArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1names(JNIEnv *env, jclass, jobject schema_buf) { @@ -1336,6 +1868,11 @@ Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1names(JNIEnv *env return res; } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_schema_get_field_type_ids + * Signature: (Ljava/nio/ByteBuffer;)[I + */ // The type IDs (of the C API v1) of all the fields of the schema JNIEXPORT jintArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1type_1ids(JNIEnv *env, jclass, jobject schema_buf) { @@ -1357,6 +1894,11 @@ Java_org_duckdb_DuckDBBindings_duckdb_1v2_1schema_1get_1field_1type_1ids(JNIEnv return res; } +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_config_get_bool_option + * Signature: (Ljava/nio/ByteBuffer;[B)I + */ // Reads a BOOLEAN option, returns 1 or 0, or -1 if the option is not set or is not a BOOLEAN JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1bool_1option(JNIEnv *env, jclass, jobject config_buf, From d6fad06cf6d56c5ed7b4873bf74fe051048d9015 Mon Sep 17 00:00:00 2001 From: Alex Kasko Date: Wed, 2 Dec 2026 11:26:34 +0000 Subject: [PATCH 13/21] Apply enable_external_access and lock_configuration after the runtime options 'allowed_directories' and 'allowed_paths' can only be set on a running instance, and DuckDB refuses to change them when the external access is disabled. The usual sandboxing setup, enable_external_access=false with allowed_directories, failed to connect: enable_external_access was a startup option and the allowed directories were set after it. When these options are given together, enable_external_access=false is applied after them when the instance is created. The same is done for lock_configuration, that refused all the options that are set after the startup (the allowed paths, the logging options, jdbc_stream_results). The options that are applied this way are not startup options, so they are not compared when a cached instance is shared. A connection that asks for these restrictions is refused, as before, when the existing instance does not have them. --- src/main/java/org/duckdb/DuckDBInstances.java | 144 +++++++++++++++-- src/test/java/org/duckdb/TestDuckDBJDBC.java | 149 ++++++++++++++++++ 2 files changed, 280 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/duckdb/DuckDBInstances.java b/src/main/java/org/duckdb/DuckDBInstances.java index 962422cc4..8d9ad65a6 100644 --- a/src/main/java/org/duckdb/DuckDBInstances.java +++ b/src/main/java/org/duckdb/DuckDBInstances.java @@ -28,6 +28,14 @@ private DuckDBInstances() { "enable_logging", "logging_level", "logging_mode", "logging_storage", "enabled_log_types", "disabled_log_types"}; + // The options that are refused by DuckDB once external access is disabled + private static final String[] ALLOWED_PATHS_OPTIONS = {"allowed_directories", "allowed_paths"}; + + // The options that restrict the changes of the other options. The order in which the properties are applied is + // not defined, so these options are applied after the options that are written when the instance is created. + private static final String ENABLE_EXTERNAL_ACCESS_OPTION = "enable_external_access"; + private static final String LOCK_CONFIGURATION_OPTION = "lock_configuration"; + private static final String MEMORY_PREFIX = ":memory:"; // The addresses of the instances that are not shared are even, of the shared ones are odd @@ -105,9 +113,9 @@ private static synchronized ByteBuffer defaultEnvironment() throws SQLException return defaultEnvironment; } - private static boolean isRuntimeOption(String name) { + private static boolean isOneOf(String name, String[] options) { String lower = name.toLowerCase(Locale.ROOT); - for (String option : RUNTIME_OPTIONS) { + for (String option : options) { if (option.equals(lower)) { return true; } @@ -115,6 +123,10 @@ private static boolean isRuntimeOption(String name) { return false; } + private static boolean isRuntimeOption(String name) { + return isOneOf(name, RUNTIME_OPTIONS); + } + private static String quoteListEntry(String entry) { return "'" + entry.replace("'", "''") + "'"; } @@ -194,17 +206,85 @@ private static void registerStreamResultsOption(ByteBuffer instance) throws SQLE } } - // The settings that cannot be given at startup are written when the instance is created - private static void initInstance(ByteBuffer instance, List runtimeOptions) throws SQLException { + // The value of a BOOLEAN option, converted from its text by the engine + private static boolean optionIsTrue(ByteBuffer instance, String[] option) throws SQLException { + ByteBuffer conn = duckdb_v2_connection_create(instance); + ByteBuffer type = null; + ByteBuffer text = null; + ByteBuffer value = null; + try { + ByteBuffer factory = duckdb_v2_connection_get_factory(conn); + type = duckdb_create_logical_type(CAPIType.DUCKDB_TYPE_BOOLEAN.typeId); + text = duckdb_v2_value_create_varchar(factory, option[1].getBytes(UTF_8)); + value = duckdb_v2_value_cast(factory, text, type); + return duckdb_get_bool(value); + } catch (SQLException e) { + throw failedToSetOption(option, e); + } finally { + if (value != null) { + duckdb_v2_value_destroy(value); + } + if (text != null) { + duckdb_v2_value_destroy(text); + } + if (type != null) { + duckdb_destroy_logical_type(type); + } + duckdb_v2_connection_destroy(conn); + } + } + + private static SQLException failedToSetOption(String[] option, SQLException e) { + return new SQLException("Failed to set configuration option \"" + option[0] + + "\", error: " + rawMessage(e.getMessage())); + } + + private static void setGlobalOption(ByteBuffer config, String[] option) throws SQLException { + try { + duckdb_v2_config_set_option_text(config, option[0].getBytes(UTF_8), option[1].getBytes(UTF_8), + SCOPE_GLOBAL); + } catch (SQLException e) { + throw failedToSetOption(option, e); + } + } + + /** + * The settings that cannot be given at startup are written when the instance is created, and the options that + * restrict the changes of the settings are applied after them. + */ + private static void initInstance(ByteBuffer instance, List runtimeOptions, + List restrictingOptions) throws SQLException { registerStreamResultsOption(instance); ByteBuffer config = duckdb_v2_instance_get_config(instance); for (String[] option : runtimeOptions) { - try { - duckdb_v2_config_set_option_text(config, option[0].getBytes(UTF_8), option[1].getBytes(UTF_8), - SCOPE_GLOBAL); - } catch (SQLException e) { - throw new SQLException("Failed to set configuration option \"" + option[0] + - "\", error: " + rawMessage(e.getMessage())); + setGlobalOption(config, option); + } + for (String[] option : restrictingOptions) { + // external access is enabled in a new instance and cannot be enabled again when the instance is running + if (ENABLE_EXTERNAL_ACCESS_OPTION.equalsIgnoreCase(option[0]) && optionIsTrue(instance, option)) { + continue; + } + setGlobalOption(config, option); + } + } + + /** + * The restricting options that are applied after the startup are not startup options, so they are not compared + * when an existing instance is shared: an instance that is less restricted than requested is refused here. + */ + private static void checkSharedInstance(ByteBuffer instance, List restrictingOptions) + throws SQLException { + ByteBuffer config = duckdb_v2_instance_get_config(instance); + for (String[] option : restrictingOptions) { + boolean requested = optionIsTrue(instance, option); + boolean restricts = ENABLE_EXTERNAL_ACCESS_OPTION.equalsIgnoreCase(option[0]) ? !requested : requested; + if (!restricts) { + continue; + } + boolean existing = duckdb_v2_config_get_bool_option(config, option[0].getBytes(UTF_8)) == 1; + if (existing != requested) { + throw new SQLException("Can't open a connection to same database file with a different " + + "configuration than existing connections"); } } } @@ -215,6 +295,10 @@ static Connected startup(String database, boolean readOnly, Properties props, bo List names = new ArrayList<>(); List values = new ArrayList<>(); List runtimeOptions = new ArrayList<>(); + List restrictingOptions = new ArrayList<>(); + String[] externalAccess = null; + String[] lockConfiguration = null; + boolean allowedPaths = false; names.add("duckdb_api"); values.add("java"); if (readOnly) { @@ -229,20 +313,54 @@ static Connected startup(String database, boolean readOnly, Properties props, bo } if (JDBC_STREAM_RESULTS_OPTION.equals(key) || isRuntimeOption(key)) { runtimeOptions.add(new String[] {key, value}); + allowedPaths |= isOneOf(key, ALLOWED_PATHS_OPTIONS); + } else if (ENABLE_EXTERNAL_ACCESS_OPTION.equalsIgnoreCase(key)) { + externalAccess = new String[] {key, value}; + } else if (LOCK_CONFIGURATION_OPTION.equalsIgnoreCase(key)) { + lockConfiguration = new String[] {key, value}; } else { names.add(key); values.add(value); } } + // DuckDB refuses to change 'allowed_directories' and 'allowed_paths' when the external access is disabled, + // and to change any option when the configuration is locked. At startup these options are commonly used + // together, so the restricting options are applied after the options that they would refuse. + if (externalAccess != null) { + if (allowedPaths) { + restrictingOptions.add(externalAccess); + } else { + names.add(externalAccess[0]); + values.add(externalAccess[1]); + } + } + if (lockConfiguration != null) { + if (!runtimeOptions.isEmpty()) { + restrictingOptions.add(lockConfiguration); + } else { + names.add(lockConfiguration[0]); + values.add(lockConfiguration[1]); + } + } boolean shouldCache = cacheInstance && !database.equals(MEMORY_PREFIX) && !database.isEmpty(); InstanceRef ref; if (shouldCache) { - ByteBuffer instance; + ByteBuffer instance = null; + boolean[] created = new boolean[1]; try { instance = duckdb_v2_instance_open_shared(defaultEnvironment(), database.getBytes(UTF_8), utf8(names), - utf8(values), inst -> initInstance(inst, runtimeOptions)); + utf8(values), inst -> { + created[0] = true; + initInstance(inst, runtimeOptions, restrictingOptions); + }); + if (!created[0]) { + checkSharedInstance(instance, restrictingOptions); + } } catch (SQLException e) { + if (instance != null) { + duckdb_v2_instance_destroy(instance); + } throw new SQLException("Connection Error: " + rawMessage(e.getMessage()), e.getSQLState(), e.getErrorCode(), e); } @@ -260,7 +378,7 @@ static Connected startup(String database, boolean readOnly, Properties props, bo duckdb_v2_instance_attach(instance, null, (database.isEmpty() ? MEMORY_PREFIX : database).getBytes(UTF_8), true); } - initInstance(instance, runtimeOptions); + initInstance(instance, runtimeOptions, restrictingOptions); } catch (SQLException | RuntimeException e) { if (instance != null) { duckdb_v2_instance_destroy(instance); diff --git a/src/test/java/org/duckdb/TestDuckDBJDBC.java b/src/test/java/org/duckdb/TestDuckDBJDBC.java index 5a803b860..561002a2b 100644 --- a/src/test/java/org/duckdb/TestDuckDBJDBC.java +++ b/src/test/java/org/duckdb/TestDuckDBJDBC.java @@ -2384,6 +2384,155 @@ public static void test_typed_connection_properties() throws Exception { } } + private static Path writeCsv(Path dir) throws Exception { + Files.createDirectories(dir); + Path file = dir.resolve("data.csv"); + Files.write(file, "a\n42\n".getBytes(UTF_8)); + return file; + } + + private static String csvQuery(Path file) { + return "SELECT a FROM read_csv('" + file.toString().replace("'", "''") + "')"; + } + + // The connection can read the allowed file and nothing else + private static void assertSandboxed(Connection conn, Path allowedFile, Path forbiddenFile) throws Exception { + try (Statement stmt = conn.createStatement()) { + try (ResultSet rs = stmt.executeQuery("SELECT current_setting('enable_external_access')")) { + assertTrue(rs.next()); + assertFalse(rs.getBoolean(1)); + } + try (ResultSet rs = stmt.executeQuery(csvQuery(allowedFile))) { + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 42); + assertFalse(rs.next()); + } + } + // a statement is closed when its query fails + try (Statement stmt = conn.createStatement()) { + String message = assertThrows(() -> stmt.executeQuery(csvQuery(forbiddenFile)), SQLException.class); + assertTrue(message.contains("Permission Error"), message); + } + try (Statement stmt = conn.createStatement()) { + String message = assertThrows(() -> stmt.execute("SET enable_external_access = true"), SQLException.class); + // the configuration can be locked as well + assertTrue(message.contains("Cannot enable external access") || message.contains("locked"), message); + } + } + + public static void test_allowed_directories_external_access_disabled() throws Exception { + try (TempDirectory dir = new TempDirectory()) { + Path allowedFile = writeCsv(dir.path().resolve("allowed")); + Path forbiddenFile = writeCsv(dir.path().resolve("forbidden")); + + // the usual sandboxing setup, in any order of the properties + Properties config = new Properties(); + config.put("enable_external_access", false); + config.put("allowed_directories", singletonList(allowedFile.getParent().toString())); + try (Connection conn = DriverManager.getConnection(JDBC_URL, config)) { + assertSandboxed(conn, allowedFile, forbiddenFile); + } + + Properties configPaths = new Properties(); + configPaths.put("allowed_paths", singletonList(allowedFile.toString())); + configPaths.put("enable_external_access", "false"); + try (Connection conn = DriverManager.getConnection(JDBC_URL, configPaths)) { + assertSandboxed(conn, allowedFile, forbiddenFile); + } + + // the external access that stays enabled is not changed + Properties configEnabled = new Properties(); + configEnabled.put("enable_external_access", true); + configEnabled.put("allowed_directories", singletonList(allowedFile.getParent().toString())); + try (Connection conn = DriverManager.getConnection(JDBC_URL, configEnabled); + Statement stmt = conn.createStatement()) { + try (ResultSet rs = stmt.executeQuery("SELECT current_setting('enable_external_access')")) { + assertTrue(rs.next()); + assertTrue(rs.getBoolean(1)); + } + try (ResultSet rs = stmt.executeQuery(csvQuery(forbiddenFile))) { + assertTrue(rs.next()); + } + } + + // an invalid value is reported + Properties configInvalid = new Properties(); + configInvalid.put("enable_external_access", "not_a_boolean"); + configInvalid.put("allowed_directories", singletonList(allowedFile.getParent().toString())); + String message = + assertThrows(() -> DriverManager.getConnection(JDBC_URL, configInvalid), SQLException.class); + assertTrue(message.contains("enable_external_access"), message); + } + } + + public static void test_allowed_directories_external_access_disabled_cached_instance() throws Exception { + try (TempDirectory dir = new TempDirectory()) { + Path allowedFile = writeCsv(dir.path().resolve("allowed")); + Path forbiddenFile = writeCsv(dir.path().resolve("forbidden")); + String url = JDBC_URL + dir.path().resolve("sandboxed.db"); + + Properties config = new Properties(); + config.put("enable_external_access", false); + config.put("allowed_directories", singletonList(allowedFile.getParent().toString())); + try (DuckDBConnection conn1 = DriverManager.getConnection(url, config).unwrap(DuckDBConnection.class); + Statement stmt = conn1.createStatement()) { + assertSandboxed(conn1, allowedFile, forbiddenFile); + // the database itself stays accessible + stmt.execute("CREATE TABLE tab1 (col1 INTEGER)"); + stmt.execute("INSERT INTO tab1 VALUES (42)"); + stmt.execute("CHECKPOINT"); + // the instance is shared by the connections with the same properties + try (DuckDBConnection conn2 = DriverManager.getConnection(url, config).unwrap(DuckDBConnection.class)) { + assertEquals(conn1.dbAddress, conn2.dbAddress); + assertSandboxed(conn2, allowedFile, forbiddenFile); + } + } + + // an instance with the external access enabled is not shared with a connection that disables it + String urlOpen = JDBC_URL + dir.path().resolve("open.db"); + try (Connection conn1 = DriverManager.getConnection(urlOpen)) { + String message = assertThrows(() -> DriverManager.getConnection(urlOpen, config), SQLException.class); + assertTrue(message.contains("different configuration"), message); + assertTrue(conn1.isValid(0)); + } + try (Connection conn = DriverManager.getConnection(urlOpen, config)) { + assertSandboxed(conn, allowedFile, forbiddenFile); + } + } + } + + public static void test_lock_configuration_with_runtime_options() throws Exception { + try (TempDirectory dir = new TempDirectory()) { + Path allowedFile = writeCsv(dir.path().resolve("allowed")); + Path forbiddenFile = writeCsv(dir.path().resolve("forbidden")); + + Properties config = new Properties(); + config.put("lock_configuration", true); + config.put("enable_external_access", false); + config.put("allowed_directories", singletonList(allowedFile.getParent().toString())); + config.put(JDBC_STREAM_RESULTS, true); + config.put("threads", 1); + for (String url : new String[] {JDBC_URL, JDBC_URL + dir.path().resolve("locked.db")}) { + try (Connection conn = DriverManager.getConnection(url, config); + Statement stmt = conn.createStatement()) { + try (ResultSet rs = stmt.executeQuery("SELECT current_setting('enable_external_access'), " + + "current_setting('lock_configuration'), " + + "current_setting('jdbc_stream_results'), " + + "current_setting('threads')")) { + assertTrue(rs.next()); + assertFalse(rs.getBoolean(1)); + assertTrue(rs.getBoolean(2)); + assertTrue(rs.getBoolean(3)); + assertEquals(rs.getInt(4), 1); + } + assertSandboxed(conn, allowedFile, forbiddenFile); + String message = assertThrows(() -> stmt.execute("SET threads = 2"), SQLException.class); + assertTrue(message.contains("locked"), message); + } + } + } + } + public static void test_client_config_retained_on_dup() throws Exception { try (Connection conn = DriverManager.getConnection(JDBC_URL)) { try (Statement stmt1 = conn.createStatement()) { From 8cd0fc0bc6a8acff31a4acf24298f2a1e760d899 Mon Sep 17 00:00:00 2001 From: Alex Kasko Date: Wed, 2 Dec 2026 11:31:08 +0000 Subject: [PATCH 14/21] Append only to the columns of the table that are not generated The appender took its columns from the binding of SELECT * FROM table, that includes the generated columns. The INSERT with all the columns is rejected by DuckDB for a table with a generated column, and the appender asked for the values of the generated columns. The columns are read from the description of the table now (duckdb_v2_connection_describe_table), the generated columns are skipped like the appender of the engine did. The INSERT uses the resolved name of the table, that does not depend on the search path. The entry points for the qualified names and the table descriptions are added to the bindings. --- duckdb_java.def | 15 ++ duckdb_java.exp | 15 ++ duckdb_java.map | 15 ++ src/jni/bindings_v2.cpp | 230 ++++++++++++++++++ src/main/java/org/duckdb/DuckDBBindings.java | 40 +++ .../java/org/duckdb/DuckDBV2Appender.java | 109 ++++++--- src/test/java/org/duckdb/TestAppender.java | 71 ++++++ src/test/java/org/duckdb/TestBindings.java | 76 ++++++ 8 files changed, 534 insertions(+), 37 deletions(-) diff --git a/duckdb_java.def b/duckdb_java.def index 867b012bd..93dd55dfc 100644 --- a/duckdb_java.def +++ b/duckdb_java.def @@ -179,6 +179,21 @@ Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1get_1type Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1to_1string Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1variant_1to_1value Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1cast +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1create +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1destroy +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1get_1part_1count +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1get_1part +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1render +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1describe_1table +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1table_1description_1destroy +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1table_1description_1get_1qname +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1table_1description_1get_1column_1count +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1table_1description_1get_1column +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1description_1destroy +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1description_1get_1name +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1description_1get_1type +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1description_1has_1default +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1description_1has_1generated Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1flatten Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1value Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1set_1size diff --git a/duckdb_java.exp b/duckdb_java.exp index b6e445625..1732a9630 100644 --- a/duckdb_java.exp +++ b/duckdb_java.exp @@ -176,6 +176,21 @@ _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1get_1type _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1to_1string _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1variant_1to_1value _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1cast +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1create +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1destroy +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1get_1part_1count +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1get_1part +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1render +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1describe_1table +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1table_1description_1destroy +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1table_1description_1get_1qname +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1table_1description_1get_1column_1count +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1table_1description_1get_1column +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1description_1destroy +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1description_1get_1name +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1description_1get_1type +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1description_1has_1default +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1description_1has_1generated _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1flatten _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1value _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1set_1size diff --git a/duckdb_java.map b/duckdb_java.map index 19f168045..b5890a3eb 100644 --- a/duckdb_java.map +++ b/duckdb_java.map @@ -178,6 +178,21 @@ DUCKDB_JAVA { Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1to_1string; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1variant_1to_1value; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1cast; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1create; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1destroy; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1get_1part_1count; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1get_1part; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1render; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1describe_1table; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1table_1description_1destroy; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1table_1description_1get_1qname; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1table_1description_1get_1column_1count; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1table_1description_1get_1column; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1description_1destroy; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1description_1get_1name; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1description_1get_1type; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1description_1has_1default; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1description_1has_1generated; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1flatten; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1get_1value; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1vector_1set_1size; diff --git a/src/jni/bindings_v2.cpp b/src/jni/bindings_v2.cpp index 6634924fc..3ac03e240 100644 --- a/src/jni/bindings_v2.cpp +++ b/src/jni/bindings_v2.cpp @@ -1920,3 +1920,233 @@ JNIEXPORT jint JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1config_1get_1b } return res ? 1 : 0; } + +/* --- qualified names and table descriptions --- */ + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_qname_create + * Signature: ([[B)Ljava/nio/ByteBuffer; + */ +// The parts are ordered outermost first, the returned name is owned by the caller +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1create(JNIEnv *env, jclass, + jobjectArray parts_j) { + std::vector parts; + jsize count = parts_j == nullptr ? 0 : env->GetArrayLength(parts_j); + for (jsize i = 0; i < count; i++) { + auto part_arr = reinterpret_cast(env->GetObjectArrayElement(parts_j, i)); + parts.push_back(jbyteArray_to_string(env, part_arr)); + env->DeleteLocalRef(part_arr); + if (env->ExceptionCheck()) { + return nullptr; + } + } + std::vector part_ptrs; + std::vector part_lens; + for (auto &part : parts) { + part_ptrs.push_back(part.data()); + part_lens.push_back(part.size()); + } + duckdb_v2_qname_handle qname = nullptr; + CALL_V2(duckdb_v2_qname_create(part_ptrs.data(), part_lens.data(), parts.size(), &qname, ERR_OUT), nullptr); + return make_ptr_buf(env, qname); +} + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_qname_destroy + * Signature: (Ljava/nio/ByteBuffer;)V + */ +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1destroy(JNIEnv *env, jclass, + jobject qname_buf) { + CHECK_BUF(qname, qname_buf, duckdb_v2_qname_handle, "qualified name"); + duckdb_v2_qname_destroy(&qname); +} + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_qname_get_part_count + * Signature: (Ljava/nio/ByteBuffer;)J + */ +JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1get_1part_1count(JNIEnv *env, jclass, + jobject qname_buf) { + CHECK_BUF_RET(qname, qname_buf, duckdb_v2_qname_handle, "qualified name", 0); + idx_t count = 0; + CALL_V2(duckdb_v2_qname_get_part_count(qname, &count, ERR_OUT), 0); + return uint64_to_jlong(count); +} + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_qname_get_part + * Signature: (Ljava/nio/ByteBuffer;J)[B + */ +JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1get_1part(JNIEnv *env, jclass, + jobject qname_buf, + jlong index) { + CHECK_BUF_RET(qname, qname_buf, duckdb_v2_qname_handle, "qualified name", nullptr); + idx_t idx = jlong_to_idx(env, index); + if (env->ExceptionCheck()) { + return nullptr; + } + const char *part = nullptr; + idx_t part_len = 0; + CALL_V2(duckdb_v2_qname_get_part(qname, idx, &part, &part_len, ERR_OUT), nullptr); + return make_jbyteArray(env, part, part_len); +} + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_qname_render + * Signature: (Ljava/nio/ByteBuffer;)[B + */ +// The name as SQL text, its parts are quoted where the identifiers require it +JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1render(JNIEnv *env, jclass, + jobject qname_buf) { + CHECK_BUF_RET(qname, qname_buf, duckdb_v2_qname_handle, "qualified name", nullptr); + idx_t length = 0; + CALL_V2(duckdb_v2_qname_render(qname, nullptr, 0, &length, ERR_OUT), nullptr); + std::vector text(length + 1); + CALL_V2(duckdb_v2_qname_render(qname, text.data(), text.size(), &length, ERR_OUT), nullptr); + return make_jbyteArray(env, text.data(), length); +} + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_connection_describe_table + * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ +// The name is resolved like the same name in SQL, the returned description is owned by the caller +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1connection_1describe_1table(JNIEnv *env, jclass, + jobject conn_buf, + jobject qname_buf) { + CHECK_BUF_RET(conn, conn_buf, duckdb_v2_connection_handle, "connection", nullptr); + CHECK_BUF_RET(qname, qname_buf, duckdb_v2_qname_handle, "qualified name", nullptr); + duckdb_v2_table_description_handle description = nullptr; + CALL_V2(duckdb_v2_connection_describe_table(conn, qname, &description, ERR_OUT), nullptr); + return make_ptr_buf(env, description); +} + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_table_description_destroy + * Signature: (Ljava/nio/ByteBuffer;)V + */ +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1table_1description_1destroy(JNIEnv *env, jclass, + jobject desc_buf) { + CHECK_BUF(description, desc_buf, duckdb_v2_table_description_handle, "table description"); + duckdb_v2_table_description_destroy(&description); +} + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_table_description_get_qname + * Signature: (Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ +// The resolved name of the table, the returned name is owned by the caller +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1table_1description_1get_1qname(JNIEnv *env, jclass, + jobject desc_buf) { + CHECK_BUF_RET(description, desc_buf, duckdb_v2_table_description_handle, "table description", nullptr); + duckdb_v2_qname_handle qname = nullptr; + CALL_V2(duckdb_v2_table_description_get_qname(description, &qname, ERR_OUT), nullptr); + return make_ptr_buf(env, qname); +} + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_table_description_get_column_count + * Signature: (Ljava/nio/ByteBuffer;)J + */ +// All the columns are counted, the generated columns included +JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1table_1description_1get_1column_1count( + JNIEnv *env, jclass, jobject desc_buf) { + CHECK_BUF_RET(description, desc_buf, duckdb_v2_table_description_handle, "table description", 0); + idx_t count = 0; + CALL_V2(duckdb_v2_table_description_get_column_count(description, &count, ERR_OUT), 0); + return uint64_to_jlong(count); +} + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_table_description_get_column + * Signature: (Ljava/nio/ByteBuffer;J)Ljava/nio/ByteBuffer; + */ +// The returned column description is owned by the caller +JNIEXPORT jobject JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1table_1description_1get_1column(JNIEnv *env, + jclass, + jobject desc_buf, + jlong index) { + CHECK_BUF_RET(description, desc_buf, duckdb_v2_table_description_handle, "table description", nullptr); + idx_t idx = jlong_to_idx(env, index); + if (env->ExceptionCheck()) { + return nullptr; + } + duckdb_v2_column_description_handle column = nullptr; + CALL_V2(duckdb_v2_table_description_get_column(description, idx, &column, ERR_OUT), nullptr); + return make_ptr_buf(env, column); +} + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_column_description_destroy + * Signature: (Ljava/nio/ByteBuffer;)V + */ +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1description_1destroy(JNIEnv *env, jclass, + jobject column_buf) { + CHECK_BUF(column, column_buf, duckdb_v2_column_description_handle, "column description"); + duckdb_v2_column_description_destroy(&column); +} + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_column_description_get_name + * Signature: (Ljava/nio/ByteBuffer;)[B + */ +JNIEXPORT jbyteArray JNICALL +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1description_1get_1name(JNIEnv *env, jclass, jobject column_buf) { + CHECK_BUF_RET(column, column_buf, duckdb_v2_column_description_handle, "column description", nullptr); + const char *name = nullptr; + idx_t name_len = 0; + CALL_V2(duckdb_v2_column_description_get_name(column, &name, &name_len, ERR_OUT), nullptr); + return make_jbyteArray(env, name, name_len); +} + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_column_description_get_type + * Signature: (Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ +// The returned type is borrowed from the column description and must not be destroyed +JNIEXPORT jobject JNICALL +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1description_1get_1type(JNIEnv *env, jclass, jobject column_buf) { + CHECK_BUF_RET(column, column_buf, duckdb_v2_column_description_handle, "column description", nullptr); + duckdb_v2_logical_type_handle type = nullptr; + CALL_V2(duckdb_v2_column_description_get_type(column, &type, ERR_OUT), nullptr); + return make_ptr_buf(env, type); +} + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_column_description_has_default + * Signature: (Ljava/nio/ByteBuffer;)Z + */ +JNIEXPORT jboolean JNICALL +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1description_1has_1default(JNIEnv *env, jclass, jobject column_buf) { + CHECK_BUF_RET(column, column_buf, duckdb_v2_column_description_handle, "column description", JNI_FALSE); + bool has_default = false; + CALL_V2(duckdb_v2_column_description_has_default(column, &has_default, ERR_OUT), JNI_FALSE); + return has_default ? JNI_TRUE : JNI_FALSE; +} + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_column_description_has_generated + * Signature: (Ljava/nio/ByteBuffer;)Z + */ +JNIEXPORT jboolean JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1description_1has_1generated( + JNIEnv *env, jclass, jobject column_buf) { + CHECK_BUF_RET(column, column_buf, duckdb_v2_column_description_handle, "column description", JNI_FALSE); + bool has_generated = false; + CALL_V2(duckdb_v2_column_description_has_generated(column, &has_generated, ERR_OUT), JNI_FALSE); + return has_generated ? JNI_TRUE : JNI_FALSE; +} diff --git a/src/main/java/org/duckdb/DuckDBBindings.java b/src/main/java/org/duckdb/DuckDBBindings.java index 81200f4c4..10502efe3 100644 --- a/src/main/java/org/duckdb/DuckDBBindings.java +++ b/src/main/java/org/duckdb/DuckDBBindings.java @@ -483,6 +483,46 @@ static native void duckdb_v2_column_data_collection_append(ByteBuffer collection static native void duckdb_v2_statement_add_collection(ByteBuffer statement, byte[] name, ByteBuffer collection, byte[][] column_names) throws SQLException; + // qualified names and table descriptions + + // creates a qualified name from one to three parts, outermost first, it is owned by the caller + static native ByteBuffer duckdb_v2_qname_create(byte[][] parts) throws SQLException; + + static native void duckdb_v2_qname_destroy(ByteBuffer qname) throws SQLException; + + static native long duckdb_v2_qname_get_part_count(ByteBuffer qname) throws SQLException; + + static native byte[] duckdb_v2_qname_get_part(ByteBuffer qname, long index) throws SQLException; + + // the name as SQL text, its parts are quoted where the identifiers require it + static native byte[] duckdb_v2_qname_render(ByteBuffer qname) throws SQLException; + + // resolves the name of the table like SQL does, the returned description is owned by the caller + static native ByteBuffer duckdb_v2_connection_describe_table(ByteBuffer conn, ByteBuffer qname) throws SQLException; + + static native void duckdb_v2_table_description_destroy(ByteBuffer description) throws SQLException; + + // the resolved name of the table, it is owned by the caller + static native ByteBuffer duckdb_v2_table_description_get_qname(ByteBuffer description) throws SQLException; + + // counts all the columns in the declared order, the generated columns included + static native long duckdb_v2_table_description_get_column_count(ByteBuffer description) throws SQLException; + + // the returned column description is owned by the caller + static native ByteBuffer duckdb_v2_table_description_get_column(ByteBuffer description, long index) + throws SQLException; + + static native void duckdb_v2_column_description_destroy(ByteBuffer column) throws SQLException; + + static native byte[] duckdb_v2_column_description_get_name(ByteBuffer column) throws SQLException; + + // the returned type is borrowed from the column description and must not be destroyed + static native ByteBuffer duckdb_v2_column_description_get_type(ByteBuffer column) throws SQLException; + + static native boolean duckdb_v2_column_description_has_default(ByteBuffer column) throws SQLException; + + static native boolean duckdb_v2_column_description_has_generated(ByteBuffer column) throws SQLException; + // environments, instances and connections // the initializer of a new shared instance, called with the instance (that is borrowed for the call) diff --git a/src/main/java/org/duckdb/DuckDBV2Appender.java b/src/main/java/org/duckdb/DuckDBV2Appender.java index d331556a1..ff348edf5 100644 --- a/src/main/java/org/duckdb/DuckDBV2Appender.java +++ b/src/main/java/org/duckdb/DuckDBV2Appender.java @@ -5,11 +5,13 @@ import java.nio.ByteBuffer; import java.sql.SQLException; +import java.util.ArrayList; import java.util.List; /** * Appends the data chunks to a table, using the C API v2 that has no appender: the chunks are collected into a - * column data collection, that is read by a prepared {@code INSERT INTO table SELECT * FROM }. + * column data collection, that is read by an {@code INSERT INTO table SELECT * FROM }. The chunks have + * the columns of the table that are not generated. */ final class DuckDBV2Appender { private static final byte[] BUFFER_NAME = "__duckdb_appender_buffer".getBytes(UTF_8); @@ -19,6 +21,8 @@ final class DuckDBV2Appender { private final String schema; private final String table; private final ByteBuffer[] types; + // the indexes of the columns in the table, that can also have generated columns + private final int[] tableColumns; private ByteBuffer statement; private ByteBuffer collection; private ByteBuffer appendState; @@ -26,12 +30,14 @@ final class DuckDBV2Appender { private List defaults; private String error = ""; - private DuckDBV2Appender(DuckDBConnection conn, String catalog, String schema, String table, ByteBuffer[] types) { + private DuckDBV2Appender(DuckDBConnection conn, String catalog, String schema, String table, ByteBuffer[] types, + int[] tableColumns) { this.conn = conn; this.catalog = catalog; this.schema = schema; this.table = table; this.types = types; + this.tableColumns = tableColumns; } static String quoteIdentifier(String name) { @@ -46,51 +52,79 @@ private static ByteBuffer parseSingle(ByteBuffer connHandle, String sql) throws return DuckDBCore.parseSingleStatement(connHandle, sql); } - /** Creates an appender to the table, the catalog and the schema can be null. */ + private static boolean isEmpty(String name) { + return name == null || name.isEmpty(); + } + + /** + * Creates an appender to the table, the catalog and the schema can be null. The name of the table is resolved like + * the same name in SQL, the default schema is used when only the catalog is given. + */ static DuckDBV2Appender create(DuckDBConnection conn, String catalog, String schema, String table) throws SQLException { - StringBuilder qualified = new StringBuilder(); - if (catalog != null) { - qualified.append(quoteIdentifier(catalog)).append('.'); + List parts = new ArrayList<>(); + if (!isEmpty(catalog)) { + parts.add(catalog.getBytes(UTF_8)); + parts.add((isEmpty(schema) ? DuckDBConnection.DEFAULT_SCHEMA : schema).getBytes(UTF_8)); + } else if (!isEmpty(schema)) { + parts.add(schema.getBytes(UTF_8)); } - if (schema != null) { - qualified.append(quoteIdentifier(schema)).append('.'); - } - qualified.append(quoteIdentifier(table)); + parts.add(String.valueOf(table).getBytes(UTF_8)); ByteBuffer connHandle = conn.connRef; ByteBuffer factory = duckdb_v2_connection_get_factory(connHandle); - // the columns of the table: binding reports them without reading a row - ByteBuffer probe = parseSingle(connHandle, "SELECT * FROM " + qualified); - ByteBuffer[] schemas = null; - ByteBuffer[] types; - String[] names; + // The columns that can be appended to: the generated columns are computed by the engine + String qualified; + List typeList = new ArrayList<>(); + List nameList = new ArrayList<>(); + List tableColumnList = new ArrayList<>(); + ByteBuffer requested = duckdb_v2_qname_create(parts.toArray(new byte[0][])); + ByteBuffer description = null; + ByteBuffer resolved = null; + boolean described = false; + conn.queryGate.acquireUninterruptibly(); try { - schemas = duckdb_v2_statement_bind(connHandle, probe); - int count = (int) duckdb_v2_schema_get_count(schemas[0]); - if (count == 0) { - throw new SQLException("Invalid Input Error: table " + qualified + " has no columns to append to"); - } - types = new ByteBuffer[count]; - names = new String[count]; - try { - for (int i = 0; i < count; i++) { - types[i] = duckdb_v2_logical_type_copy(duckdb_v2_schema_get_field_type(schemas[0], i)); - names[i] = new String(duckdb_v2_schema_get_field_name(schemas[0], i), UTF_8); + description = duckdb_v2_connection_describe_table(connHandle, requested); + // the name that the lookup landed on, it does not depend on the search path + resolved = duckdb_v2_table_description_get_qname(description); + qualified = new String(duckdb_v2_qname_render(resolved), UTF_8); + int count = (int) duckdb_v2_table_description_get_column_count(description); + for (int i = 0; i < count; i++) { + ByteBuffer column = duckdb_v2_table_description_get_column(description, i); + try { + if (duckdb_v2_column_description_has_generated(column)) { + continue; + } + typeList.add(duckdb_v2_logical_type_copy(duckdb_v2_column_description_get_type(column))); + nameList.add(new String(duckdb_v2_column_description_get_name(column), UTF_8)); + tableColumnList.add(i); + } finally { + duckdb_v2_column_description_destroy(column); } - } catch (SQLException e) { - destroyTypes(types); - throw e; } + if (typeList.isEmpty()) { + throw new SQLException("Invalid Input Error: table " + qualified + " has no columns to append to"); + } + described = true; } finally { - if (schemas != null) { - duckdb_v2_schema_destroy(schemas[0]); - if (schemas[1] != null) { - duckdb_v2_schema_destroy(schemas[1]); - } + conn.queryGate.release(); + if (!described) { + destroyTypes(typeList.toArray(new ByteBuffer[0])); } - duckdb_v2_sql_statement_destroy(probe); + if (resolved != null) { + duckdb_v2_qname_destroy(resolved); + } + if (description != null) { + duckdb_v2_table_description_destroy(description); + } + duckdb_v2_qname_destroy(requested); + } + ByteBuffer[] types = typeList.toArray(new ByteBuffer[0]); + String[] names = nameList.toArray(new String[0]); + int[] tableColumns = new int[names.length]; + for (int i = 0; i < tableColumns.length; i++) { + tableColumns[i] = tableColumnList.get(i); } StringBuilder columns = new StringBuilder(); @@ -103,7 +137,7 @@ static DuckDBV2Appender create(DuckDBConnection conn, String catalog, String sch String insert = "INSERT INTO " + qualified + " (" + columns + ") SELECT * FROM " + new String(BUFFER_NAME, UTF_8); - DuckDBV2Appender appender = new DuckDBV2Appender(conn, catalog, schema, table, types); + DuckDBV2Appender appender = new DuckDBV2Appender(conn, catalog, schema, table, types, tableColumns); boolean ok = false; try { appender.statement = parseSingle(connHandle, insert); @@ -227,7 +261,8 @@ int appendDefaultToChunk(ByteBuffer chunk, long col, long row) { if (duckdb_v2_vector_get_size(vec) <= row) { duckdb_v2_vector_set_size(vec, row + 1); } - String defaultSql = col < defaults.size() ? defaults.get((int) col) : null; + int tableColumn = col >= 0 && col < tableColumns.length ? tableColumns[(int) col] : -1; + String defaultSql = tableColumn >= 0 && tableColumn < defaults.size() ? defaults.get(tableColumn) : null; ByteBuffer value; if (defaultSql != null) { // the default value is an expression, that is evaluated every time as it can be volatile diff --git a/src/test/java/org/duckdb/TestAppender.java b/src/test/java/org/duckdb/TestAppender.java index aca9d951c..12bf39971 100644 --- a/src/test/java/org/duckdb/TestAppender.java +++ b/src/test/java/org/duckdb/TestAppender.java @@ -82,6 +82,77 @@ public static void test_appender_default() throws Exception { } } + public static void test_appender_generated_column() throws Exception { + try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); + Statement stmt = conn.createStatement()) { + + stmt.execute("CREATE TABLE tab1(col1 INTEGER, col2 INTEGER GENERATED ALWAYS AS (col1 * 2), col3 VARCHAR)"); + // the values of the generated column are not appended + try (DuckDBAppender appender = conn.createAppender("tab1")) { + appender.beginRow().append(41).append("foo").endRow(); + appender.beginRow().append(42).append("bar").endRow(); + assertEquals(appender.flush(), 2L); + appender.beginRow().append(43).appendNull().endRow(); + // a row has two values + appender.beginRow().append(44).append("baz"); + assertThrows(() -> { appender.append(88); }, SQLException.class); + appender.endRow(); + } + + try (ResultSet rs = stmt.executeQuery("SELECT col1, col2, col3 FROM tab1 ORDER BY col1")) { + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 41); + assertEquals(rs.getInt(2), 82); + assertEquals(rs.getString(3), "foo"); + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 42); + assertEquals(rs.getInt(2), 84); + assertEquals(rs.getString(3), "bar"); + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 43); + assertEquals(rs.getInt(2), 86); + assertNull(rs.getString(3)); + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 44); + assertEquals(rs.getInt(2), 88); + assertEquals(rs.getString(3), "baz"); + assertFalse(rs.next()); + } + } + } + + public static void test_appender_generated_column_default() throws Exception { + try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); + Statement stmt = conn.createStatement()) { + + // the generated columns come before the columns with the default values + stmt.execute("CREATE TABLE tab1(gen1 INTEGER GENERATED ALWAYS AS (col1 + 1) VIRTUAL, " + + "col1 INTEGER DEFAULT 42, gen2 VARCHAR AS (col2 || 'bar'), col2 VARCHAR DEFAULT 'foo', " + + "col3 INTEGER)"); + try (DuckDBAppender appender = conn.createAppender("tab1")) { + appender.beginRow().appendDefault().appendDefault().appendDefault().endRow(); + appender.beginRow().append(1).append("baz").append(2).endRow(); + assertEquals(appender.flush(), 2L); + } + + try (ResultSet rs = stmt.executeQuery("SELECT gen1, col1, gen2, col2, col3 FROM tab1 ORDER BY col1 DESC")) { + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 43); + assertEquals(rs.getInt(2), 42); + assertEquals(rs.getString(3), "foobar"); + assertEquals(rs.getString(4), "foo"); + assertNull(rs.getObject(5)); + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 2); + assertEquals(rs.getInt(2), 1); + assertEquals(rs.getString(3), "bazbar"); + assertEquals(rs.getString(4), "baz"); + assertEquals(rs.getInt(5), 2); + assertFalse(rs.next()); + } + } + } + public static void test_appender_boolean() throws Exception { try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); Statement stmt = conn.createStatement()) { diff --git a/src/test/java/org/duckdb/TestBindings.java b/src/test/java/org/duckdb/TestBindings.java index 40d52f0e5..2cc42e8fb 100644 --- a/src/test/java/org/duckdb/TestBindings.java +++ b/src/test/java/org/duckdb/TestBindings.java @@ -652,6 +652,82 @@ public static void test_bindings_decimal_type() throws Exception { } } + public static void test_v2_appender_generated_column() throws Exception { + try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); + Statement stmt = conn.createStatement()) { + stmt.execute("CREATE TABLE tab1(col1 INT, gen1 INT GENERATED ALWAYS AS (col1 * 2), col2 VARCHAR)"); + + // only the columns that can be appended to + DuckDBV2Appender appender = DuckDBV2Appender.create(conn, null, null, "tab1"); + assertEquals(appender.columnCount(), 2L); + ByteBuffer col1Type = appender.columnType(0); + assertEquals(duckdb_get_type_id(col1Type), DUCKDB_TYPE_INTEGER.typeId); + ByteBuffer col2Type = appender.columnType(1); + assertEquals(duckdb_get_type_id(col2Type), DUCKDB_TYPE_VARCHAR.typeId); + assertNull(appender.columnType(2)); + + duckdb_destroy_logical_type(col1Type); + duckdb_destroy_logical_type(col2Type); + assertEquals(appender.close(), 0); + appender.destroy(); + + assertThrows(() -> { DuckDBV2Appender.create(conn, null, null, "tab2"); }, SQLException.class); + } + } + + public static void test_bindings_table_description() throws Exception { + try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); + Statement stmt = conn.createStatement()) { + stmt.execute("CREATE SCHEMA \"My Schema\""); + stmt.execute("CREATE TABLE \"My Schema\".\"Tab1\"(col1 INT DEFAULT 42, " + + "gen1 INT GENERATED ALWAYS AS (col1 * 2), \"Col 2\" VARCHAR)"); + + ByteBuffer qname = + duckdb_v2_qname_create(new byte[][] {"my schema".getBytes(UTF_8), "tab1".getBytes(UTF_8)}); + assertEquals(duckdb_v2_qname_get_part_count(qname), 2L); + assertEquals(duckdb_v2_qname_get_part(qname, 1), "tab1".getBytes(UTF_8)); + assertEquals(duckdb_v2_qname_render(qname), "\"my schema\".tab1".getBytes(UTF_8)); + + ByteBuffer description = duckdb_v2_connection_describe_table(conn.connRef, qname); + // the resolved name has the casing that the table was created with + ByteBuffer resolved = duckdb_v2_table_description_get_qname(description); + assertEquals(duckdb_v2_qname_get_part_count(resolved), 3L); + assertEquals(duckdb_v2_qname_get_part(resolved, 0), "memory".getBytes(UTF_8)); + assertEquals(duckdb_v2_qname_get_part(resolved, 1), "My Schema".getBytes(UTF_8)); + assertEquals(duckdb_v2_qname_get_part(resolved, 2), "Tab1".getBytes(UTF_8)); + assertEquals(duckdb_v2_qname_render(resolved), "memory.\"My Schema\".Tab1".getBytes(UTF_8)); + + assertEquals(duckdb_v2_table_description_get_column_count(description), 3L); + ByteBuffer col1 = duckdb_v2_table_description_get_column(description, 0); + assertEquals(duckdb_v2_column_description_get_name(col1), "col1".getBytes(UTF_8)); + assertEquals(duckdb_get_type_id(duckdb_v2_column_description_get_type(col1)), DUCKDB_TYPE_INTEGER.typeId); + assertTrue(duckdb_v2_column_description_has_default(col1)); + assertFalse(duckdb_v2_column_description_has_generated(col1)); + ByteBuffer gen1 = duckdb_v2_table_description_get_column(description, 1); + assertEquals(duckdb_v2_column_description_get_name(gen1), "gen1".getBytes(UTF_8)); + assertFalse(duckdb_v2_column_description_has_default(gen1)); + assertTrue(duckdb_v2_column_description_has_generated(gen1)); + ByteBuffer col2 = duckdb_v2_table_description_get_column(description, 2); + assertEquals(duckdb_v2_column_description_get_name(col2), "Col 2".getBytes(UTF_8)); + assertEquals(duckdb_get_type_id(duckdb_v2_column_description_get_type(col2)), DUCKDB_TYPE_VARCHAR.typeId); + assertFalse(duckdb_v2_column_description_has_default(col2)); + assertFalse(duckdb_v2_column_description_has_generated(col2)); + assertThrows(() -> { duckdb_v2_table_description_get_column(description, 3); }, SQLException.class); + + duckdb_v2_column_description_destroy(col2); + duckdb_v2_column_description_destroy(gen1); + duckdb_v2_column_description_destroy(col1); + duckdb_v2_qname_destroy(resolved); + duckdb_v2_table_description_destroy(description); + duckdb_v2_qname_destroy(qname); + + ByteBuffer missing = duckdb_v2_qname_create(new byte[][] {"tab2".getBytes(UTF_8)}); + assertThrows(() -> { duckdb_v2_connection_describe_table(conn.connRef, missing); }, SQLException.class); + duckdb_v2_qname_destroy(missing); + assertThrows(() -> { duckdb_v2_qname_create(new byte[0][]); }, SQLException.class); + } + } + public static void test_bindings_decimal_type_validation() throws Exception { assertThrows(() -> { duckdb_create_decimal_type(0, 0); }, SQLException.class); assertThrows(() -> { duckdb_create_decimal_type(-1, 0); }, SQLException.class); From f385906dae800d8f326534cc6eb6e06f58f0ca29 Mon Sep 17 00:00:00 2001 From: Alex Kasko Date: Wed, 2 Dec 2026 11:32:57 +0000 Subject: [PATCH 15/21] Look up the column defaults of the appender by the resolved table name The default values were read from duckdb_columns() with an exact match of the table name as it was given to the appender, and without a schema or a catalog when they were not given. A table that was created as "Foo" and appended to as "foo" got NULL instead of its defaults, and the defaults of the tables with the same name in the other schemas and catalogs were mixed up. The lookup uses the catalog, the schema and the name that the table description resolved the name to. --- .../java/org/duckdb/DuckDBV2Appender.java | 37 +++++------ src/test/java/org/duckdb/TestAppender.java | 63 +++++++++++++++++++ 2 files changed, 82 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/duckdb/DuckDBV2Appender.java b/src/main/java/org/duckdb/DuckDBV2Appender.java index ff348edf5..36193e4da 100644 --- a/src/main/java/org/duckdb/DuckDBV2Appender.java +++ b/src/main/java/org/duckdb/DuckDBV2Appender.java @@ -17,9 +17,8 @@ final class DuckDBV2Appender { private static final byte[] BUFFER_NAME = "__duckdb_appender_buffer".getBytes(UTF_8); private final DuckDBConnection conn; - private final String catalog; - private final String schema; - private final String table; + // the catalog, the schema and the name of the table that the name of the table is resolved to + private final String[] resolvedName; private final ByteBuffer[] types; // the indexes of the columns in the table, that can also have generated columns private final int[] tableColumns; @@ -30,12 +29,9 @@ final class DuckDBV2Appender { private List defaults; private String error = ""; - private DuckDBV2Appender(DuckDBConnection conn, String catalog, String schema, String table, ByteBuffer[] types, - int[] tableColumns) { + private DuckDBV2Appender(DuckDBConnection conn, String[] resolvedName, ByteBuffer[] types, int[] tableColumns) { this.conn = conn; - this.catalog = catalog; - this.schema = schema; - this.table = table; + this.resolvedName = resolvedName; this.types = types; this.tableColumns = tableColumns; } @@ -76,6 +72,7 @@ static DuckDBV2Appender create(DuckDBConnection conn, String catalog, String sch // The columns that can be appended to: the generated columns are computed by the engine String qualified; + String[] resolvedName; List typeList = new ArrayList<>(); List nameList = new ArrayList<>(); List tableColumnList = new ArrayList<>(); @@ -89,6 +86,13 @@ static DuckDBV2Appender create(DuckDBConnection conn, String catalog, String sch // the name that the lookup landed on, it does not depend on the search path resolved = duckdb_v2_table_description_get_qname(description); qualified = new String(duckdb_v2_qname_render(resolved), UTF_8); + resolvedName = new String[(int) duckdb_v2_qname_get_part_count(resolved)]; + for (int i = 0; i < resolvedName.length; i++) { + resolvedName[i] = new String(duckdb_v2_qname_get_part(resolved, i), UTF_8); + } + if (resolvedName.length != 3) { + throw new SQLException("Invalid Input Error: cannot resolve the name of the table " + qualified); + } int count = (int) duckdb_v2_table_description_get_column_count(description); for (int i = 0; i < count; i++) { ByteBuffer column = duckdb_v2_table_description_get_column(description, i); @@ -137,7 +141,7 @@ static DuckDBV2Appender create(DuckDBConnection conn, String catalog, String sch String insert = "INSERT INTO " + qualified + " (" + columns + ") SELECT * FROM " + new String(BUFFER_NAME, UTF_8); - DuckDBV2Appender appender = new DuckDBV2Appender(conn, catalog, schema, table, types, tableColumns); + DuckDBV2Appender appender = new DuckDBV2Appender(conn, resolvedName, types, tableColumns); boolean ok = false; try { appender.statement = parseSingle(connHandle, insert); @@ -245,15 +249,12 @@ int close() { int appendDefaultToChunk(ByteBuffer chunk, long col, long row) { try { if (defaults == null) { - // the default values of all columns of the table, in the order of the columns - String sql = "SELECT column_default FROM duckdb_columns() WHERE table_name = " + quoteLiteral(table); - if (schema != null) { - sql += " AND schema_name = " + quoteLiteral(schema); - } - if (catalog != null) { - sql += " AND database_name = " + quoteLiteral(catalog); - } - sql += " ORDER BY column_index"; + // The default values of all columns of the table, in the order of the columns. The table is looked + // up by its resolved name, that has the casing that the table was created with: the tables with the + // same name in the other schemas and catalogs are not matched. + String sql = "SELECT column_default FROM duckdb_columns() WHERE database_name = " + + quoteLiteral(resolvedName[0]) + " AND schema_name = " + quoteLiteral(resolvedName[1]) + + " AND table_name = " + quoteLiteral(resolvedName[2]) + " ORDER BY column_index"; defaults = DuckDBCore.queryStrings(conn, sql); } ByteBuffer vec = duckdb_data_chunk_get_vector(chunk, col); diff --git a/src/test/java/org/duckdb/TestAppender.java b/src/test/java/org/duckdb/TestAppender.java index 12bf39971..7d9d8b30f 100644 --- a/src/test/java/org/duckdb/TestAppender.java +++ b/src/test/java/org/duckdb/TestAppender.java @@ -82,6 +82,69 @@ public static void test_appender_default() throws Exception { } } + private static void assertDefaultRows(Statement stmt, String table, int col1, String col2) throws Exception { + try (ResultSet rs = stmt.executeQuery("SELECT col1, col2 FROM " + table + " ORDER BY col1")) { + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 1); + assertEquals(rs.getString(2), "explicit"); + assertTrue(rs.next()); + assertEquals(rs.getInt(1), col1); + assertEquals(rs.getString(2), col2); + assertFalse(rs.next()); + } + } + + private static void appendDefaultRows(DuckDBAppender appender) throws Exception { + try { + appender.beginRow().append(1).append("explicit").endRow(); + appender.beginRow().appendDefault().appendDefault().endRow(); + assertEquals(appender.flush(), 2L); + } finally { + appender.close(); + } + } + + public static void test_appender_default_table_name_case() throws Exception { + try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); + Statement stmt = conn.createStatement()) { + + stmt.execute("CREATE SCHEMA \"Sch1\""); + stmt.execute("CREATE TABLE \"Sch1\".\"Tab1\"(col1 INTEGER DEFAULT 42, col2 VARCHAR DEFAULT 'foo')"); + // the names are matched like in SQL, regardless of the case + appendDefaultRows(conn.createAppender("sch1", "tab1")); + assertDefaultRows(stmt, "\"Sch1\".\"Tab1\"", 42, "foo"); + stmt.execute("DELETE FROM \"Sch1\".\"Tab1\""); + appendDefaultRows(conn.createAppender("MEMORY", "SCH1", "TAB1")); + assertDefaultRows(stmt, "\"Sch1\".\"Tab1\"", 42, "foo"); + } + } + + public static void test_appender_default_same_table_name() throws Exception { + try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); + Statement stmt = conn.createStatement()) { + + // the tables with the same name have different default values + stmt.execute("CREATE TABLE main.tab1(col1 INTEGER DEFAULT 42, col2 VARCHAR DEFAULT 'foo')"); + stmt.execute("CREATE SCHEMA sch1"); + stmt.execute("CREATE TABLE sch1.tab1(col1 INTEGER DEFAULT 43, col2 VARCHAR DEFAULT 'bar')"); + stmt.execute("ATTACH ':memory:' AS db1"); + stmt.execute("CREATE TABLE db1.main.tab1(col1 INTEGER DEFAULT 44, col2 VARCHAR DEFAULT 'baz')"); + + appendDefaultRows(conn.createAppender("tab1")); + assertDefaultRows(stmt, "memory.main.tab1", 42, "foo"); + appendDefaultRows(conn.createAppender("sch1", "tab1")); + assertDefaultRows(stmt, "memory.sch1.tab1", 43, "bar"); + appendDefaultRows(conn.createAppender("db1", "main", "tab1")); + assertDefaultRows(stmt, "db1.main.tab1", 44, "baz"); + + // the temporary table is the one that the name without a schema is resolved to + stmt.execute("CREATE TEMPORARY TABLE tab1(col1 INTEGER DEFAULT 45, col2 VARCHAR DEFAULT 'boo')"); + appendDefaultRows(conn.createAppender("tab1")); + assertDefaultRows(stmt, "temp.main.tab1", 45, "boo"); + assertDefaultRows(stmt, "memory.main.tab1", 42, "foo"); + } + } + public static void test_appender_generated_column() throws Exception { try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); Statement stmt = conn.createStatement()) { From 1900dafa1e55c9898af9eb75668088d4ae9bd30b Mon Sep 17 00:00:00 2001 From: Alex Kasko Date: Wed, 2 Dec 2026 11:41:10 +0000 Subject: [PATCH 16/21] Do not evaluate the appender defaults row by row and prepare the INSERT once Every appendDefault call ran a SELECT of the default expression on the connection, and every flush planned the INSERT from scratch. Appending 1M rows with two defaulted columns took 2M queries (about two minutes), it takes less than a second now. The appender only marks the rows that have the default value. A column that has it in all the rows of a chunk is left out of the INSERT, so that the engine fills it, also with the volatile defaults like nextval. When a chunk has both the default and the other values in a column, the defaults are evaluated by one query for the chunk. The INSERT statements are prepared once and are reused by the next flushes. --- src/main/java/org/duckdb/DuckDBCore.java | 39 -- .../java/org/duckdb/DuckDBV2Appender.java | 372 ++++++++++++++---- src/test/java/org/duckdb/TestAppender.java | 167 ++++++++ 3 files changed, 463 insertions(+), 115 deletions(-) diff --git a/src/main/java/org/duckdb/DuckDBCore.java b/src/main/java/org/duckdb/DuckDBCore.java index 716f75964..732b41434 100644 --- a/src/main/java/org/duckdb/DuckDBCore.java +++ b/src/main/java/org/duckdb/DuckDBCore.java @@ -411,45 +411,6 @@ static List queryStrings(DuckDBConnection connection, String sql) throws } } - /** Runs the query and returns the first value of its result, that is owned by the caller. */ - static ByteBuffer queryValue(DuckDBConnection connection, String sql) throws SQLException { - connection.queryGate.acquireUninterruptibly(); - try { - ByteBuffer conn = conn(connection.connRef); - ByteBuffer statement = parseSingleStatement(conn, sql); - ByteBuffer result; - try { - result = duckdb_v2_statement_execute(conn, statement, null); - } finally { - duckdb_v2_sql_statement_destroy(statement); - } - try { - ByteBuffer chunk = duckdb_v2_result_fetch_chunk(result); - if (chunk == null) { - throw invalid("Unable to evaluate the query: " + sql); - } - try { - if (duckdb_data_chunk_get_size(chunk) == 0) { - throw invalid("Unable to evaluate the query: " + sql); - } - ByteBuffer value = duckdb_v2_vector_get_value(duckdb_data_chunk_get_vector(chunk, 0), 0); - // the rest of the result is read to complete the query - ByteBuffer rest; - while ((rest = duckdb_v2_result_fetch_chunk(result)) != null) { - duckdb_destroy_data_chunk(rest); - } - return value; - } finally { - duckdb_destroy_data_chunk(chunk); - } - } finally { - duckdb_v2_result_destroy(result); - } - } finally { - connection.queryGate.release(); - } - } - /** Runs the statement and discards its result. */ static void executeSql(DuckDBConnection connection, String sql) throws SQLException { connection.queryGate.acquireUninterruptibly(); diff --git a/src/main/java/org/duckdb/DuckDBV2Appender.java b/src/main/java/org/duckdb/DuckDBV2Appender.java index 36193e4da..b01fbc885 100644 --- a/src/main/java/org/duckdb/DuckDBV2Appender.java +++ b/src/main/java/org/duckdb/DuckDBV2Appender.java @@ -6,34 +6,75 @@ import java.nio.ByteBuffer; import java.sql.SQLException; import java.util.ArrayList; +import java.util.BitSet; +import java.util.HashMap; import java.util.List; +import java.util.Map; /** * Appends the data chunks to a table, using the C API v2 that has no appender: the chunks are collected into a - * column data collection, that is read by an {@code INSERT INTO table SELECT * FROM }. The chunks have - * the columns of the table that are not generated. + * column data collection, that is read by a prepared {@code INSERT INTO table SELECT * FROM }. The chunks + * have the columns of the table that are not generated. + * + *

The default values are not evaluated by the appender. A column that has the default value in all the rows of a + * chunk is left out of the INSERT, so that the engine fills it. Only when a chunk has both the default and the other + * values in a column, its default values are evaluated, with one query for the chunk. */ final class DuckDBV2Appender { private static final byte[] BUFFER_NAME = "__duckdb_appender_buffer".getBytes(UTF_8); + private static final long VECTOR_SIZE = duckdb_vector_size(); + + /** The INSERT of the buffered rows, without the columns that are filled with their default values. */ + private static final class Insert { + final ByteBuffer statement; + // the statement is prepared when it is executed for the first time + ByteBuffer prepared; + + Insert(ByteBuffer statement) { + this.statement = statement; + } + } private final DuckDBConnection conn; + // the name of the table as SQL text + private final String qualifiedName; // the catalog, the schema and the name of the table that the name of the table is resolved to private final String[] resolvedName; private final ByteBuffer[] types; + private final String[] names; + // whether the columns have the default values, the other columns have the NULL default + private final boolean[] hasDefault; // the indexes of the columns in the table, that can also have generated columns private final int[] tableColumns; - private ByteBuffer statement; private ByteBuffer collection; private ByteBuffer appendState; - // the SQL texts of the default values of the columns, they are loaded when the first default is appended + // the INSERT statements by the columns that are left out of them + private final Map inserts = new HashMap<>(); + // the columns that are left out of the INSERT of the buffered rows + private BitSet bufferedOmitted = new BitSet(); + private ByteBuffer nullValue; + // the SQL texts of the default values of the columns of the table, they are loaded when they are needed private List defaults; + + // The chunk that the default values are appended to, with its vectors + private ByteBuffer defaultsChunk; + private ByteBuffer[] defaultsVectors; + // the rows of the chunk that have the default value, by the column + private final BitSet[] defaultRows; + private boolean hasDefaultRows = false; + private String error = ""; - private DuckDBV2Appender(DuckDBConnection conn, String[] resolvedName, ByteBuffer[] types, int[] tableColumns) { + private DuckDBV2Appender(DuckDBConnection conn, String qualifiedName, String[] resolvedName, ByteBuffer[] types, + String[] names, boolean[] hasDefault, int[] tableColumns) { this.conn = conn; + this.qualifiedName = qualifiedName; this.resolvedName = resolvedName; this.types = types; + this.names = names; + this.hasDefault = hasDefault; this.tableColumns = tableColumns; + this.defaultRows = new BitSet[types.length]; } static String quoteIdentifier(String name) { @@ -44,10 +85,6 @@ static String quoteLiteral(String value) { return "'" + value.replace("'", "''") + "'"; } - private static ByteBuffer parseSingle(ByteBuffer connHandle, String sql) throws SQLException { - return DuckDBCore.parseSingleStatement(connHandle, sql); - } - private static boolean isEmpty(String name) { return name == null || name.isEmpty(); } @@ -75,6 +112,7 @@ static DuckDBV2Appender create(DuckDBConnection conn, String catalog, String sch String[] resolvedName; List typeList = new ArrayList<>(); List nameList = new ArrayList<>(); + List hasDefaultList = new ArrayList<>(); List tableColumnList = new ArrayList<>(); ByteBuffer requested = duckdb_v2_qname_create(parts.toArray(new byte[0][])); ByteBuffer description = null; @@ -102,6 +140,7 @@ static DuckDBV2Appender create(DuckDBConnection conn, String catalog, String sch } typeList.add(duckdb_v2_logical_type_copy(duckdb_v2_column_description_get_type(column))); nameList.add(new String(duckdb_v2_column_description_get_name(column), UTF_8)); + hasDefaultList.add(duckdb_v2_column_description_has_default(column)); tableColumnList.add(i); } finally { duckdb_v2_column_description_destroy(column); @@ -126,32 +165,20 @@ static DuckDBV2Appender create(DuckDBConnection conn, String catalog, String sch } ByteBuffer[] types = typeList.toArray(new ByteBuffer[0]); String[] names = nameList.toArray(new String[0]); + boolean[] hasDefault = new boolean[names.length]; int[] tableColumns = new int[names.length]; - for (int i = 0; i < tableColumns.length; i++) { - tableColumns[i] = tableColumnList.get(i); - } - - StringBuilder columns = new StringBuilder(); for (int i = 0; i < names.length; i++) { - if (i > 0) { - columns.append(", "); - } - columns.append(quoteIdentifier(names[i])); + hasDefault[i] = hasDefaultList.get(i); + tableColumns[i] = tableColumnList.get(i); } - String insert = - "INSERT INTO " + qualified + " (" + columns + ") SELECT * FROM " + new String(BUFFER_NAME, UTF_8); - DuckDBV2Appender appender = new DuckDBV2Appender(conn, resolvedName, types, tableColumns); + DuckDBV2Appender appender = + new DuckDBV2Appender(conn, qualified, resolvedName, types, names, hasDefault, tableColumns); boolean ok = false; try { - appender.statement = parseSingle(connHandle, insert); appender.collection = duckdb_v2_column_data_collection_create(factory, types); appender.appendState = duckdb_v2_column_data_collection_append_state_create(appender.collection); - byte[][] nameBytes = new byte[names.length][]; - for (int i = 0; i < names.length; i++) { - nameBytes[i] = names[i].getBytes(UTF_8); - } - duckdb_v2_statement_add_collection(appender.statement, BUFFER_NAME, appender.collection, nameBytes); + appender.nullValue = DuckDBCore.nullValue(factory); ok = true; return appender; } finally { @@ -191,9 +218,187 @@ private int fail(SQLException e) { return 1; } + // --------------------------------------------------------------------------------------------------------- + // Default values + // --------------------------------------------------------------------------------------------------------- + + private ByteBuffer defaultsVector(ByteBuffer chunk, int col) throws SQLException { + if (chunk != defaultsChunk) { + // the default values are tracked for one chunk at a time, that is appended before the next one is filled + clearDefaultRows(); + defaultsChunk = chunk; + defaultsVectors = new ByteBuffer[types.length]; + } + ByteBuffer vec = defaultsVectors[col]; + if (vec == null) { + vec = duckdb_data_chunk_get_vector(chunk, col); + defaultsVectors[col] = vec; + } + return vec; + } + + private void clearDefaultRows() { + if (hasDefaultRows) { + for (BitSet rows : defaultRows) { + if (rows != null) { + rows.clear(); + } + } + hasDefaultRows = false; + } + } + + /** + * Appends the default value of the column to the row of the chunk, returns 0 on success. The value of the row is + * set to NULL here, the default value is written when the chunk is appended (see {@link #appendChunk}). + */ + int appendDefaultToChunk(ByteBuffer chunk, long col, long row) { + try { + if (col < 0 || col >= types.length) { + throw new SQLException("Invalid Input Error: invalid column index: " + col); + } + if (row < 0 || row >= VECTOR_SIZE) { + throw new SQLException("Invalid Input Error: invalid row index: " + row); + } + int colIdx = (int) col; + ByteBuffer vec = defaultsVector(chunk, colIdx); + BitSet rows = defaultRows[colIdx]; + if (rows == null) { + rows = new BitSet(); + defaultRows[colIdx] = rows; + } + if (rows.isEmpty()) { + // the size of the vector is set by the caller when the chunk is complete + duckdb_v2_vector_set_size(vec, VECTOR_SIZE); + } + duckdb_v2_vector_set_value(vec, row, nullValue); + rows.set((int) row); + hasDefaultRows = true; + return 0; + } catch (SQLException e) { + return fail(e); + } + } + + private String defaultSql(int col) throws SQLException { + if (defaults == null) { + // The default values of all columns of the table, in the order of the columns. The table is looked + // up by its resolved name, that has the casing that the table was created with: the tables with the + // same name in the other schemas and catalogs are not matched. + String sql = + "SELECT column_default FROM duckdb_columns() WHERE database_name = " + quoteLiteral(resolvedName[0]) + + " AND schema_name = " + quoteLiteral(resolvedName[1]) + + " AND table_name = " + quoteLiteral(resolvedName[2]) + " ORDER BY column_index"; + defaults = DuckDBCore.queryStrings(conn, sql); + } + int tableColumn = tableColumns[col]; + String sql = tableColumn < defaults.size() ? defaults.get(tableColumn) : null; + if (sql == null) { + throw new SQLException("Invalid Input Error: cannot read the default value of the column " + + quoteIdentifier(names[col])); + } + return sql; + } + + /** + * Writes the default values of the column to the rows of the vector. The default value is an expression that can + * be volatile, it is evaluated for every row by one query. + */ + private void writeDefaults(ByteBuffer vec, int col, BitSet rows, int count) throws SQLException { + String sql = "SELECT " + defaultSql(col) + " FROM range(" + count + ")"; + conn.queryGate.acquireUninterruptibly(); + try { + ByteBuffer connHandle = conn.connRef; + ByteBuffer statement = DuckDBCore.parseSingleStatement(connHandle, sql); + ByteBuffer result; + try { + result = duckdb_v2_statement_execute(connHandle, statement, null); + } finally { + duckdb_v2_sql_statement_destroy(statement); + } + try { + int row = rows.nextSetBit(0); + ByteBuffer values; + while ((values = duckdb_v2_result_fetch_chunk(result)) != null) { + try { + long size = duckdb_data_chunk_get_size(values); + ByteBuffer valuesVec = duckdb_data_chunk_get_vector(values, 0); + for (long i = 0; i < size && row >= 0; i++) { + ByteBuffer value = duckdb_v2_vector_get_value(valuesVec, i); + try { + duckdb_v2_vector_set_value(vec, row, value); + } finally { + duckdb_v2_value_destroy(value); + } + row = rows.nextSetBit(row + 1); + } + } finally { + duckdb_destroy_data_chunk(values); + } + } + if (row >= 0) { + throw new SQLException("Invalid Input Error: cannot evaluate the default value of the column " + + quoteIdentifier(names[col])); + } + } finally { + duckdb_v2_result_destroy(result); + } + } finally { + conn.queryGate.release(); + } + } + + /** + * Returns the columns of the chunk that are left out of the INSERT: the ones that have the default value in all + * the rows. The default values of the other columns are written to the chunk. + */ + private BitSet resolveDefaults(ByteBuffer chunk) throws SQLException { + BitSet omitted = new BitSet(); + if (!hasDefaultRows || chunk != defaultsChunk) { + return omitted; + } + int rowCount = (int) duckdb_data_chunk_get_size(chunk); + try { + for (int col = 0; col < types.length; col++) { + BitSet rows = defaultRows[col]; + // the rows of a column without a default value are NULL already + if (rows == null || !hasDefault[col]) { + continue; + } + // the rows that are not completed are not appended + rows.clear(rowCount, Math.max(rowCount, rows.length())); + int count = rows.cardinality(); + if (count == 0) { + continue; + } + // the INSERT needs at least one column + if (count == rowCount && omitted.cardinality() + 1 < types.length) { + omitted.set(col); + } else { + writeDefaults(defaultsVector(chunk, col), col, rows, count); + } + } + } finally { + clearDefaultRows(); + } + return omitted; + } + + // --------------------------------------------------------------------------------------------------------- + // Appending + // --------------------------------------------------------------------------------------------------------- + /** Appends the chunk (that is borrowed for the call) to the buffer, returns 0 on success. */ int appendChunk(ByteBuffer chunk) { try { + BitSet omitted = resolveDefaults(chunk); + if (!omitted.equals(bufferedOmitted)) { + // the buffered rows are inserted with other columns + if (duckdb_v2_column_data_collection_row_count(collection) > 0) { + flushBuffer(); + } + bufferedOmitted = omitted; + } duckdb_v2_column_data_collection_append(collection, appendState, chunk); return 0; } catch (SQLException e) { @@ -209,16 +414,51 @@ private void resetBuffer() throws SQLException { appendState = duckdb_v2_column_data_collection_append_state_create(collection); } - /** Appends the buffered rows to the table, returns 0 on success. */ - int flush() { - try { - if (duckdb_v2_column_data_collection_row_count(collection) == 0) { - return 0; + // The INSERT of the buffered rows without the omitted columns, that are filled by the engine + private Insert insert(BitSet omitted) throws SQLException { + Insert insert = inserts.get(omitted); + if (insert != null) { + return insert; + } + StringBuilder columns = new StringBuilder(); + for (int i = 0; i < names.length; i++) { + if (omitted.get(i)) { + continue; + } + if (columns.length() > 0) { + columns.append(", "); } + columns.append(quoteIdentifier(names[i])); + } + String sql = "INSERT INTO " + qualifiedName + " (" + columns + ") SELECT " + columns + " FROM " + + new String(BUFFER_NAME, UTF_8); + byte[][] nameBytes = new byte[names.length][]; + for (int i = 0; i < names.length; i++) { + nameBytes[i] = names[i].getBytes(UTF_8); + } + ByteBuffer statement = DuckDBCore.parseSingleStatement(conn.connRef, sql); + try { + duckdb_v2_statement_add_collection(statement, BUFFER_NAME, collection, nameBytes); + } catch (SQLException e) { + duckdb_v2_sql_statement_destroy(statement); + throw e; + } + insert = new Insert(statement); + inserts.put((BitSet) omitted.clone(), insert); + return insert; + } + + // Appends the buffered rows to the table, the rows are dropped when they cannot be appended + private void flushBuffer() throws SQLException { + try { conn.queryGate.acquireUninterruptibly(); try { - ByteBuffer connHandle = conn.connRef; - ByteBuffer result = duckdb_v2_statement_execute(connHandle, statement, null); + Insert insert = insert(bufferedOmitted); + if (insert.prepared == null) { + // the statement is planned once, every execution reads the rows that are buffered then + insert.prepared = duckdb_v2_prepared_statement_create(conn.connRef, insert.statement, false); + } + ByteBuffer result = duckdb_v2_prepared_statement_execute(insert.prepared, null); try { duckdb_v2_result_drain(result); } finally { @@ -227,77 +467,57 @@ int flush() { } finally { conn.queryGate.release(); } - resetBuffer(); - return 0; } catch (SQLException e) { - int state = fail(e); try { // a failed flush drops the rows, a retry must not run the same failing statement over them resetBuffer(); } catch (SQLException ignored) { // nothing else can be done } - return state; + throw e; } + resetBuffer(); } - int close() { - return flush(); - } - - /** Appends the default value of the column to the row of the chunk, returns 0 on success. */ - int appendDefaultToChunk(ByteBuffer chunk, long col, long row) { + /** Appends the buffered rows to the table, returns 0 on success. */ + int flush() { try { - if (defaults == null) { - // The default values of all columns of the table, in the order of the columns. The table is looked - // up by its resolved name, that has the casing that the table was created with: the tables with the - // same name in the other schemas and catalogs are not matched. - String sql = "SELECT column_default FROM duckdb_columns() WHERE database_name = " + - quoteLiteral(resolvedName[0]) + " AND schema_name = " + quoteLiteral(resolvedName[1]) + - " AND table_name = " + quoteLiteral(resolvedName[2]) + " ORDER BY column_index"; - defaults = DuckDBCore.queryStrings(conn, sql); - } - ByteBuffer vec = duckdb_data_chunk_get_vector(chunk, col); - // the size of the vector is set by the caller when the chunk is complete - if (duckdb_v2_vector_get_size(vec) <= row) { - duckdb_v2_vector_set_size(vec, row + 1); - } - int tableColumn = col >= 0 && col < tableColumns.length ? tableColumns[(int) col] : -1; - String defaultSql = tableColumn >= 0 && tableColumn < defaults.size() ? defaults.get(tableColumn) : null; - ByteBuffer value; - if (defaultSql != null) { - // the default value is an expression, that is evaluated every time as it can be volatile - value = DuckDBCore.queryValue(conn, "SELECT " + defaultSql); - } else { - // a column without a default value gets the NULL default - value = DuckDBCore.nullValue(duckdb_v2_connection_get_factory(conn.connRef)); - } - try { - duckdb_v2_vector_set_value(vec, row, value); - } finally { - duckdb_v2_value_destroy(value); + if (duckdb_v2_column_data_collection_row_count(collection) == 0) { + return 0; } + flushBuffer(); return 0; } catch (SQLException e) { return fail(e); } } + int close() { + return flush(); + } + /** Releases the resources of the appender, the buffered rows are not appended. */ void destroy() { try { + for (Insert insert : inserts.values()) { + if (insert.prepared != null) { + duckdb_v2_prepared_statement_destroy(insert.prepared); + } + duckdb_v2_sql_statement_destroy(insert.statement); + } + inserts.clear(); if (appendState != null) { duckdb_v2_column_data_collection_append_state_destroy(appendState); appendState = null; } - if (statement != null) { - duckdb_v2_sql_statement_destroy(statement); - statement = null; - } if (collection != null) { duckdb_v2_column_data_collection_destroy(collection); collection = null; } + if (nullValue != null) { + duckdb_v2_value_destroy(nullValue); + nullValue = null; + } } catch (SQLException e) { // nothing else can be done } diff --git a/src/test/java/org/duckdb/TestAppender.java b/src/test/java/org/duckdb/TestAppender.java index 7d9d8b30f..636df22ee 100644 --- a/src/test/java/org/duckdb/TestAppender.java +++ b/src/test/java/org/duckdb/TestAppender.java @@ -145,6 +145,173 @@ public static void test_appender_default_same_table_name() throws Exception { } } + public static void test_appender_default_all_rows() throws Exception { + try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); + Statement stmt = conn.createStatement()) { + + stmt.execute("CREATE TABLE tab1(col1 INTEGER DEFAULT 42, col2 VARCHAR DEFAULT 'foo', col3 INTEGER, " + + "col4 VARCHAR DEFAULT 'bar')"); + // more rows than a chunk has + int count = (1 << 12) + 7; + try (DuckDBAppender appender = conn.createAppender("tab1")) { + for (int i = 0; i < count; i++) { + // col1 and col2 have the default values in all the rows, col3 has the NULL default + appender.beginRow().appendDefault().appendDefault(); + if (i % 2 == 0) { + appender.append(i); + } else { + appender.appendDefault(); + } + appender.append("row" + i).endRow(); + } + appender.flush(); + // all the columns have the default values + appender.beginRow().appendDefault().appendDefault().appendDefault().appendDefault().endRow(); + appender.beginRow().appendDefault().appendDefault().appendDefault().appendDefault().endRow(); + assertEquals(appender.flush(), 2L); + } + + try (ResultSet rs = stmt.executeQuery( + "SELECT count(*), count(*) FILTER (col1 = 42 AND col2 = 'foo'), count(col3), sum(col3), " + + "count(*) FILTER (col4 = 'bar'), count(DISTINCT col4) FROM tab1")) { + assertTrue(rs.next()); + assertEquals(rs.getLong(1), count + 2L); + assertEquals(rs.getLong(2), count + 2L); + long evenCount = (count + 1) / 2; + assertEquals(rs.getLong(3), evenCount); + assertEquals(rs.getLong(4), evenCount * (evenCount - 1)); + assertEquals(rs.getLong(5), 2L); + assertEquals(rs.getLong(6), count + 1L); + assertFalse(rs.next()); + } + } + } + + public static void test_appender_default_some_rows() throws Exception { + try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); + Statement stmt = conn.createStatement()) { + + stmt.execute("CREATE TABLE tab1(id INTEGER, col1 INTEGER DEFAULT 42, col2 VARCHAR DEFAULT 'foo', " + + "col3 VARCHAR[] DEFAULT ['bar', 'baz'], col4 DECIMAL(10,2) DEFAULT 1.5)"); + int count = (1 << 11) + 100; + try (DuckDBAppender appender = conn.createAppender("tab1")) { + for (int i = 0; i < count; i++) { + appender.beginRow().append(i); + if (i % 3 == 0) { + appender.appendDefault(); + } else { + appender.append(i); + } + if (i % 5 == 0) { + appender.append("row" + i); + } else { + appender.appendDefault(); + } + if (i % 2 == 0) { + appender.appendDefault(); + } else { + appender.appendNull(); + } + if (i == 7) { + appender.append(new BigDecimal("7.25")); + } else { + appender.appendDefault(); + } + appender.endRow(); + } + } + + try (ResultSet rs = stmt.executeQuery("SELECT id, col1, col2, col3::VARCHAR, col4 FROM tab1 ORDER BY id")) { + for (int i = 0; i < count; i++) { + assertTrue(rs.next()); + assertEquals(rs.getInt(1), i); + assertEquals(rs.getInt(2), i % 3 == 0 ? 42 : i); + assertEquals(rs.getString(3), i % 5 == 0 ? "row" + i : "foo"); + assertEquals(rs.getString(4), i % 2 == 0 ? "[bar, baz]" : null); + assertEquals(rs.getBigDecimal(5), new BigDecimal(i == 7 ? "7.25" : "1.50")); + } + assertFalse(rs.next()); + } + } + } + + public static void test_appender_default_volatile() throws Exception { + try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); + Statement stmt = conn.createStatement()) { + + stmt.execute("CREATE SEQUENCE seq1"); + stmt.execute("CREATE TABLE tab1(id BIGINT DEFAULT nextval('seq1'), col1 VARCHAR, " + + "col2 UUID DEFAULT uuid(), col3 TIMESTAMP DEFAULT now())"); + int count = (1 << 11) + 100; + try (DuckDBAppender appender = conn.createAppender("tab1")) { + // the default values are evaluated for every row + for (int i = 0; i < count; i++) { + appender.beginRow().appendDefault().append("all").appendDefault().appendDefault().endRow(); + } + appender.flush(); + // also when only some of the rows have them + for (int i = 0; i < count; i++) { + appender.beginRow(); + if (i % 2 == 0) { + appender.appendDefault(); + } else { + appender.append(-1L - i); + } + appender.append("some").appendDefault().appendDefault().endRow(); + } + appender.flush(); + } + + try (ResultSet rs = stmt.executeQuery( + "SELECT col1, count(*), count(DISTINCT id), min(id), max(id), count(DISTINCT col2), " + + "count(col3) FROM tab1 GROUP BY col1 ORDER BY col1")) { + assertTrue(rs.next()); + assertEquals(rs.getString(1), "all"); + assertEquals(rs.getLong(2), (long) count); + assertEquals(rs.getLong(3), (long) count); + assertEquals(rs.getLong(4), 1L); + assertEquals(rs.getLong(5), (long) count); + assertEquals(rs.getLong(6), (long) count); + assertEquals(rs.getLong(7), (long) count); + assertTrue(rs.next()); + assertEquals(rs.getString(1), "some"); + assertEquals(rs.getLong(2), (long) count); + assertEquals(rs.getLong(3), (long) count); + assertEquals(rs.getLong(4), (long) -count); + assertEquals(rs.getLong(5), count + count / 2L); + assertEquals(rs.getLong(6), (long) count); + assertEquals(rs.getLong(7), (long) count); + assertFalse(rs.next()); + } + } + } + + public static void test_appender_default_not_null() throws Exception { + try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); + Statement stmt = conn.createStatement()) { + + stmt.execute("CREATE TABLE tab1(col1 INTEGER NOT NULL, col2 VARCHAR DEFAULT 'foo')"); + // the column has no default value + DuckDBAppender appender = conn.createAppender("tab1"); + appender.beginRow().appendDefault().appendDefault().endRow(); + String message = assertThrows(appender::flush, SQLException.class); + assertTrue(message.contains("NOT NULL constraint failed"), message); + appender.close(); + + try (DuckDBAppender appender2 = conn.createAppender("tab1")) { + appender2.beginRow().append(42).appendDefault().endRow(); + assertEquals(appender2.flush(), 1L); + } + + try (ResultSet rs = stmt.executeQuery("SELECT col1, col2 FROM tab1")) { + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 42); + assertEquals(rs.getString(2), "foo"); + assertFalse(rs.next()); + } + } + } + public static void test_appender_generated_column() throws Exception { try (DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); Statement stmt = conn.createStatement()) { From 0c99becd67b74e4fcdbc7023425c4564fcb1c7c5 Mon Sep 17 00:00:00 2001 From: Alex Kasko Date: Wed, 2 Dec 2026 11:44:44 +0000 Subject: [PATCH 17/21] Copy the data of the nested values of a VARIANT The value of a VARIANT is read through a temporary vector of one row, that is destroyed when the value is read. Only the data of the top-level vector was copied, the vectors of the elements of a LIST, an ARRAY or a STRUCT value kept pointing to the released memory: reading them later, e.g. with Array#getResultSet, was a use-after-free. The data of all the vectors that are created for the value is copied now. --- src/main/java/org/duckdb/DuckDBCore.java | 40 +++++++---- src/test/java/org/duckdb/TestVariant.java | 84 +++++++++++++++++++++++ 2 files changed, 110 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/duckdb/DuckDBCore.java b/src/main/java/org/duckdb/DuckDBCore.java index 732b41434..b85c91162 100644 --- a/src/main/java/org/duckdb/DuckDBCore.java +++ b/src/main/java/org/duckdb/DuckDBCore.java @@ -1022,7 +1022,7 @@ static DuckDBVector[] fetch(ResultRef ref) throws SQLException { ref.detailCache = new String[columnCount]; } vectors[col] = processVector(factory, duckdb_data_chunk_get_vector(chunk, col), rowCount, ref.detailCache, - col, ref.typeIds); + col, ref.typeIds, false); } return vectors; } @@ -1135,12 +1135,15 @@ private static int fixedWidth(int typeId, ByteBuffer type) throws SQLException { } static DuckDBVector processVector(ByteBuffer factory, ByteBuffer vec, int rowCount) throws SQLException { - return processVector(factory, vec, rowCount, null, 0, null); + return processVector(factory, vec, rowCount, null, 0, null, false); } - // The details of the types of the columns are cached in the array if it is given + /** + * The details of the types of the columns are cached in the array if it is given. The fixed-width values are read + * from the memory of the vector: when the vector does not outlive the returned one, they are copied (retain). + */ private static DuckDBVector processVector(ByteBuffer factory, ByteBuffer vec, int rowCount, String[] details, - int detailIdx, int[] typeIds) throws SQLException { + int detailIdx, int[] typeIds, boolean retain) throws SQLException { duckdb_v2_vector_flatten(vec); if (typeIds != null && details != null && details[detailIdx] != null) { // the type of the column is known from the previous chunks, no need to read it @@ -1151,6 +1154,9 @@ private static DuckDBVector processVector(ByteBuffer factory, ByteBuffer vec, in DuckDBVector jvec = new DuckDBVector(details[detailIdx], rowCount, nulls); if (width > 0) { jvec.constlen_data = duckdb_vector_get_data(vec, (long) rowCount * width); + if (retain) { + jvec.retainConstlenData(); + } } else if (id == TYPE_DECIMAL) { jvec.varlen_data = readWideDecimals(vec, nulls, rowCount); } else if (id == TYPE_VARCHAR) { @@ -1181,6 +1187,9 @@ private static DuckDBVector processVector(ByteBuffer factory, ByteBuffer vec, in int width = fixedWidth(typeId, type); if (width > 0) { jvec.constlen_data = duckdb_vector_get_data(vec, (long) rowCount * width); + if (retain) { + jvec.retainConstlenData(); + } return jvec; } @@ -1190,7 +1199,7 @@ private static DuckDBVector processVector(ByteBuffer factory, ByteBuffer vec, in return jvec; case TYPE_STRUCT: case TYPE_UNION: - processStruct(factory, vec, type, jvec, rowCount); + processStruct(factory, vec, type, jvec, rowCount, retain); return jvec; case TYPE_BLOB: case TYPE_GEOMETRY: { @@ -1201,8 +1210,8 @@ private static DuckDBVector processVector(ByteBuffer factory, ByteBuffer vec, in } case TYPE_ARRAY: { int size = (int) duckdb_array_type_array_size(type); - DuckDBVector child = - processVector(factory, duckdb_array_vector_get_child(vec), Math.multiplyExact(rowCount, size)); + DuckDBVector child = processVector(factory, duckdb_array_vector_get_child(vec), + Math.multiplyExact(rowCount, size), null, 0, null, retain); DuckDBArray[] arrays = new DuckDBArray[rowCount]; for (int row = 0; row < rowCount; row++) { if (!nulls[row]) { @@ -1216,7 +1225,8 @@ private static DuckDBVector processVector(ByteBuffer factory, ByteBuffer vec, in case TYPE_LIST: { ByteBuffer entries = duckdb_vector_get_data(vec, (long) rowCount * 16).order(NATIVE_ORDER); int listSize = (int) duckdb_list_vector_get_size(vec); - DuckDBVector child = processVector(factory, duckdb_list_vector_get_child(vec), listSize); + DuckDBVector child = + processVector(factory, duckdb_list_vector_get_child(vec), listSize, null, 0, null, retain); DuckDBArray[] arrays = new DuckDBArray[rowCount]; for (int row = 0; row < rowCount; row++) { if (!nulls[row]) { @@ -1348,12 +1358,13 @@ private static String[] castToStrings(ByteBuffer factory, ByteBuffer vec, int ro } private static void processStruct(ByteBuffer factory, ByteBuffer vec, ByteBuffer type, DuckDBVector jvec, - int rowCount) throws SQLException { + int rowCount, boolean retain) throws SQLException { int childCount = (int) duckdb_struct_type_child_count(type); DuckDBVector[] columns = new DuckDBVector[childCount]; String[] names = new String[childCount]; for (int i = 0; i < childCount; i++) { - columns[i] = processVector(factory, duckdb_struct_vector_get_child(vec, i), rowCount); + columns[i] = + processVector(factory, duckdb_struct_vector_get_child(vec, i), rowCount, null, 0, null, retain); byte[] name = duckdb_struct_type_child_name(type, i); // the members of a TUPLE are unnamed, use the positional names: "element1", "element2", ... names[i] = name == null || name.length == 0 ? "element" + (i + 1) : new String(name, UTF_8); @@ -1366,7 +1377,10 @@ private static void processStruct(ByteBuffer factory, ByteBuffer vec, ByteBuffer jvec.varlen_data = structs; } - // The value of a VARIANT is read as a vector of one row of the type of the value + /** + * The value of a VARIANT is read as a vector of one row of the type of the value. The vector is destroyed here, so + * the returned vector and the vectors of its nested values keep copies of their values. + */ private static DuckDBVector variantToVector(ByteBuffer factory, ByteBuffer vec, int row) throws SQLException { ByteBuffer variant = duckdb_v2_vector_get_value(vec, row); ByteBuffer value = null; @@ -1381,9 +1395,7 @@ private static DuckDBVector variantToVector(ByteBuffer factory, ByteBuffer vec, single = duckdb_create_vector(type); duckdb_v2_vector_set_size(single, 1); duckdb_v2_vector_set_value(single, 0, value); - DuckDBVector res = processVector(factory, single, 1); - res.retainConstlenData(); - return res; + return processVector(factory, single, 1, null, 0, null, true); } finally { if (single != null) { duckdb_destroy_vector(single); diff --git a/src/test/java/org/duckdb/TestVariant.java b/src/test/java/org/duckdb/TestVariant.java index de88e0e7a..2845f6c5e 100644 --- a/src/test/java/org/duckdb/TestVariant.java +++ b/src/test/java/org/duckdb/TestVariant.java @@ -201,6 +201,90 @@ public static void test_variant_list_of_variants() throws Exception { } } + // The nested values of many rows are read from the vectors that are created for the values of the variants, + // they must not be read from the memory of these vectors that is released (and reused by the next rows). + // Array#getArray returns the values that are read when the row is fetched, Array#getResultSet reads them later. + public static void test_variant_nested_many_rows() throws Exception { + int count = 5000; + try (Connection conn = DriverManager.getConnection(JDBC_URL); Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery( + "SELECT [i, i + 1, i + 2]::BIGINT[]::VARIANT AS col1, " + + "[i, i * 2]::INTEGER[2]::VARIANT AS col2, " + + "{'a': i, 'b': i::DOUBLE / 2, 'c': [i::HUGEINT, NULL], 'd': {'e': i::SMALLINT}}::VARIANT AS col3, " + + "[{'f': i::DECIMAL(18,3), 'g': [i::UBIGINT]}]::VARIANT AS col4, " + + "MAP {i: DATE '1970-01-01' + i::INTEGER}::VARIANT AS col5 " + + "FROM range(" + count + ") t(i) ORDER BY i")) { + // the values are read when all the rows of the chunk are fetched + for (long i = 0; i < count; i++) { + assertTrue(rs.next()); + Array listWrapper = (Array) rs.getObject(1); + Object[] list = (Object[]) listWrapper.getArray(); + assertEquals(list.length, 3); + assertEquals(list[0], i); + assertEquals(list[1], i + 1); + assertEquals(list[2], i + 2); + try (ResultSet elements = listWrapper.getResultSet()) { + for (int j = 0; j < 3; j++) { + assertTrue(elements.next()); + assertEquals(elements.getLong(2), i + j); + } + assertFalse(elements.next()); + } + + Array arrayWrapper = (Array) rs.getObject(2); + Object[] array = (Object[]) arrayWrapper.getArray(); + assertEquals(array.length, 2); + assertEquals(array[0], (int) i); + assertEquals(array[1], (int) i * 2); + try (ResultSet elements = arrayWrapper.getResultSet()) { + assertTrue(elements.next()); + assertEquals(elements.getInt(2), (int) i); + assertTrue(elements.next()); + assertEquals(elements.getInt(2), (int) i * 2); + assertFalse(elements.next()); + } + + Map struct = ((DuckDBStruct) rs.getObject(3)).getMap(); + assertEquals(struct.size(), 4); + assertEquals(struct.get("a"), i); + assertEquals(struct.get("b"), i / 2.0); + Object[] nestedList = (Object[]) ((Array) struct.get("c")).getArray(); + assertEquals(nestedList.length, 2); + assertEquals(nestedList[0], BigInteger.valueOf(i)); + assertNull(nestedList[1]); + try (ResultSet elements = ((Array) struct.get("c")).getResultSet()) { + assertTrue(elements.next()); + assertEquals(elements.getObject(2), BigInteger.valueOf(i)); + assertTrue(elements.next()); + assertNull(elements.getObject(2)); + assertFalse(elements.next()); + } + Map nestedStruct = ((DuckDBStruct) struct.get("d")).getMap(); + assertEquals(nestedStruct.get("e"), (short) i); + + Object[] structList = (Object[]) ((Array) rs.getObject(4)).getArray(); + assertEquals(structList.length, 1); + Map listStruct = ((DuckDBStruct) structList[0]).getMap(); + assertEquals(listStruct.get("f"), new BigDecimal(BigInteger.valueOf(i * 1000), 3)); + Object[] innerList = (Object[]) ((Array) listStruct.get("g")).getArray(); + assertEquals(innerList.length, 1); + assertEquals(innerList[0], BigInteger.valueOf(i)); + try (ResultSet elements = ((Array) listStruct.get("g")).getResultSet()) { + assertTrue(elements.next()); + assertEquals(elements.getObject(2), BigInteger.valueOf(i)); + assertFalse(elements.next()); + } + + Object[] entries = (Object[]) ((Array) rs.getObject(5)).getArray(); + assertEquals(entries.length, 1); + Map entry = ((DuckDBStruct) entries[0]).getMap(); + assertEquals(entry.get("key"), i); + assertEquals(entry.get("value"), java.time.LocalDate.ofEpochDay(i)); + } + assertFalse(rs.next()); + } + } + public static void test_variant_map() throws Exception { try (Connection conn = DriverManager.getConnection(JDBC_URL); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT MAP {'foo': 41, 'bar': 42}::VARIANT AS col1")) { From abd2c4d133fdb1722c9059ae77daba8dadd3e505 Mon Sep 17 00:00:00 2001 From: Alex Kasko Date: Wed, 2 Dec 2026 11:48:27 +0000 Subject: [PATCH 18/21] Read the current schema and catalog without running a query getSchema and getCatalog ran SELECT current_schema() and SELECT current_database() on the connection of the user. With jdbc_stream_results=true that failed while a result was streamed, and in an aborted transaction it failed with 'Current transaction is aborted'. The schema and the catalog are read from the 'schema' and 'search_path' settings of the session now, that does not run anything on the connection. When the search path has no catalog, the default database of the instance is used, it is read once with a connection of its own. setSchema and setCatalog still run a statement: the catalog entries are looked up in a transaction when the search path is set. They set the same search path entries as before the port: the schema name is not split at the dots, and the catalog is set with its default schema. --- src/main/java/org/duckdb/DuckDBCore.java | 128 +++++++++++++----- src/main/java/org/duckdb/DuckDBInstances.java | 21 +++ src/test/java/org/duckdb/TestDuckDBJDBC.java | 98 ++++++++++++++ 3 files changed, 216 insertions(+), 31 deletions(-) diff --git a/src/main/java/org/duckdb/DuckDBCore.java b/src/main/java/org/duckdb/DuckDBCore.java index b85c91162..40bc7bb5e 100644 --- a/src/main/java/org/duckdb/DuckDBCore.java +++ b/src/main/java/org/duckdb/DuckDBCore.java @@ -75,6 +75,8 @@ private DuckDBCore() { private static final byte[] STREAM_RESULTS_OPTION = "jdbc_stream_results".getBytes(UTF_8); private static final byte[] MAX_DECIMAL_WIDTH_OPTION = "max_decimal_width".getBytes(UTF_8); + private static final byte[] SCHEMA_OPTION = "schema".getBytes(UTF_8); + private static final byte[] SEARCH_PATH_OPTION = "search_path".getBytes(UTF_8); // The widest DECIMAL that is stored as a fixed-size integer, wider decimals are stored as BIGNUM blobs private static final int MAX_FIXED_SIZE_DECIMAL_WIDTH = 38; @@ -380,34 +382,38 @@ static ByteBuffer parseSingleStatement(ByteBuffer conn, String sql) throws SQLEx static List queryStrings(DuckDBConnection connection, String sql) throws SQLException { connection.queryGate.acquireUninterruptibly(); try { - ByteBuffer conn = conn(connection.connRef); - ByteBuffer statement = parseSingleStatement(conn, sql); - ByteBuffer result; - try { - result = duckdb_v2_statement_execute(conn, statement, null); - } finally { - duckdb_v2_sql_statement_destroy(statement); - } - try { - List res = new ArrayList<>(); - ByteBuffer chunk; - while ((chunk = duckdb_v2_result_fetch_chunk(result)) != null) { - try { - int rowCount = (int) duckdb_data_chunk_get_size(chunk); - ByteBuffer vec = duckdb_data_chunk_get_vector(chunk, 0); - for (int row = 0; row < rowCount; row++) { - res.add(valueToString(vec, row)); - } - } finally { - duckdb_destroy_data_chunk(chunk); + return queryStrings(conn(connection.connRef), sql); + } finally { + connection.queryGate.release(); + } + } + + /** Runs the query on the connection that is not used by anything else. */ + static List queryStrings(ByteBuffer conn, String sql) throws SQLException { + ByteBuffer statement = parseSingleStatement(conn, sql); + ByteBuffer result; + try { + result = duckdb_v2_statement_execute(conn, statement, null); + } finally { + duckdb_v2_sql_statement_destroy(statement); + } + try { + List res = new ArrayList<>(); + ByteBuffer chunk; + while ((chunk = duckdb_v2_result_fetch_chunk(result)) != null) { + try { + int rowCount = (int) duckdb_data_chunk_get_size(chunk); + ByteBuffer vec = duckdb_data_chunk_get_vector(chunk, 0); + for (int row = 0; row < rowCount; row++) { + res.add(valueToString(vec, row)); } + } finally { + duckdb_destroy_data_chunk(chunk); } - return res; - } finally { - duckdb_v2_result_destroy(result); } + return res; } finally { - connection.queryGate.release(); + duckdb_v2_result_destroy(result); } } @@ -433,25 +439,85 @@ static void executeSql(DuckDBConnection connection, String sql) throws SQLExcept } } - private static String queryString(DuckDBConnection connection, String sql) throws SQLException { - List res = queryStrings(connection, sql); - return res.isEmpty() ? null : res.get(0); + // The text of a setting of the session, it is read without running a query on the connection + private static String sessionOption(DuckDBConnection connection, byte[] name) throws SQLException { + conn(connection.connRef); + ByteBuffer value = duckdb_v2_config_get_option_value(connection.config(), name); + try { + return new String(duckdb_v2_value_to_string(value), UTF_8); + } finally { + duckdb_v2_value_destroy(value); + } } + /** + * Returns the parts of the first entry of a search path like {@code db1."my.schema",db2.main}. The parts are + * separated with dots and are quoted when they have a dot, a comma or a quote in them. + */ + static List firstSearchPathEntry(String path) { + List parts = new ArrayList<>(); + StringBuilder part = new StringBuilder(); + boolean quoted = false; + for (int i = 0; i < path.length(); i++) { + char c = path.charAt(i); + if (quoted) { + if (c != '"') { + part.append(c); + } else if (i + 1 < path.length() && path.charAt(i + 1) == '"') { + // an escaped quote + part.append(c); + i++; + } else { + quoted = false; + } + } else if (c == '"') { + quoted = true; + } else if (c == '.') { + parts.add(part.toString()); + part.setLength(0); + } else if (c == ',') { + break; + } else { + part.append(c); + } + } + if (part.length() > 0 || !parts.isEmpty()) { + parts.add(part.toString()); + } + return parts; + } + + /* + * The current schema and catalog are read from the settings of the session and not with a query: a query cannot + * run in a transaction that is aborted, and it closes the result that is streamed on the connection. + */ + static String getSchema(DuckDBConnection connection) throws SQLException { - return queryString(connection, "SELECT current_schema()"); + // the schema of the first entry of the search path + List entry = firstSearchPathEntry(sessionOption(connection, SCHEMA_OPTION)); + return entry.isEmpty() ? null : entry.get(entry.size() - 1); } static String getCatalog(DuckDBConnection connection) throws SQLException { - return queryString(connection, "SELECT current_database()"); + List entry = firstSearchPathEntry(sessionOption(connection, SEARCH_PATH_OPTION)); + if (entry.size() > 1) { + return entry.get(0); + } + // the search path has no catalog until it is set with a catalog, e.g. by USE + return connection.instanceRef.defaultDatabase(); } + // The catalog of the schema is looked up in a transaction, so the search path is set with a statement + static void setSchema(DuckDBConnection connection, String schema) throws SQLException { - executeSql(connection, "SET schema = " + DuckDBV2Appender.quoteLiteral(schema)); + // the name is quoted, it is not split into a catalog and a schema + executeSql(connection, + "SET schema = " + DuckDBV2Appender.quoteLiteral(DuckDBV2Appender.quoteIdentifier(schema))); } static void setCatalog(DuckDBConnection connection, String catalog) throws SQLException { - executeSql(connection, "USE " + DuckDBV2Appender.quoteIdentifier(catalog)); + executeSql(connection, "USE " + DuckDBV2Appender.quoteIdentifier(catalog) + "." + + DuckDBV2Appender.quoteIdentifier(DuckDBConnection.DEFAULT_SCHEMA)); } // --------------------------------------------------------------------------------------------------------- diff --git a/src/main/java/org/duckdb/DuckDBInstances.java b/src/main/java/org/duckdb/DuckDBInstances.java index 8d9ad65a6..771d28d89 100644 --- a/src/main/java/org/duckdb/DuckDBInstances.java +++ b/src/main/java/org/duckdb/DuckDBInstances.java @@ -51,6 +51,7 @@ static final class InstanceRef { private int refs = 1; private final ByteBuffer environment; private ByteBuffer instance; + private String defaultDatabase; final long address; private InstanceRef(ByteBuffer environment, ByteBuffer instance, long address) { @@ -71,6 +72,26 @@ ByteBuffer instance() { return instance; } + /** + * The database that the connections to the instance use when their search path has no catalog. It is read + * with a connection of its own, so that nothing is run on the connections of the user. + */ + synchronized String defaultDatabase() throws SQLException { + if (defaultDatabase == null) { + if (instance == null) { + throw new SQLException("The instance is destroyed"); + } + ByteBuffer conn = duckdb_v2_connection_create(instance); + try { + List res = DuckDBCore.queryStrings(conn, "SELECT current_database()"); + defaultDatabase = res.isEmpty() ? null : res.get(0); + } finally { + duckdb_v2_connection_destroy(conn); + } + } + return defaultDatabase; + } + void release() { ByteBuffer toDestroy = null; synchronized (this) { diff --git a/src/test/java/org/duckdb/TestDuckDBJDBC.java b/src/test/java/org/duckdb/TestDuckDBJDBC.java index 561002a2b..51a4b5de9 100644 --- a/src/test/java/org/duckdb/TestDuckDBJDBC.java +++ b/src/test/java/org/duckdb/TestDuckDBJDBC.java @@ -873,6 +873,104 @@ public static void test_uuid() throws Exception { } } + public static void test_search_path_entry() throws Exception { + assertEquals(DuckDBCore.firstSearchPathEntry(""), emptyList()); + assertEquals(DuckDBCore.firstSearchPathEntry("main"), singletonList("main")); + assertEquals(DuckDBCore.firstSearchPathEntry("db1.main"), asList("db1", "main")); + assertEquals(DuckDBCore.firstSearchPathEntry("db1.main,db2.sch2"), asList("db1", "main")); + assertEquals(DuckDBCore.firstSearchPathEntry("\"my.db\".\"my,schema\",db2.sch2"), asList("my.db", "my,schema")); + assertEquals(DuckDBCore.firstSearchPathEntry("\"my\"\"schema\""), singletonList("my\"schema")); + } + + public static void test_get_set_schema_catalog_quoted_names() throws Exception { + try (Connection conn = DriverManager.getConnection(JDBC_URL); Statement stmt = conn.createStatement()) { + String catalog = conn.getCatalog(); + stmt.execute("CREATE SCHEMA \"my.schema\""); + stmt.execute("CREATE SCHEMA \"my\"\"other,schema\""); + stmt.execute("ATTACH ':memory:' AS \"my.db\""); + stmt.execute("CREATE SCHEMA \"my.db\".sch1"); + + // the name of the schema is not split into a catalog and a schema + conn.setSchema("my.schema"); + assertEquals(conn.getSchema(), "my.schema"); + assertEquals(conn.getCatalog(), catalog); + conn.setSchema("my\"other,schema"); + assertEquals(conn.getSchema(), "my\"other,schema"); + assertEquals(conn.getCatalog(), catalog); + assertThrows(() -> conn.setSchema("sch1"), SQLException.class); + assertEquals(conn.getSchema(), "my\"other,schema"); + + conn.setCatalog("my.db"); + assertEquals(conn.getCatalog(), "my.db"); + assertEquals(conn.getSchema(), DuckDBConnection.DEFAULT_SCHEMA); + conn.setSchema("sch1"); + assertEquals(conn.getCatalog(), "my.db"); + assertEquals(conn.getSchema(), "sch1"); + + stmt.execute("USE " + catalog + ".\"my.schema\""); + assertEquals(conn.getCatalog(), catalog); + assertEquals(conn.getSchema(), "my.schema"); + try (ResultSet rs = stmt.executeQuery("SELECT current_database(), current_schema()")) { + assertTrue(rs.next()); + assertEquals(rs.getString(1), catalog); + assertEquals(rs.getString(2), "my.schema"); + } + // a catalog that is not attached + assertThrows(() -> conn.setCatalog("sch1"), SQLException.class); + assertEquals(conn.getCatalog(), catalog); + } + } + + public static void test_get_schema_catalog_streaming_result() throws Exception { + Properties config = new Properties(); + config.put(JDBC_STREAM_RESULTS, true); + try (Connection conn = DriverManager.getConnection(JDBC_URL, config); Statement stmt = conn.createStatement()) { + stmt.execute("CREATE SCHEMA sch1"); + stmt.execute("SET schema = 'sch1'"); + long count = 100000; + try (ResultSet rs = stmt.executeQuery("SELECT i FROM range(" + count + ") t(i)")) { + assertTrue(rs.next()); + // the current schema and catalog are read without a query, the result that is streamed stays open + assertEquals(conn.getSchema(), "sch1"); + assertEquals(conn.getCatalog(), "memory"); + assertEquals(conn.getMetaData().getConnection().getSchema(), "sch1"); + long rows = 1; + long sum = rs.getLong(1); + while (rs.next()) { + rows++; + sum += rs.getLong(1); + } + assertEquals(rows, count); + assertEquals(sum, count * (count - 1) / 2); + } + } + } + + public static void test_get_schema_catalog_aborted_transaction() throws Exception { + try (Connection conn = DriverManager.getConnection(JDBC_URL)) { + try (Statement stmt = conn.createStatement()) { + stmt.execute("CREATE SCHEMA sch1"); + stmt.execute("CREATE TABLE tab1 (col1 INTEGER PRIMARY KEY)"); + stmt.execute("INSERT INTO tab1 VALUES (42)"); + stmt.execute("SET schema = 'sch1'"); + } + conn.setAutoCommit(false); + try (Statement stmt = conn.createStatement()) { + assertThrows(() -> stmt.execute("INSERT INTO main.tab1 VALUES (42)"), SQLException.class); + } + try (Statement stmt = conn.createStatement()) { + String message = assertThrows(() -> stmt.execute("SELECT 42"), SQLException.class); + assertTrue(message.contains("transaction is aborted"), message); + } + // no query is run to read the current schema and catalog + assertEquals(conn.getSchema(), "sch1"); + assertEquals(conn.getCatalog(), "memory"); + conn.rollback(); + assertEquals(conn.getSchema(), "sch1"); + assertEquals(conn.getCatalog(), "memory"); + } + } + public static void test_get_schema() throws Exception { DuckDBConnection conn = DriverManager.getConnection(JDBC_URL).unwrap(DuckDBConnection.class); From f53bb6b3e2683ae9f75ad28bfd97ee492a225596 Mon Sep 17 00:00:00 2001 From: Alex Kasko Date: Wed, 2 Dec 2026 11:50:44 +0000 Subject: [PATCH 19/21] Identify a cached instance by an id that is kept in the instance The dbAddress of a connection to a cached instance was the 32-bit hash code of the path of the database, so two databases could get the same address. The JFR memory monitor, that is keyed by the address, then reported the memory of one of them for both, and was stopped when the connections to one of them were closed. The address of a cached instance is an id that is stored in the object cache of the instance by its first handle, the other handles to the instance read it from there. The ids are unique in the process. --- duckdb_java.def | 2 + duckdb_java.exp | 2 + duckdb_java.map | 2 + src/jni/bindings_v2.cpp | 67 +++++++++++++++++++ src/main/java/org/duckdb/DuckDBBindings.java | 9 +++ src/main/java/org/duckdb/DuckDBInstances.java | 40 +++++++---- src/test/java/org/duckdb/TestDuckDBJDBC.java | 34 ++++++++++ 7 files changed, 144 insertions(+), 12 deletions(-) diff --git a/duckdb_java.def b/duckdb_java.def index 93dd55dfc..98aa613e3 100644 --- a/duckdb_java.def +++ b/duckdb_java.def @@ -179,6 +179,8 @@ Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1get_1type Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1to_1string Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1variant_1to_1value Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1cast +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1get_1object_1cache +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1object_1cache_1get_1or_1create Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1create Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1destroy Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1get_1part_1count diff --git a/duckdb_java.exp b/duckdb_java.exp index 1732a9630..089efcef8 100644 --- a/duckdb_java.exp +++ b/duckdb_java.exp @@ -176,6 +176,8 @@ _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1get_1type _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1to_1string _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1variant_1to_1value _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1cast +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1get_1object_1cache +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1object_1cache_1get_1or_1create _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1create _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1destroy _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1get_1part_1count diff --git a/duckdb_java.map b/duckdb_java.map index b5890a3eb..c6b30098c 100644 --- a/duckdb_java.map +++ b/duckdb_java.map @@ -178,6 +178,8 @@ DUCKDB_JAVA { Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1to_1string; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1variant_1to_1value; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1value_1cast; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1get_1object_1cache; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1object_1cache_1get_1or_1create; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1create; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1destroy; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1qname_1get_1part_1count; diff --git a/src/jni/bindings_v2.cpp b/src/jni/bindings_v2.cpp index 3ac03e240..83f9531ca 100644 --- a/src/jni/bindings_v2.cpp +++ b/src/jni/bindings_v2.cpp @@ -2150,3 +2150,70 @@ JNIEXPORT jboolean JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1column_1de CALL_V2(duckdb_v2_column_description_has_generated(column, &has_generated, ERR_OUT), JNI_FALSE); return has_generated ? JNI_TRUE : JNI_FALSE; } + +/* --- object cache --- */ + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_instance_get_object_cache + * Signature: (Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer; + */ +// The returned object cache is borrowed from the instance and must not be destroyed +JNIEXPORT jobject JNICALL +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1instance_1get_1object_1cache(JNIEnv *env, jclass, jobject instance_buf) { + CHECK_BUF_RET(instance, instance_buf, duckdb_v2_instance_handle, "instance", nullptr); + duckdb_v2_object_cache_handle cache = nullptr; + CALL_V2(duckdb_v2_instance_get_object_cache(instance, &cache, ERR_OUT), nullptr); + return make_ptr_buf(env, cache); +} + +// The data of a new entry is a copy of the bytes, the entry is pinned: it is kept for as long as the instance lives +static void object_cache_create_bytes(void *user_data, duckdb_v2_opaque *data, idx_t *size_bytes, + duckdb_v2_error_info_handle *) { + auto bytes = reinterpret_cast(user_data); + data->ptr = new std::string(*bytes); + data->destroy = [](void *ptr) { + delete reinterpret_cast(ptr); + }; + data->equals = nullptr; + *size_bytes = 0; +} + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_object_cache_get_or_create + * Signature: (Ljava/nio/ByteBuffer;[B[B[B)[B + */ +// Returns the bytes of the entry. The entry is created with the given bytes if there is none, only one of the +// concurrent calls creates it. +JNIEXPORT jbyteArray JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1object_1cache_1get_1or_1create( + JNIEnv *env, jclass, jobject cache_buf, jbyteArray type_j, jbyteArray key_j, jbyteArray data_j) { + CHECK_BUF_RET(cache, cache_buf, duckdb_v2_object_cache_handle, "object cache", nullptr); + auto type = jbyteArray_to_string(env, type_j); + if (env->ExceptionCheck()) { + return nullptr; + } + auto key = jbyteArray_to_string(env, key_j); + if (env->ExceptionCheck()) { + return nullptr; + } + auto data = jbyteArray_to_string(env, data_j); + if (env->ExceptionCheck()) { + return nullptr; + } + duckdb_v2_object_cache_entry_handle entry = nullptr; + CALL_V2(duckdb_v2_object_cache_get_or_create(cache, type.data(), type.size(), key.data(), key.size(), + object_cache_create_bytes, &data, &entry, ERR_OUT), + nullptr); + void *stored = nullptr; + v2_error err; + jbyteArray res = nullptr; + if (duckdb_v2_object_cache_entry_get_data(entry, &stored, err.out()) != DUCKDB_V2_ERROR_NONE) { + throw_v2_error(env, err); + } else if (stored != nullptr) { + auto bytes = reinterpret_cast(stored); + res = make_jbyteArray(env, bytes->data(), bytes->size()); + } + duckdb_v2_object_cache_entry_destroy(&entry); + return res; +} diff --git a/src/main/java/org/duckdb/DuckDBBindings.java b/src/main/java/org/duckdb/DuckDBBindings.java index 10502efe3..4d76294e6 100644 --- a/src/main/java/org/duckdb/DuckDBBindings.java +++ b/src/main/java/org/duckdb/DuckDBBindings.java @@ -483,6 +483,15 @@ static native void duckdb_v2_column_data_collection_append(ByteBuffer collection static native void duckdb_v2_statement_add_collection(ByteBuffer statement, byte[] name, ByteBuffer collection, byte[][] column_names) throws SQLException; + // object cache + + // the returned object cache is borrowed from the instance + static native ByteBuffer duckdb_v2_instance_get_object_cache(ByteBuffer instance) throws SQLException; + + // returns the bytes of the entry, that is created with the given bytes (and is never evicted) if there is none + static native byte[] duckdb_v2_object_cache_get_or_create(ByteBuffer cache, byte[] type, byte[] key, byte[] data) + throws SQLException; + // qualified names and table descriptions // creates a qualified name from one to three parts, outermost first, it is owned by the caller diff --git a/src/main/java/org/duckdb/DuckDBInstances.java b/src/main/java/org/duckdb/DuckDBInstances.java index 771d28d89..a9e22c4d8 100644 --- a/src/main/java/org/duckdb/DuckDBInstances.java +++ b/src/main/java/org/duckdb/DuckDBInstances.java @@ -4,7 +4,6 @@ import static org.duckdb.DuckDBBindings.*; import java.nio.ByteBuffer; -import java.nio.file.Paths; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; @@ -38,8 +37,12 @@ private DuckDBInstances() { private static final String MEMORY_PREFIX = ":memory:"; - // The addresses of the instances that are not shared are even, of the shared ones are odd - private static final AtomicLong NEXT_ADDRESS = new AtomicLong(1); + // The addresses of the instances are the ids that are unique in the process, 0 is not used + private static final AtomicLong NEXT_ADDRESS = new AtomicLong(0); + + // The entry of the object cache of an instance that keeps the address of the instance + private static final byte[] OBJECT_CACHE_TYPE = "duckdb_jdbc.instance".getBytes(UTF_8); + private static final byte[] OBJECT_CACHE_ADDRESS_KEY = "address".getBytes(UTF_8); private static ByteBuffer defaultEnvironment = null; @@ -385,7 +388,14 @@ static Connected startup(String database, boolean readOnly, Properties props, bo throw new SQLException("Connection Error: " + rawMessage(e.getMessage()), e.getSQLState(), e.getErrorCode(), e); } - ref = new InstanceRef(null, instance, hashOfPath(database) | 1L); + long address; + try { + address = sharedInstanceAddress(instance); + } catch (SQLException | RuntimeException e) { + duckdb_v2_instance_destroy(instance); + throw e; + } + ref = new InstanceRef(null, instance, address); } else { ByteBuffer environment = duckdb_v2_environment_create(); ByteBuffer instance = null; @@ -407,7 +417,7 @@ static Connected startup(String database, boolean readOnly, Properties props, bo duckdb_v2_environment_destroy(environment); throw e; } - ref = new InstanceRef(environment, instance, NEXT_ADDRESS.incrementAndGet() << 1); + ref = new InstanceRef(environment, instance, NEXT_ADDRESS.incrementAndGet()); } try { return new Connected(ref, duckdb_v2_connection_create(ref.instance())); @@ -417,14 +427,20 @@ static Connected startup(String database, boolean readOnly, Properties props, bo } } - private static long hashOfPath(String database) { - String key; - try { - key = Paths.get(database).toAbsolutePath().normalize().toString(); - } catch (RuntimeException e) { - key = database; + /** + * The address of an instance that is shared: all the handles to the instance, that are opened with any spelling + * of its path, get the same address, and no other instance gets it. The address is kept in the object cache of + * the instance, the first handle to the instance stores it there. + */ + private static long sharedInstanceAddress(ByteBuffer instance) throws SQLException { + ByteBuffer cache = duckdb_v2_instance_get_object_cache(instance); + byte[] candidate = ByteBuffer.allocate(Long.BYTES).putLong(NEXT_ADDRESS.incrementAndGet()).array(); + byte[] address = + duckdb_v2_object_cache_get_or_create(cache, OBJECT_CACHE_TYPE, OBJECT_CACHE_ADDRESS_KEY, candidate); + if (address == null || address.length != Long.BYTES) { + throw new SQLException("Invalid Input Error: cannot read the address of the instance"); } - return key.hashCode() & 0xffffffffL; + return ByteBuffer.wrap(address).getLong(); } /** Connects to the instance of the connection, the session settings of the connection are copied. */ diff --git a/src/test/java/org/duckdb/TestDuckDBJDBC.java b/src/test/java/org/duckdb/TestDuckDBJDBC.java index 51a4b5de9..e26079f91 100644 --- a/src/test/java/org/duckdb/TestDuckDBJDBC.java +++ b/src/test/java/org/duckdb/TestDuckDBJDBC.java @@ -1121,6 +1121,40 @@ public static void test_null_bytes_in_string() throws Exception { } } + public static void test_instance_cache_db_address() throws Exception { + try (TempDirectory dir = new TempDirectory()) { + // the paths of the databases have the same hash code + String path1 = dir.path().resolve("Aa.db").toString(); + String path2 = dir.path().resolve("BB.db").toString(); + assertEquals(path1.hashCode(), path2.hashCode()); + try (DuckDBConnection conn1 = DriverManager.getConnection(JDBC_URL + path1).unwrap(DuckDBConnection.class); + DuckDBConnection conn2 = DriverManager.getConnection(JDBC_URL + path2).unwrap(DuckDBConnection.class); + DuckDBConnection conn3 = DriverManager.getConnection(JDBC_URL + path1).unwrap(DuckDBConnection.class); + DuckDBConnection dup = conn2.duplicate()) { + assertTrue(conn1.dbAddress != 0); + assertTrue(conn2.dbAddress != 0); + // different databases + assertTrue(conn1.dbAddress != conn2.dbAddress); + // the same database + assertEquals(conn1.dbAddress, conn3.dbAddress); + assertEquals(conn2.dbAddress, dup.dbAddress); + } + // the instance is destroyed with its last connection, a new instance is not the same database + long address1; + try (DuckDBConnection conn1 = + DriverManager.getConnection(JDBC_URL + path1).unwrap(DuckDBConnection.class)) { + address1 = conn1.dbAddress; + } + try (DuckDBConnection conn1 = DriverManager.getConnection(JDBC_URL + path1).unwrap(DuckDBConnection.class); + DuckDBConnection conn2 = + DriverManager.getConnection(JDBC_URL + path2).unwrap(DuckDBConnection.class)) { + assertTrue(conn1.dbAddress != address1); + assertTrue(conn2.dbAddress != address1); + assertTrue(conn1.dbAddress != conn2.dbAddress); + } + } + } + public static void test_instance_cache() throws Exception { try (TempDirectory dir = new TempDirectory()) { String fileUrl = JDBC_URL + dir.path().resolve("instance_cache.db"); From 7ec414fc594461f8ac4b32194bb6a70bcf3b3b95 Mon Sep 17 00:00:00 2001 From: Alex Kasko Date: Wed, 2 Dec 2026 11:57:30 +0000 Subject: [PATCH 20/21] Export the Arrow stream from the chunks of the result without copying them The Arrow export copied all the rows of the result into a column data collection and ran a query over the collection to get the Arrow batches. A result that is streamed was read into the memory before the first batch was returned, the rows were copied twice, and the batches were filled by the threads of that query, so their sizes were not exact. The rows that are not read yet are scanned by a table function now: the chunks that are fetched already are passed to the scan as they are, and a result that is streamed is read when the Arrow stream is read. The scan is done by one thread in the order of the result, so the batches have the requested size again: the assertions of TestArrow that were relaxed are restored. --- duckdb_java.def | 2 + duckdb_java.exp | 2 + duckdb_java.map | 2 + src/jni/arrow_export.cpp | 354 +++++++++++++++--- src/main/java/org/duckdb/DuckDBBindings.java | 20 +- src/main/java/org/duckdb/DuckDBCore.java | 66 +--- src/main/java/org/duckdb/DuckDBResultSet.java | 2 +- src/test/external/TestArrow.java | 76 +++- 8 files changed, 416 insertions(+), 108 deletions(-) diff --git a/duckdb_java.def b/duckdb_java.def index 98aa613e3..a230f3450 100644 --- a/duckdb_java.def +++ b/duckdb_java.def @@ -250,6 +250,8 @@ Java_org_duckdb_DuckDBBindings_duckdb_1v2_1option_1get_1name Java_org_duckdb_DuckDBBindings_duckdb_1v2_1option_1supports_1scope Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1close_1streams Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1export_1stream +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1result +Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1release_1result Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1scan_1function Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1stream Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1release_1stream diff --git a/duckdb_java.exp b/duckdb_java.exp index 089efcef8..0b735fff5 100644 --- a/duckdb_java.exp +++ b/duckdb_java.exp @@ -247,6 +247,8 @@ _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1option_1get_1name _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1option_1supports_1scope _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1close_1streams _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1export_1stream +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1result +_Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1release_1result _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1scan_1function _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1stream _Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1release_1stream diff --git a/duckdb_java.map b/duckdb_java.map index c6b30098c..24bcb1337 100644 --- a/duckdb_java.map +++ b/duckdb_java.map @@ -249,6 +249,8 @@ DUCKDB_JAVA { Java_org_duckdb_DuckDBBindings_duckdb_1v2_1option_1supports_1scope; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1close_1streams; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1export_1stream; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1result; + Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1release_1result; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1scan_1function; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1stream; Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1release_1stream; diff --git a/src/jni/arrow_export.cpp b/src/jni/arrow_export.cpp index 0b586e850..d28a845c8 100644 --- a/src/jni/arrow_export.cpp +++ b/src/jni/arrow_export.cpp @@ -1,16 +1,19 @@ // Exports a query result as an Arrow stream, over the C API v2 only. // -// The rows of the result are bound to a statement (SELECT * FROM the rows) that is executed with the Arrow result -// format, and the result is turned into an ArrowArrayStream. An Arrow stream is a C structure with callbacks, so it -// cannot be implemented in Java. The stream that is handed out owns the statement and the rows, it is released by -// its consumer. When the connection is closed before the consumer, the streams of the connection are closed: the -// reads of the stream fail then. +// The rows of the result that are not read yet are scanned by a table function, the statement that selects from it +// is executed with the Arrow result format, and its result is turned into an ArrowArrayStream. The rows are not +// collected: the chunks of the result are passed to the scan as they are, and a result that is streamed is read +// when the Arrow stream is read. An Arrow stream is a C structure with callbacks, so it cannot be implemented in +// Java. The stream that is handed out owns the statement and the rows, it is released by its consumer. When the +// connection is closed before the consumer, the streams of the connection are closed: the reads of the stream fail +// then. #include "bindings.hpp" #include "refs.hpp" #include "util.hpp" #include #include +#include #include #include #include @@ -19,13 +22,87 @@ namespace { +/** + * The rows of a query result that are not read yet: the chunks that are fetched already, and the result that the next + * chunks are fetched from (when the result is streamed). The rows are read once, by the scan of the Arrow export. + */ +struct ResultSource { + std::mutex lock; + std::vector names; + std::vector types; + std::deque chunks; + duckdb_v2_result_handle result = nullptr; + bool closed = false; + + ResultSource() = default; + ResultSource(const ResultSource &) = delete; + ResultSource &operator=(const ResultSource &) = delete; + + //! Releases the rows that are not read + void Close() { + std::lock_guard guard(lock); + closed = true; + for (auto &chunk : chunks) { + duckdb_v2_data_chunk_destroy(&chunk); + } + chunks.clear(); + if (result) { + duckdb_v2_result_destroy(&result); + result = nullptr; + } + } + + ~ResultSource() { + Close(); + for (auto &type : types) { + destroy_logical_type(type); + } + } +}; + +struct ResultSources { + std::mutex lock; + int64_t next_id = 1; + std::unordered_map> sources; + + int64_t Add(std::shared_ptr source) { + std::lock_guard guard(lock); + int64_t id = next_id++; + sources[id] = std::move(source); + return id; + } + + std::shared_ptr Get(int64_t id) { + std::lock_guard guard(lock); + auto it = sources.find(id); + return it == sources.end() ? nullptr : it->second; + } + + std::shared_ptr Remove(int64_t id) { + std::lock_guard guard(lock); + auto it = sources.find(id); + if (it == sources.end()) { + return nullptr; + } + auto res = std::move(it->second); + sources.erase(it); + return res; + } +}; + +ResultSources &result_sources() { + static ResultSources sources; + return sources; +} + struct ExportedStream { //! The stream that is handed out, it must be the first member ArrowArrayStream stream {}; //! The stream of the Arrow result ArrowArrayStream inner {}; duckdb_v2_sql_statement_handle statement = nullptr; - duckdb_v2_column_data_collection_handle collection = nullptr; + //! The rows of the result that the statement scans + std::shared_ptr source; //! The connection of the result that is exported, the stream is closed with it duckdb_v2_connection_handle connection = nullptr; //! The connection of its own that the statement runs on, so that the connection of the result stays usable @@ -46,9 +123,10 @@ struct ExportedStream { duckdb_v2_sql_statement_destroy(&statement); statement = nullptr; } - if (collection) { - duckdb_v2_column_data_collection_destroy(&collection); - collection = nullptr; + if (source) { + // the result that is streamed belongs to the connection that is being closed + source->Close(); + source.reset(); } if (helper) { duckdb_v2_connection_destroy(&helper); @@ -135,23 +213,90 @@ void stream_release(ArrowArrayStream *stream) { } // namespace +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_arrow_register_result + * Signature: (Ljava/nio/ByteBuffer;[Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)J + */ +// Registers the rows of a result as a source for the Arrow export, returns the id of the source. The source takes the +// ownership of the chunks and of the result (that can be null) when the call succeeds, the schema is borrowed. +JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1result(JNIEnv *env, jclass, + jobject schema_buf, + jobjectArray chunks_j, + jobject result_buf) { + auto schema = schema_buf == nullptr + ? nullptr + : reinterpret_cast(env->GetDirectBufferAddress(schema_buf)); + if (!schema) { + env->ThrowNew(J_SQLException, "Invalid schema"); + return 0; + } + auto source = std::make_shared(); + v2_error err; + idx_t count = 0; + if (duckdb_v2_schema_get_count(schema, &count, err.out()) != DUCKDB_V2_ERROR_NONE) { + throw_sql_exception(env, err); + return 0; + } + for (idx_t i = 0; i < count; i++) { + const char *name = nullptr; + idx_t name_len = 0; + duckdb_v2_logical_type_handle type = nullptr; + if (duckdb_v2_schema_get_field(schema, i, &name, &name_len, &type, err.out()) != DUCKDB_V2_ERROR_NONE) { + throw_sql_exception(env, err); + return 0; + } + source->names.emplace_back(name, name_len); + source->types.push_back(copy_logical_type(type)); + } + std::vector chunks; + jsize chunk_count = chunks_j == nullptr ? 0 : env->GetArrayLength(chunks_j); + for (jsize i = 0; i < chunk_count; i++) { + jobject chunk_buf = env->GetObjectArrayElement(chunks_j, i); + auto chunk = chunk_buf_to_chunk(env, chunk_buf); + env->DeleteLocalRef(chunk_buf); + if (env->ExceptionCheck()) { + return 0; + } + chunks.push_back(chunk); + } + // nothing can fail from here on, the ownership of the rows is taken + source->chunks.assign(chunks.begin(), chunks.end()); + if (result_buf != nullptr) { + source->result = reinterpret_cast(env->GetDirectBufferAddress(result_buf)); + } + return static_cast(result_sources().Add(std::move(source))); +} + +/* + * Class: org_duckdb_DuckDBBindings + * Method: duckdb_v2_arrow_release_result + * Signature: (J)V + */ +// Releases the registered rows of a result, if they are not owned by an exported stream +JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1release_1result(JNIEnv *, jclass, jlong id) { + auto source = result_sources().Remove(static_cast(id)); + if (source) { + source->Close(); + } +} + /* * Class: org_duckdb_DuckDBBindings * Method: duckdb_v2_arrow_export_stream - * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;J)J + * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;JJ)J */ -// Executes the statement (that reads the collection) on the helper connection with the Arrow result format and returns -// the address of the stream of the result. The stream takes the ownership of the helper connection, of the statement -// and of the collection when the call succeeds, conn is the connection that the stream is closed with. +// Executes the statement (that scans the registered rows of a result) on the helper connection with the Arrow result +// format and returns the address of the stream of the result. The stream takes the ownership of the helper connection, +// of the statement and of the registered rows when the call succeeds, conn is the connection that the stream is closed +// with. JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1export_1stream( - JNIEnv *env, jclass, jobject conn_buf, jobject helper_buf, jobject st_buf, jobject collection_buf, - jlong batch_size) { + JNIEnv *env, jclass, jobject conn_buf, jobject helper_buf, jobject st_buf, jlong source_id, jlong batch_size) { auto conn = reinterpret_cast(env->GetDirectBufferAddress(conn_buf)); auto helper = reinterpret_cast(env->GetDirectBufferAddress(helper_buf)); auto statement = reinterpret_cast(env->GetDirectBufferAddress(st_buf)); - auto collection = - reinterpret_cast(env->GetDirectBufferAddress(collection_buf)); - if (!conn || !helper || !statement || !collection) { + auto source = result_sources().Get(static_cast(source_id)); + if (!conn || !helper || !statement || !source) { env->ThrowNew(J_SQLException, "Invalid Arrow export arguments"); return 0; } @@ -176,8 +321,10 @@ JNIEXPORT jlong JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1export throw_sql_exception(env, err); return 0; } + // the rows are owned by the stream from here on + result_sources().Remove(static_cast(source_id)); exported->statement = statement; - exported->collection = collection; + exported->source = std::move(source); exported->connection = conn; exported->helper = helper; exported->stream.private_data = exported; @@ -500,6 +647,146 @@ void scan_exec(duckdb_v2_data_source_exec_info_handle info, duckdb_v2_context_ha } } +// --------------------------------------------------------------------------------------------------------------------- +// Result scan: the rows of a query result are scanned by the table function that the statement of the Arrow export +// selects from +// --------------------------------------------------------------------------------------------------------------------- + +const char *const RESULT_SCAN_FUNCTION = "__jdbc_arrow_result_scan"; + +struct ResultScanBindData { + std::shared_ptr source; +}; + +void result_scan_bind(duckdb_v2_function_bind_info_handle info, duckdb_v2_table_function_bind_info_handle result, + duckdb_v2_context_handle, duckdb_v2_error_info_handle *err) { + v2_value id_value; + v2_error call_err; + int64_t id = 0; + if (duckdb_v2_function_bind_get_arg_value(info, 0, id_value.out(), call_err.out()) != DUCKDB_V2_ERROR_NONE || + duckdb_v2_value_get_bigint(id_value.get(), &id, call_err.out()) != DUCKDB_V2_ERROR_NONE) { + set_callback_error(err, call_err.code(), call_err.raw_message()); + return; + } + auto source = result_sources().Get(id); + if (!source) { + set_callback_error(err, DUCKDB_V2_ERROR_INPUT_INVALID, "This result has been released"); + return; + } + for (idx_t i = 0; i < source->names.size(); i++) { + auto &name = source->names[i]; + if (duckdb_v2_table_function_bind_add_result_column(result, name.data(), name.size(), source->types[i], + call_err.out()) != DUCKDB_V2_ERROR_NONE) { + set_callback_error(err, call_err.code(), call_err.raw_message()); + return; + } + } + auto bind_data = new ResultScanBindData {std::move(source)}; + duckdb_v2_opaque opaque = {bind_data, [](void *data) { delete static_cast(data); }, nullptr}; + if (duckdb_v2_function_bind_set_bind_data(info, &opaque, call_err.out()) != DUCKDB_V2_ERROR_NONE) { + delete bind_data; + set_callback_error(err, call_err.code(), call_err.raw_message()); + } +} + +void result_scan_init_global(duckdb_v2_data_source_init_global_info_handle info, duckdb_v2_context_handle, + duckdb_v2_error_info_handle *) { + // the chunks are read in the order of the result + duckdb_v2_data_source_init_global_set_max_threads(info, 1, nullptr); +} + +void result_scan_exec(duckdb_v2_data_source_exec_info_handle info, duckdb_v2_context_handle, + duckdb_v2_error_info_handle *err) { + v2_error call_err; + void *bind_ptr = nullptr; + if (duckdb_v2_data_source_exec_get_bind_data(info, &bind_ptr, call_err.out()) != DUCKDB_V2_ERROR_NONE) { + set_callback_error(err, call_err.code(), call_err.raw_message()); + return; + } + auto &source = *static_cast(bind_ptr)->source; + v2_data_chunk chunk; + idx_t row_count = 0; + { + std::lock_guard guard(source.lock); + // the chunks without rows are skipped: an empty output chunk is the end of the scan + while (row_count == 0) { + if (source.closed) { + set_callback_error(err, DUCKDB_V2_ERROR_INPUT_INVALID, "This result has been released"); + return; + } + if (!source.chunks.empty()) { + chunk = v2_data_chunk(source.chunks.front()); + source.chunks.pop_front(); + } else if (source.result) { + // the result is streamed, the query of the result is run here + if (duckdb_v2_result_fetch_chunk(source.result, chunk.out(), call_err.out()) != DUCKDB_V2_ERROR_NONE) { + set_callback_error(err, call_err.code(), call_err.raw_message()); + return; + } + } else { + chunk.reset(); + } + if (!chunk) { + return; + } + if (duckdb_v2_data_chunk_get_size(chunk.get(), &row_count, call_err.out()) != DUCKDB_V2_ERROR_NONE) { + set_callback_error(err, call_err.code(), call_err.raw_message()); + return; + } + } + } + // the vectors of the output share the data of the chunk, that is not copied + duckdb_v2_data_chunk_handle output = nullptr; + if (duckdb_v2_data_source_exec_get_output_chunk(info, &output, call_err.out()) != DUCKDB_V2_ERROR_NONE) { + set_callback_error(err, call_err.code(), call_err.raw_message()); + return; + } + idx_t column_count = 0; + duckdb_v2_data_chunk_get_vector_count(chunk.get(), &column_count, nullptr); + for (idx_t i = 0; i < column_count; i++) { + duckdb_v2_vector_handle target = nullptr; + duckdb_v2_vector_handle vector = nullptr; + if (duckdb_v2_data_chunk_get_vector(output, i, &target, call_err.out()) != DUCKDB_V2_ERROR_NONE || + duckdb_v2_data_chunk_get_vector(chunk.get(), i, &vector, call_err.out()) != DUCKDB_V2_ERROR_NONE || + duckdb_v2_vector_reference(target, vector, call_err.out()) != DUCKDB_V2_ERROR_NONE || + duckdb_v2_vector_set_size(target, row_count, call_err.out()) != DUCKDB_V2_ERROR_NONE) { + set_callback_error(err, call_err.code(), call_err.raw_message()); + return; + } + } +} + +// Registers a table function with one BIGINT parameter, the scan callbacks are set on a data source: the table +// function keeps a copy of it +bool register_scan_function(duckdb_v2_connection_handle conn, const char *name, + duckdb_v2_table_function_bind_callback_fn bind, + duckdb_v2_data_source_init_global_callback_fn init_global, + duckdb_v2_data_source_exec_callback_fn exec, v2_error &err) { + duckdb_v2_factory_handle factory = nullptr; + v2_table_function function; + v2_data_source data_source; + v2_logical_type bigint; + duckdb_v2_function_signature_handle signature = nullptr; + return duckdb_v2_connection_get_factory(conn, &factory, err.out()) == DUCKDB_V2_ERROR_NONE && + duckdb_v2_table_function_create(factory, function.out(), err.out()) == DUCKDB_V2_ERROR_NONE && + duckdb_v2_table_function_set_name(function.get(), name, std::strlen(name), err.out()) == + DUCKDB_V2_ERROR_NONE && + duckdb_v2_factory_create_type_from_id(factory, DUCKDB_V2_LOGICAL_TYPE_ID_BIGINT, nullptr, nullptr, nullptr, + 0, bigint.out(), err.out()) == DUCKDB_V2_ERROR_NONE && + duckdb_v2_table_function_get_signature(function.get(), &signature, err.out()) == DUCKDB_V2_ERROR_NONE && + duckdb_v2_function_signature_add_parameter(signature, "id", 2, bigint.get(), nullptr, + DUCKDB_V2_FUNCTION_PARAMETER_KIND_POSITIONAL_ONLY, + err.out()) == DUCKDB_V2_ERROR_NONE && + duckdb_v2_table_function_set_bind_callback(function.get(), bind, err.out()) == DUCKDB_V2_ERROR_NONE && + duckdb_v2_data_source_create(factory, data_source.out(), err.out()) == DUCKDB_V2_ERROR_NONE && + duckdb_v2_data_source_set_init_global_callback(data_source.get(), init_global, err.out()) == + DUCKDB_V2_ERROR_NONE && + duckdb_v2_data_source_set_exec_callback(data_source.get(), exec, err.out()) == DUCKDB_V2_ERROR_NONE && + duckdb_v2_table_function_set_data_source(function.get(), data_source.get(), err.out()) == + DUCKDB_V2_ERROR_NONE && + duckdb_v2_connection_register_table_function(conn, function.get(), err.out()) == DUCKDB_V2_ERROR_NONE; +} + // Closes the registered streams of the connection void close_registered_streams(duckdb_v2_connection_handle conn) { std::vector> closing; @@ -527,7 +814,7 @@ void close_registered_streams(duckdb_v2_connection_handle conn) { * Method: duckdb_v2_arrow_register_scan_function * Signature: (Ljava/nio/ByteBuffer;)V */ -// Registers the table function that scans the registered streams +// Registers the table functions that scan the registered streams and the rows of the exported results JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1register_1scan_1function(JNIEnv *env, jclass, jobject conn_buf) { auto conn = reinterpret_cast(env->GetDirectBufferAddress(conn_buf)); @@ -536,30 +823,9 @@ JNIEXPORT void JNICALL Java_org_duckdb_DuckDBBindings_duckdb_1v2_1arrow_1registe return; } v2_error err; - duckdb_v2_factory_handle factory = nullptr; - v2_table_function function; - // the scan callbacks are set on a data source, the table function keeps a copy of it - v2_data_source data_source; - v2_logical_type bigint; - duckdb_v2_function_signature_handle signature = nullptr; - const char *name = ARROW_SCAN_FUNCTION; - if (duckdb_v2_connection_get_factory(conn, &factory, err.out()) != DUCKDB_V2_ERROR_NONE || - duckdb_v2_table_function_create(factory, function.out(), err.out()) != DUCKDB_V2_ERROR_NONE || - duckdb_v2_table_function_set_name(function.get(), name, std::strlen(name), err.out()) != DUCKDB_V2_ERROR_NONE || - duckdb_v2_factory_create_type_from_id(factory, DUCKDB_V2_LOGICAL_TYPE_ID_BIGINT, nullptr, nullptr, nullptr, 0, - bigint.out(), err.out()) != DUCKDB_V2_ERROR_NONE || - duckdb_v2_table_function_get_signature(function.get(), &signature, err.out()) != DUCKDB_V2_ERROR_NONE || - duckdb_v2_function_signature_add_parameter(signature, "stream_id", 9, bigint.get(), nullptr, - DUCKDB_V2_FUNCTION_PARAMETER_KIND_POSITIONAL_ONLY, - err.out()) != DUCKDB_V2_ERROR_NONE || - duckdb_v2_table_function_set_bind_callback(function.get(), scan_bind, err.out()) != DUCKDB_V2_ERROR_NONE || - duckdb_v2_data_source_create(factory, data_source.out(), err.out()) != DUCKDB_V2_ERROR_NONE || - duckdb_v2_data_source_set_init_global_callback(data_source.get(), scan_init_global, err.out()) != - DUCKDB_V2_ERROR_NONE || - duckdb_v2_data_source_set_exec_callback(data_source.get(), scan_exec, err.out()) != DUCKDB_V2_ERROR_NONE || - duckdb_v2_table_function_set_data_source(function.get(), data_source.get(), err.out()) != - DUCKDB_V2_ERROR_NONE || - duckdb_v2_connection_register_table_function(conn, function.get(), err.out()) != DUCKDB_V2_ERROR_NONE) { + if (!register_scan_function(conn, ARROW_SCAN_FUNCTION, scan_bind, scan_init_global, scan_exec, err) || + !register_scan_function(conn, RESULT_SCAN_FUNCTION, result_scan_bind, result_scan_init_global, result_scan_exec, + err)) { throw_sql_exception(env, err); } } diff --git a/src/main/java/org/duckdb/DuckDBBindings.java b/src/main/java/org/duckdb/DuckDBBindings.java index 4d76294e6..efe569488 100644 --- a/src/main/java/org/duckdb/DuckDBBindings.java +++ b/src/main/java/org/duckdb/DuckDBBindings.java @@ -619,13 +619,23 @@ static native void duckdb_v2_connection_register_custom_option(ByteBuffer conn, // Arrow export - // Executes the statement (that reads the collection) on the helper connection with the Arrow result format and - // returns the address of the ArrowArrayStream. The stream owns the helper connection, the statement and the - // collection (the stream is released by its consumer), conn is the connection that the stream is closed with. + // Registers the rows of a result that are not read yet as a source for the Arrow export: the chunks that are + // fetched already and the result (can be null) that the next chunks are fetched from. Returns the id of the + // source, that owns the chunks and the result. The schema is borrowed. + static native long duckdb_v2_arrow_register_result(ByteBuffer schema, ByteBuffer[] chunks, ByteBuffer result) + throws SQLException; + + // releases the registered rows of a result, if they are not owned by an exported stream + static native void duckdb_v2_arrow_release_result(long id); + + // Executes the statement (that scans the registered rows of a result) on the helper connection with the Arrow + // result format and returns the address of the ArrowArrayStream. The stream owns the helper connection, the + // statement and the rows (the stream is released by its consumer), conn is the connection that the stream is + // closed with. static native long duckdb_v2_arrow_export_stream(ByteBuffer conn, ByteBuffer helper, ByteBuffer statement, - ByteBuffer collection, long batch_size) throws SQLException; + long source_id, long batch_size) throws SQLException; - // registers the table function that scans the registered Arrow streams + // registers the table functions that scan the registered Arrow streams and the rows of the exported results static native void duckdb_v2_arrow_register_scan_function(ByteBuffer conn) throws SQLException; // moves the stream (the address of an ArrowArrayStream) out of its struct and registers it, returns its id diff --git a/src/main/java/org/duckdb/DuckDBCore.java b/src/main/java/org/duckdb/DuckDBCore.java index 40bc7bb5e..1ae6b9b9a 100644 --- a/src/main/java/org/duckdb/DuckDBCore.java +++ b/src/main/java/org/duckdb/DuckDBCore.java @@ -687,13 +687,12 @@ static void registerArrowStream(DuckDBConnection connection, long streamAddress, } } - private static final byte[] ARROW_ROWS_NAME = "__jdbc_result_rows".getBytes(UTF_8); - /** - * Exports the rows of the result that are not read yet as an Arrow stream of record batches of at most - * batchSize rows, returns the address of the ArrowArrayStream. The rows are moved into the stream, a result that is - * streamed is read into the memory first. The rows are bound to a statement (SELECT * FROM the rows) that runs on - * a connection of its own, so that the connection of the result stays usable while the stream is open. + * Exports the rows of the result that are not read yet as an Arrow stream of record batches of batchSize rows (the + * last batch can be smaller), returns the address of the ArrowArrayStream. The rows are moved into the stream: + * the chunks that are fetched already are converted as they are, and a result that is streamed is read when the + * stream is read. The rows are scanned by a statement that runs on a connection of its own, so that the + * connection of the result stays usable while the stream is open. */ static long exportArrow(ResultRef ref, DuckDBConnection connection, long batchSize) throws SQLException { if (ref == null || ref.schema == null) { @@ -703,69 +702,36 @@ static long exportArrow(ResultRef ref, DuckDBConnection connection, long batchSi throw invalid("Arrow batch size must be greater than 0"); } connection.queryGate.acquireUninterruptibly(); - ByteBuffer collection = null; + long source = 0; ByteBuffer helper = null; ByteBuffer statement = null; try { ByteBuffer connHandle = conn(connection.connRef); - ByteBuffer factory = duckdb_v2_connection_get_factory(connHandle); if (ref.currentChunk != null) { duckdb_destroy_data_chunk(ref.currentChunk); ref.currentChunk = null; } - int columnCount = ref.names.length; - ByteBuffer[] types = new ByteBuffer[columnCount]; - byte[][] names = new byte[columnCount][]; - for (int i = 0; i < columnCount; i++) { - types[i] = duckdb_v2_schema_get_field_type(ref.schema, i); - names[i] = ref.names[i].getBytes(UTF_8); - } - collection = duckdb_v2_column_data_collection_create(factory, types); - ByteBuffer appendState = duckdb_v2_column_data_collection_append_state_create(collection); - try { - ByteBuffer chunk; - while ((chunk = ref.chunks.poll()) != null) { - try { - duckdb_v2_column_data_collection_append(collection, appendState, chunk); - } finally { - duckdb_destroy_data_chunk(chunk); - } - } - if (ref.streamResult != null) { - ByteBuffer result = ref.streamResult; - ref.streamResult = null; - try { - while ((chunk = duckdb_v2_result_fetch_chunk(result)) != null) { - try { - duckdb_v2_column_data_collection_append(collection, appendState, chunk); - } finally { - duckdb_destroy_data_chunk(chunk); - } - } - } finally { - duckdb_v2_result_destroy(result); - } - } - } finally { - duckdb_v2_column_data_collection_append_state_destroy(appendState); - } + source = + duckdb_v2_arrow_register_result(ref.schema, ref.chunks.toArray(new ByteBuffer[0]), ref.streamResult); + // the source owns the rows now + ref.chunks.clear(); + ref.streamResult = null; helper = duckdb_v2_connection_create(connection.instanceRef.instance()); DuckDBInstances.copySessionSettings(connHandle, helper); - statement = parseSingleStatement(helper, "SELECT * FROM " + new String(ARROW_ROWS_NAME, UTF_8)); - duckdb_v2_statement_add_collection(statement, ARROW_ROWS_NAME, collection, names); - long address = duckdb_v2_arrow_export_stream(connHandle, helper, statement, collection, batchSize); + statement = parseSingleStatement(helper, "SELECT * FROM __jdbc_arrow_result_scan(" + source + ")"); + long address = duckdb_v2_arrow_export_stream(connHandle, helper, statement, source, batchSize); // the stream owns them now statement = null; - collection = null; + source = 0; helper = null; return address; } finally { if (statement != null) { duckdb_v2_sql_statement_destroy(statement); } - if (collection != null) { - duckdb_v2_column_data_collection_destroy(collection); + if (source != 0) { + duckdb_v2_arrow_release_result(source); } if (helper != null) { duckdb_v2_connection_destroy(helper); diff --git a/src/main/java/org/duckdb/DuckDBResultSet.java b/src/main/java/org/duckdb/DuckDBResultSet.java index 7f31efe42..3ab26a4f8 100644 --- a/src/main/java/org/duckdb/DuckDBResultSet.java +++ b/src/main/java/org/duckdb/DuckDBResultSet.java @@ -130,7 +130,7 @@ private void check(int columnIndex) throws SQLException { * When the connection is closed before the reader, the reader fails to load next batches. * * @param arrow_buffer_allocator an instance of {@link org.apache.arrow.memory.BufferAllocator} - * @param arrow_batch_size maximum number of rows of the arrow vectors to return, the batches can be smaller + * @param arrow_batch_size batch size of arrow vectors to return * @return an instance of {@link org.apache.arrow.vector.ipc.ArrowReader} */ public synchronized Object arrowExportStream(Object arrow_buffer_allocator, long arrow_batch_size) diff --git a/src/test/external/TestArrow.java b/src/test/external/TestArrow.java index ada83e9d7..2c4648a8b 100644 --- a/src/test/external/TestArrow.java +++ b/src/test/external/TestArrow.java @@ -14,6 +14,10 @@ import java.util.ArrayList; import java.util.List; import java.util.Properties; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import org.apache.arrow.c.ArrowArrayStream; import org.apache.arrow.c.Data; import org.apache.arrow.memory.BufferAllocator; @@ -657,13 +661,7 @@ public static void test_arrow_export_batch_size() throws Exception { sum += vec.get(i); } } - // batches are filled by the threads of the query, so they can be smaller than the batch size - int rows = 0; - for (int size : batchSizes) { - assertTrue(size > 0 && size <= 4096, "batch size: " + size); - rows += size; - } - assertEquals(rows, 10000); + assertListsEqual(batchSizes, asList(4096, 4096, 1808)); assertEquals(sum, 9999L * 10000L / 2); } } @@ -693,7 +691,69 @@ public static void test_arrow_export_streaming_result() throws Exception { } assertEquals(count, 100000L); assertEquals(sum, 99999L * 100000L / 2); - assertTrue(batches >= 10); + assertEquals(batches, 10); + } + } + + // A result that is streamed is read when the Arrow stream is read: the result has too many rows to be read into + // the memory before the first batch is returned + public static void test_arrow_export_streaming_result_not_buffered() throws Exception { + Properties config = new Properties(); + config.put(JDBC_STREAM_RESULTS, true); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try (BufferAllocator allocator = new RootAllocator(); + Connection conn = DriverManager.getConnection(JDBC_URL, config); Statement stmt = conn.createStatement(); + DuckDBResultSet rs = + stmt.executeQuery("SELECT i FROM range(0, 100000000000) t(i)").unwrap(DuckDBResultSet.class)) { + Future rows = executor.submit(() -> { + long expected = 0; + try (ArrowReader reader = (ArrowReader) rs.arrowExportStream(allocator, 4096)) { + VectorSchemaRoot root = reader.getVectorSchemaRoot(); + for (int batch = 0; batch < 100; batch++) { + assertTrue(reader.loadNextBatch()); + assertEquals(root.getRowCount(), 4096); + BigIntVector vec = (BigIntVector) root.getVector("i"); + for (int i = 0; i < root.getRowCount(); i++) { + assertEquals(vec.get(i), expected++); + } + } + } + return expected; + }); + assertEquals(rows.get(120, TimeUnit.SECONDS), 409600L); + } finally { + executor.shutdownNow(); + } + } + + // The rows that are read from the result set are not exported + public static void test_arrow_export_partially_read_result() throws Exception { + for (boolean streaming : new boolean[] {false, true}) { + Properties config = new Properties(); + config.put(JDBC_STREAM_RESULTS, streaming); + try (BufferAllocator allocator = new RootAllocator(); + Connection conn = DriverManager.getConnection(JDBC_URL, config); + Statement stmt = conn.createStatement(); + DuckDBResultSet rs = + stmt.executeQuery("SELECT i FROM range(0, 20000) t(i) ORDER BY i").unwrap(DuckDBResultSet.class)) { + // the first chunk of the result is being read + assertTrue(rs.next()); + assertEquals(rs.getLong(1), 0L); + try (ArrowReader reader = (ArrowReader) rs.arrowExportStream(allocator, 5000)) { + VectorSchemaRoot root = reader.getVectorSchemaRoot(); + List batchSizes = new ArrayList<>(); + long expected = 2048; + while (reader.loadNextBatch()) { + batchSizes.add(root.getRowCount()); + BigIntVector vec = (BigIntVector) root.getVector("i"); + for (int i = 0; i < root.getRowCount(); i++) { + assertEquals(vec.get(i), expected++); + } + } + assertEquals(expected, 20000L); + assertListsEqual(batchSizes, asList(5000, 5000, 5000, 2952)); + } + } } } From 947c698e3fa8317cbfe3c02a746b477a8eccaa1d Mon Sep 17 00:00:00 2001 From: Alex Kasko Date: Wed, 2 Dec 2026 14:04:59 +0000 Subject: [PATCH 21/21] Escape the backslashes and the quotes of the list values of the options A list value of a connection property, e.g. of 'allowed_directories', is passed to DuckDB as text that is cast to the type of the option. The backslash is the escape character of the quoted entries of that text, and the entries were only quoted: the backslashes of a Windows path were dropped ('C:\Users\dir' was read as 'C:Usersdir'), so the allowed directories did not match any file, and a quote in an entry was dropped too. On Windows the tests of the allowed directories failed with 'file system operations are disabled by configuration'. The backslashes and the quotes of the entries are escaped with a backslash. --- src/main/java/org/duckdb/DuckDBInstances.java | 4 ++- src/test/java/org/duckdb/TestDuckDBJDBC.java | 25 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/duckdb/DuckDBInstances.java b/src/main/java/org/duckdb/DuckDBInstances.java index a9e22c4d8..978ea0dd3 100644 --- a/src/main/java/org/duckdb/DuckDBInstances.java +++ b/src/main/java/org/duckdb/DuckDBInstances.java @@ -151,8 +151,10 @@ private static boolean isRuntimeOption(String name) { return isOneOf(name, RUNTIME_OPTIONS); } + // An entry of a list in its text form, that is cast to the type of the option: the backslash is the escape + // character of the quoted entries, so the backslashes (e.g. of a Windows path) and the quotes are escaped with it private static String quoteListEntry(String entry) { - return "'" + entry.replace("'", "''") + "'"; + return "'" + entry.replace("\\", "\\\\").replace("'", "\\'") + "'"; } // The text of a Java configuration value in the form that is accepted by SET, null for nulls diff --git a/src/test/java/org/duckdb/TestDuckDBJDBC.java b/src/test/java/org/duckdb/TestDuckDBJDBC.java index e26079f91..31038b985 100644 --- a/src/test/java/org/duckdb/TestDuckDBJDBC.java +++ b/src/test/java/org/duckdb/TestDuckDBJDBC.java @@ -2597,6 +2597,31 @@ public static void test_allowed_directories_external_access_disabled() throws Ex } } + // The entries of a list option are passed as they are: with the backslashes (the separators of a Windows path) + // and the quotes + public static void test_allowed_directories_special_characters() throws Exception { + try (TempDirectory dir = new TempDirectory()) { + Path forbiddenFile = writeCsv(dir.path().resolve("forbidden")); + for (String name : new String[] {"plain", "it's", "back\\slash", "quote's\\back\\slash"}) { + // the backslash is a part of the name of the directory, or the separator of two directories + Path allowedFile = writeCsv(dir.path().resolve(name)); + Properties config = new Properties(); + config.put("enable_external_access", false); + config.put("allowed_directories", asList(allowedFile.getParent().toString(), "other")); + try (Connection conn = DriverManager.getConnection(JDBC_URL, config)) { + assertSandboxed(conn, allowedFile, forbiddenFile); + } + + Properties configPaths = new Properties(); + configPaths.put("enable_external_access", false); + configPaths.put("allowed_paths", singletonList(allowedFile.toString())); + try (Connection conn = DriverManager.getConnection(JDBC_URL, configPaths)) { + assertSandboxed(conn, allowedFile, forbiddenFile); + } + } + } + } + public static void test_allowed_directories_external_access_disabled_cached_instance() throws Exception { try (TempDirectory dir = new TempDirectory()) { Path allowedFile = writeCsv(dir.path().resolve("allowed"));