diff --git a/.github/workflows/Java.yml b/.github/workflows/Java.yml index 1d6f3a217..37c32c793 100644 --- a/.github/workflows/Java.yml +++ b/.github/workflows/Java.yml @@ -219,6 +219,40 @@ jobs: java ${{ github.workspace }}/src/test/external/RunGraalNativeImage.java \ ${{ github.workspace }}/src/test/external/graal + java-linux-amd64-ffm: + name: Linux FFM (amd64, JDK 25) + runs-on: ${{ github.repository_owner == 'duckdb' && 'namespace-profile-linux-x64' || 'ubuntu-latest' }} + needs: java-linux-amd64 + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + ref: ${{ inputs.git_ref }} + + - name: Setup JDK + uses: actions/setup-java@v6 + with: + distribution: corretto + java-version: '25' + + - name: Build + if: ${{ inputs.skip_tests != 'true' }} + run: | + sudo apt-get install -y ninja-build + make release GEN=ninja + + - name: Check Java 22 classes + if: ${{ inputs.skip_tests != 'true' }} + run: | + unzip -l build/release/duckdb_jdbc.jar | grep -q 'META-INF/versions/22/org/duckdb/Ffm.class' + + - name: Java Tests (FFM) + if: ${{ inputs.skip_tests != 'true' }} + run: | + java -version + java --enable-native-access=ALL-UNNAMED -cp build/release/duckdb_jdbc.jar:build/release/duckdb_jdbc_tests.jar \ + org.duckdb.TestDuckDBJDBC + java-linux-amd64-spark: name: Linux Spark (amd64) runs-on: ${{ github.repository_owner == 'duckdb' && 'namespace-profile-linux-x64' || 'ubuntu-latest' }} @@ -376,7 +410,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 +433,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/CMakeLists.txt b/CMakeLists.txt index e6b2b45a4..c9778a49a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -638,6 +638,41 @@ add_jar(duckdb_jdbc_nolib ${JAVA_SRC_FILES} META-INF/services/java.sql.Driver GENERATE_NATIVE_HEADERS duckdb-native) add_jar(duckdb_jdbc_tests ${JAVA_TEST_FILES} INCLUDE_JARS duckdb_jdbc_nolib) +# Java 22+ implementation of the bindings: the C API of the native library is called directly with the Foreign +# Function and Memory API, without JNI. The classes are packed into the multi-release jars (META-INF/versions/22), +# they are compiled with JDK 22+ (the JDK of the build or the one of JAVA22_HOME), the rest of the driver is compiled +# for the oldest JDK. The jars have no such classes if there is no JDK 22+. + +file(GLOB_RECURSE JAVA22_SRC_FILES src/main/java22/org/duckdb/*.java) +set(JAVAC22 "") +if(Java_VERSION_MAJOR GREATER_EQUAL 22) + set(JAVAC22 ${Java_JAVAC_EXECUTABLE}) + set(JAVA22_RELEASE ${Java_VERSION_MAJOR}) +elseif(DEFINED ENV{JAVA22_HOME}) + set(JAVAC22 "$ENV{JAVA22_HOME}/bin/javac${CMAKE_EXECUTABLE_SUFFIX}") + set(JAVA22_RELEASE 22) + set(JAR22 "$ENV{JAVA22_HOME}/bin/jar${CMAKE_EXECUTABLE_SUFFIX}") +endif() +if(NOT JAR22) + set(JAR22 ${Java_JAR_EXECUTABLE}) +endif() +if(JAVAC22 AND JAVA22_SRC_FILES AND EXISTS "${JAVAC22}") + message(STATUS "Java 22 bindings are compiled with ${JAVAC22}") + add_custom_command( + OUTPUT java22/classes.stamp + DEPENDS duckdb_jdbc_nolib ${JAVA22_SRC_FILES} + COMMAND ${CMAKE_COMMAND} -E remove_directory java22/classes + COMMAND ${CMAKE_COMMAND} -E make_directory java22/classes + COMMAND ${JAVAC22} --release ${JAVA22_RELEASE} -encoding utf-8 -g -Xlint:-restricted,-try -cp duckdb_jdbc_nolib.jar -d java22/classes + ${JAVA22_SRC_FILES} + COMMAND ${CMAKE_COMMAND} -E touch java22/classes.stamp) + add_custom_target(duckdb_jdbc_java22 DEPENDS java22/classes.stamp) + set(JAVA22_ENABLED TRUE) +else() + message(STATUS "No JDK 22+ is found (set JAVA22_HOME), the jars will have no Java 22 bindings") + set(JAVA22_ENABLED FALSE) +endif() + # main shared lib compilation @@ -659,8 +694,6 @@ if(JEMALLOC_ENABLED) 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 @@ -669,16 +702,15 @@ 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}) @@ -764,14 +796,29 @@ set_target_properties(duckdb_java PROPERTIES PREFIX "lib") # JAR packing -add_custom_command( - OUTPUT dummy_jdbc_target - DEPENDS duckdb_java duckdb_jdbc_nolib duckdb_jdbc_tests - COMMAND ${CMAKE_COMMAND} -E copy - duckdb_jdbc_nolib.jar - duckdb_jdbc.jar - COMMAND ${Java_JAR_EXECUTABLE} uf duckdb_jdbc.jar -C - $ $) +if(JAVA22_ENABLED) + add_custom_command( + OUTPUT dummy_jdbc_target + DEPENDS duckdb_java duckdb_jdbc_nolib duckdb_jdbc_tests duckdb_jdbc_java22 + COMMAND ${CMAKE_COMMAND} -E copy + duckdb_jdbc_nolib.jar + duckdb_jdbc_nolib_mr.jar + COMMAND ${JAR22} uf duckdb_jdbc_nolib_mr.jar --release 22 -C java22/classes . + COMMAND ${CMAKE_COMMAND} -E copy + duckdb_jdbc_nolib_mr.jar + duckdb_jdbc.jar + COMMAND ${Java_JAR_EXECUTABLE} uf duckdb_jdbc.jar -C + $ $) +else() + add_custom_command( + OUTPUT dummy_jdbc_target + DEPENDS duckdb_java duckdb_jdbc_nolib duckdb_jdbc_tests + COMMAND ${CMAKE_COMMAND} -E copy + duckdb_jdbc_nolib.jar + duckdb_jdbc.jar + COMMAND ${Java_JAR_EXECUTABLE} uf duckdb_jdbc.jar -C + $ $) +endif() add_custom_target(jdbc ALL DEPENDS dummy_jdbc_target) diff --git a/CMakeLists.txt.in b/CMakeLists.txt.in index ddbd6cce8..0ee97d1f0 100644 --- a/CMakeLists.txt.in +++ b/CMakeLists.txt.in @@ -117,6 +117,41 @@ add_jar(duckdb_jdbc_nolib ${JAVA_SRC_FILES} META-INF/services/java.sql.Driver GENERATE_NATIVE_HEADERS duckdb-native) add_jar(duckdb_jdbc_tests ${JAVA_TEST_FILES} INCLUDE_JARS duckdb_jdbc_nolib) +# Java 22+ implementation of the bindings: the C API of the native library is called directly with the Foreign +# Function and Memory API, without JNI. The classes are packed into the multi-release jars (META-INF/versions/22), +# they are compiled with JDK 22+ (the JDK of the build or the one of JAVA22_HOME), the rest of the driver is compiled +# for the oldest JDK. The jars have no such classes if there is no JDK 22+. + +file(GLOB_RECURSE JAVA22_SRC_FILES src/main/java22/org/duckdb/*.java) +set(JAVAC22 "") +if(Java_VERSION_MAJOR GREATER_EQUAL 22) + set(JAVAC22 ${Java_JAVAC_EXECUTABLE}) + set(JAVA22_RELEASE ${Java_VERSION_MAJOR}) +elseif(DEFINED ENV{JAVA22_HOME}) + set(JAVAC22 "$ENV{JAVA22_HOME}/bin/javac${CMAKE_EXECUTABLE_SUFFIX}") + set(JAVA22_RELEASE 22) + set(JAR22 "$ENV{JAVA22_HOME}/bin/jar${CMAKE_EXECUTABLE_SUFFIX}") +endif() +if(NOT JAR22) + set(JAR22 ${Java_JAR_EXECUTABLE}) +endif() +if(JAVAC22 AND JAVA22_SRC_FILES AND EXISTS "${JAVAC22}") + message(STATUS "Java 22 bindings are compiled with ${JAVAC22}") + add_custom_command( + OUTPUT java22/classes.stamp + DEPENDS duckdb_jdbc_nolib ${JAVA22_SRC_FILES} + COMMAND ${CMAKE_COMMAND} -E remove_directory java22/classes + COMMAND ${CMAKE_COMMAND} -E make_directory java22/classes + COMMAND ${JAVAC22} --release ${JAVA22_RELEASE} -encoding utf-8 -g -Xlint:-restricted,-try -cp duckdb_jdbc_nolib.jar -d java22/classes + ${JAVA22_SRC_FILES} + COMMAND ${CMAKE_COMMAND} -E touch java22/classes.stamp) + add_custom_target(duckdb_jdbc_java22 DEPENDS java22/classes.stamp) + set(JAVA22_ENABLED TRUE) +else() + message(STATUS "No JDK 22+ is found (set JAVA22_HOME), the jars will have no Java 22 bindings") + set(JAVA22_ENABLED FALSE) +endif() + # main shared lib compilation @@ -138,8 +173,6 @@ if(JEMALLOC_ENABLED) 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 @@ -148,16 +181,15 @@ 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}) @@ -243,14 +275,29 @@ set_target_properties(duckdb_java PROPERTIES PREFIX "lib") # JAR packing -add_custom_command( - OUTPUT dummy_jdbc_target - DEPENDS duckdb_java duckdb_jdbc_nolib duckdb_jdbc_tests - COMMAND ${CMAKE_COMMAND} -E copy - duckdb_jdbc_nolib.jar - duckdb_jdbc.jar - COMMAND ${Java_JAR_EXECUTABLE} uf duckdb_jdbc.jar -C - $ $) +if(JAVA22_ENABLED) + add_custom_command( + OUTPUT dummy_jdbc_target + DEPENDS duckdb_java duckdb_jdbc_nolib duckdb_jdbc_tests duckdb_jdbc_java22 + COMMAND ${CMAKE_COMMAND} -E copy + duckdb_jdbc_nolib.jar + duckdb_jdbc_nolib_mr.jar + COMMAND ${JAR22} uf duckdb_jdbc_nolib_mr.jar --release 22 -C java22/classes . + COMMAND ${CMAKE_COMMAND} -E copy + duckdb_jdbc_nolib_mr.jar + duckdb_jdbc.jar + COMMAND ${Java_JAR_EXECUTABLE} uf duckdb_jdbc.jar -C + $ $) +else() + add_custom_command( + OUTPUT dummy_jdbc_target + DEPENDS duckdb_java duckdb_jdbc_nolib duckdb_jdbc_tests + COMMAND ${CMAKE_COMMAND} -E copy + duckdb_jdbc_nolib.jar + duckdb_jdbc.jar + COMMAND ${Java_JAR_EXECUTABLE} uf duckdb_jdbc.jar -C + $ $) +endif() add_custom_target(jdbc ALL DEPENDS dummy_jdbc_target) diff --git a/META-INF/MANIFEST.MF b/META-INF/MANIFEST.MF index 586c8b7d4..c958f79ed 100644 --- a/META-INF/MANIFEST.MF +++ b/META-INF/MANIFEST.MF @@ -12,3 +12,4 @@ Bundle-Copyright: Copyright (c) DuckDB Labs Export-Package: org.duckdb, org.duckdb.io, org.duckdb.user Import-Package: javax.sql, org.osgi.framework;resolution:=optional Automatic-Module-Name: duckdb.jdbc +Multi-Release: true diff --git a/README.md b/README.md index 442947117..285509d67 100644 --- a/README.md +++ b/README.md @@ -31,3 +31,20 @@ benchmark is intentionally not part of the regular test suite. Scalar function usage examples: [UDF.MD](UDF.MD) JFR memory monitoring usage: [JFR.md](JFR.md) + + +### Java 22+ (Foreign Function and Memory API) + +The jars are multi-release jars. On Java 22 and later the driver calls the C API of the native library directly with +the Foreign Function and Memory API (`java.lang.foreign`), without JNI. Older JDKs use the JNI bindings. + +The classes for Java 22+ are in `src/main/java22`. They are compiled with the JDK that builds the driver if it is 22 or +later, otherwise with the JDK in the `JAVA22_HOME` environment variable. If there is no such JDK, the jars are built +without them and always use JNI. + +To avoid the warning of the JDK about native access, run with `--enable-native-access=ALL-UNNAMED` +(or `--enable-native-access=duckdb.jdbc` on the module path). + +The symbols that the FFM bindings call are exported from the native library, `scripts/update_exports.py` updates the +symbol lists after the C API changes, `scripts/gen_ffm_native.py` and `scripts/gen_ffm_bindings.py` generate +`Capi.java` and `DuckDBBindings.java` of `src/main/java22`. 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/duckdb_java.def b/duckdb_java.def index 9ad70e84e..361d1a294 100644 --- a/duckdb_java.def +++ b/duckdb_java.def @@ -4,54 +4,6 @@ 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_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 -Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1startup Java_org_duckdb_DuckDBBindings_duckdb_1vector_1size Java_org_duckdb_DuckDBBindings_duckdb_1create_1scalar_1function @@ -108,15 +60,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 @@ -185,6 +128,117 @@ 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_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 +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 +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 +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 @@ -759,6 +813,7 @@ duckdb_v2_aggregate_function_finalize_get_state_count duckdb_v2_aggregate_function_finalize_get_states duckdb_v2_aggregate_function_finalize_get_user_data duckdb_v2_aggregate_function_get_docs +duckdb_v2_aggregate_function_get_generic_property duckdb_v2_aggregate_function_get_signature duckdb_v2_aggregate_function_init_get_bind_data duckdb_v2_aggregate_function_init_get_state_count @@ -768,15 +823,22 @@ duckdb_v2_aggregate_function_set_bind_callback duckdb_v2_aggregate_function_set_combine_callback duckdb_v2_aggregate_function_set_destroy_callback duckdb_v2_aggregate_function_set_finalize_callback +duckdb_v2_aggregate_function_set_generic_property duckdb_v2_aggregate_function_set_init_callback duckdb_v2_aggregate_function_set_name duckdb_v2_aggregate_function_set_property duckdb_v2_aggregate_function_set_size_callback +duckdb_v2_aggregate_function_set_stats_callback duckdb_v2_aggregate_function_set_update_callback duckdb_v2_aggregate_function_set_user_data duckdb_v2_aggregate_function_size_get_bind_data duckdb_v2_aggregate_function_size_get_user_data duckdb_v2_aggregate_function_size_set_state_size +duckdb_v2_aggregate_function_stats_get_arg_count +duckdb_v2_aggregate_function_stats_get_arg_stats +duckdb_v2_aggregate_function_stats_get_bind_data +duckdb_v2_aggregate_function_stats_get_result_stats +duckdb_v2_aggregate_function_stats_get_user_data duckdb_v2_aggregate_function_update_get_arg duckdb_v2_aggregate_function_update_get_arg_count duckdb_v2_aggregate_function_update_get_bind_data @@ -846,15 +908,19 @@ duckdb_v2_config_get_option_value duckdb_v2_config_set_option_text duckdb_v2_config_set_option_value duckdb_v2_connection_create +duckdb_v2_connection_create_secret duckdb_v2_connection_describe_table duckdb_v2_connection_destroy duckdb_v2_connection_enable_profiling duckdb_v2_connection_get_config duckdb_v2_connection_get_factory duckdb_v2_connection_get_file_system +duckdb_v2_connection_get_profiling_information duckdb_v2_connection_get_query_metrics +duckdb_v2_connection_get_secret_by_name duckdb_v2_connection_interrupt duckdb_v2_connection_log +duckdb_v2_connection_lookup_secret duckdb_v2_connection_progress_get duckdb_v2_connection_register_aggregate_function duckdb_v2_connection_register_cast_function @@ -865,11 +931,16 @@ duckdb_v2_connection_register_multi_file_function duckdb_v2_connection_register_pragma_function duckdb_v2_connection_register_replacement_scan duckdb_v2_connection_register_scalar_function +duckdb_v2_connection_register_secret_function duckdb_v2_connection_register_table_function +duckdb_v2_context_create_secret duckdb_v2_context_get_config duckdb_v2_context_get_factory duckdb_v2_context_get_file_system +duckdb_v2_context_get_object_cache +duckdb_v2_context_get_secret_by_name duckdb_v2_context_log +duckdb_v2_context_lookup_secret duckdb_v2_copy_from_bind_get_column_count duckdb_v2_copy_from_bind_get_column_name duckdb_v2_copy_from_bind_get_column_type @@ -947,6 +1018,28 @@ duckdb_v2_copy_to_statistics_get_init_data duckdb_v2_copy_to_statistics_get_user_data duckdb_v2_copy_to_statistics_set_file_size duckdb_v2_copy_to_statistics_set_row_count +duckdb_v2_crypto_cipher_create +duckdb_v2_crypto_cipher_destroy +duckdb_v2_crypto_cipher_finalize +duckdb_v2_crypto_cipher_init +duckdb_v2_crypto_cipher_update +duckdb_v2_crypto_hash +duckdb_v2_crypto_hash_digest_size +duckdb_v2_crypto_hmac +duckdb_v2_crypto_provider_create +duckdb_v2_crypto_provider_destroy +duckdb_v2_crypto_provider_set_cipher_create_callback +duckdb_v2_crypto_provider_set_cipher_destroy_callback +duckdb_v2_crypto_provider_set_cipher_finalize_callback +duckdb_v2_crypto_provider_set_cipher_init_callback +duckdb_v2_crypto_provider_set_cipher_update_callback +duckdb_v2_crypto_provider_set_hash_callback +duckdb_v2_crypto_provider_set_hmac_callback +duckdb_v2_crypto_provider_set_random_callback +duckdb_v2_crypto_provider_set_user_data +duckdb_v2_crypto_random_bytes +duckdb_v2_crypto_supports_hash +duckdb_v2_crypto_supports_hmac duckdb_v2_custom_option_create duckdb_v2_custom_option_destroy duckdb_v2_custom_option_set_default_scope @@ -984,6 +1077,7 @@ duckdb_v2_error_info_get_text duckdb_v2_error_info_set_code duckdb_v2_error_info_set_text duckdb_v2_expression_cast_get_mode +duckdb_v2_expression_check_statistics duckdb_v2_expression_column_ref_get_index duckdb_v2_expression_constant_get_value duckdb_v2_expression_function_get_name @@ -995,6 +1089,7 @@ duckdb_v2_expression_get_type duckdb_v2_extension_register_aggregate_function duckdb_v2_extension_register_cast_function duckdb_v2_extension_register_copy_function +duckdb_v2_extension_register_crypto_provider duckdb_v2_extension_register_custom_option duckdb_v2_extension_register_custom_type duckdb_v2_extension_register_log_sink @@ -1003,6 +1098,7 @@ duckdb_v2_extension_register_multi_file_function duckdb_v2_extension_register_pragma_function duckdb_v2_extension_register_replacement_scan duckdb_v2_extension_register_scalar_function +duckdb_v2_extension_register_secret_function duckdb_v2_extension_register_table_function duckdb_v2_factory_create_common_type duckdb_v2_factory_create_type_from_id @@ -1051,7 +1147,10 @@ duckdb_v2_instance_detach duckdb_v2_instance_get_config duckdb_v2_instance_get_factory duckdb_v2_instance_get_file_system +duckdb_v2_instance_get_object_cache duckdb_v2_instance_log +duckdb_v2_instance_open_shared +duckdb_v2_instance_register_crypto_provider duckdb_v2_instance_register_log_sink duckdb_v2_instance_register_replacement_scan duckdb_v2_instance_set_default @@ -1086,6 +1185,12 @@ duckdb_v2_multi_file_function_set_file_extension duckdb_v2_multi_file_function_set_name duckdb_v2_multi_file_function_set_reader_type duckdb_v2_multi_file_function_set_single_file_function +duckdb_v2_object_cache_delete +duckdb_v2_object_cache_entry_destroy +duckdb_v2_object_cache_entry_get_data +duckdb_v2_object_cache_get +duckdb_v2_object_cache_get_or_create +duckdb_v2_object_cache_put duckdb_v2_option_destroy duckdb_v2_option_get_alias duckdb_v2_option_get_alias_count @@ -1158,6 +1263,7 @@ duckdb_v2_scalar_function_exec_get_result duckdb_v2_scalar_function_exec_get_row_count duckdb_v2_scalar_function_exec_get_user_data duckdb_v2_scalar_function_get_docs +duckdb_v2_scalar_function_get_generic_property duckdb_v2_scalar_function_get_signature duckdb_v2_scalar_function_init_get_bind_data duckdb_v2_scalar_function_init_get_user_data @@ -1165,14 +1271,44 @@ duckdb_v2_scalar_function_init_set_init_data duckdb_v2_scalar_function_resolve_types_set_return_type duckdb_v2_scalar_function_set_bind_callback duckdb_v2_scalar_function_set_exec_callback +duckdb_v2_scalar_function_set_generic_property duckdb_v2_scalar_function_set_init_callback duckdb_v2_scalar_function_set_name duckdb_v2_scalar_function_set_property duckdb_v2_scalar_function_set_resolve_types_callback +duckdb_v2_scalar_function_set_schema +duckdb_v2_scalar_function_set_stats_callback duckdb_v2_scalar_function_set_user_data +duckdb_v2_scalar_function_stats_get_arg_count +duckdb_v2_scalar_function_stats_get_arg_stats +duckdb_v2_scalar_function_stats_get_bind_data +duckdb_v2_scalar_function_stats_get_result_stats +duckdb_v2_scalar_function_stats_get_user_data duckdb_v2_schema_destroy duckdb_v2_schema_get_count duckdb_v2_schema_get_field +duckdb_v2_secret_add_redacted_key +duckdb_v2_secret_add_scope +duckdb_v2_secret_clear_scope +duckdb_v2_secret_create +duckdb_v2_secret_destroy +duckdb_v2_secret_function_add_named_parameter +duckdb_v2_secret_function_create +duckdb_v2_secret_function_destroy +duckdb_v2_secret_function_set_create_callback +duckdb_v2_secret_function_set_default +duckdb_v2_secret_function_set_provider +duckdb_v2_secret_function_set_type +duckdb_v2_secret_function_set_user_data +duckdb_v2_secret_get_key +duckdb_v2_secret_get_key_count +duckdb_v2_secret_get_property +duckdb_v2_secret_get_scope +duckdb_v2_secret_get_scope_count +duckdb_v2_secret_get_value +duckdb_v2_secret_is_key_redacted +duckdb_v2_secret_set_property +duckdb_v2_secret_set_value duckdb_v2_sql_statement_destroy duckdb_v2_sql_statement_get_parameter_count duckdb_v2_sql_statement_get_parameter_name @@ -1184,11 +1320,22 @@ duckdb_v2_statement_execute duckdb_v2_statement_execute_arrow duckdb_v2_statement_iterator_destroy duckdb_v2_statement_iterator_next +duckdb_v2_stats_assign +duckdb_v2_stats_can_have_null +duckdb_v2_stats_can_have_valid +duckdb_v2_stats_create +duckdb_v2_stats_destroy +duckdb_v2_stats_get_value +duckdb_v2_stats_merge +duckdb_v2_stats_set_can_have_null +duckdb_v2_stats_set_can_have_valid +duckdb_v2_stats_set_value duckdb_v2_table_description_destroy duckdb_v2_table_description_get_column duckdb_v2_table_description_get_column_count duckdb_v2_table_description_get_qname duckdb_v2_table_description_is_readonly +duckdb_v2_table_function_add_virtual_column duckdb_v2_table_function_bind_add_result_column duckdb_v2_table_function_bind_set_cardinality duckdb_v2_table_function_bind_set_order_preservation @@ -1231,6 +1378,10 @@ duckdb_v2_table_function_init_local_get_column_index duckdb_v2_table_function_init_local_get_global_state duckdb_v2_table_function_init_local_get_user_data duckdb_v2_table_function_init_local_set_local_state +duckdb_v2_table_function_metrics_get_bind_data +duckdb_v2_table_function_metrics_get_global_state +duckdb_v2_table_function_metrics_get_user_data +duckdb_v2_table_function_metrics_set duckdb_v2_table_function_partition_data_get_bind_data duckdb_v2_table_function_partition_data_get_global_state duckdb_v2_table_function_partition_data_get_local_state @@ -1257,12 +1408,22 @@ duckdb_v2_table_function_set_filter_pushdown_callback duckdb_v2_table_function_set_get_bind_info_callback duckdb_v2_table_function_set_init_global_callback duckdb_v2_table_function_set_init_local_callback +duckdb_v2_table_function_set_metrics_callback duckdb_v2_table_function_set_name duckdb_v2_table_function_set_partition_data_callback duckdb_v2_table_function_set_partitioning_callback duckdb_v2_table_function_set_progress_callback duckdb_v2_table_function_set_projection_pushdown +duckdb_v2_table_function_set_stats_callback +duckdb_v2_table_function_set_to_string_callback duckdb_v2_table_function_set_user_data +duckdb_v2_table_function_stats_get_bind_data +duckdb_v2_table_function_stats_get_column_index +duckdb_v2_table_function_stats_get_result_stats +duckdb_v2_table_function_stats_get_user_data +duckdb_v2_table_function_to_string_get_bind_data +duckdb_v2_table_function_to_string_get_user_data +duckdb_v2_table_function_to_string_set duckdb_v2_token_iterator_destroy duckdb_v2_token_iterator_ends_unterminated duckdb_v2_token_iterator_next @@ -1341,6 +1502,7 @@ duckdb_v2_value_get_uuid duckdb_v2_value_get_varchar duckdb_v2_value_is_null duckdb_v2_value_to_string +duckdb_v2_value_variant_to_value duckdb_v2_vector_cast duckdb_v2_vector_constant_set_valid duckdb_v2_vector_flat_get_validity_mutable diff --git a/duckdb_java.exp b/duckdb_java.exp index aceb8881f..62b7a3fad 100644 --- a/duckdb_java.exp +++ b/duckdb_java.exp @@ -1,54 +1,6 @@ _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_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 -_Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1startup _Java_org_duckdb_DuckDBBindings_duckdb_1vector_1size _Java_org_duckdb_DuckDBBindings_duckdb_1create_1scalar_1function @@ -105,15 +57,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 @@ -182,6 +125,117 @@ _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_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 +_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 +_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 +_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 @@ -756,6 +810,7 @@ _duckdb_v2_aggregate_function_finalize_get_state_count _duckdb_v2_aggregate_function_finalize_get_states _duckdb_v2_aggregate_function_finalize_get_user_data _duckdb_v2_aggregate_function_get_docs +_duckdb_v2_aggregate_function_get_generic_property _duckdb_v2_aggregate_function_get_signature _duckdb_v2_aggregate_function_init_get_bind_data _duckdb_v2_aggregate_function_init_get_state_count @@ -765,15 +820,22 @@ _duckdb_v2_aggregate_function_set_bind_callback _duckdb_v2_aggregate_function_set_combine_callback _duckdb_v2_aggregate_function_set_destroy_callback _duckdb_v2_aggregate_function_set_finalize_callback +_duckdb_v2_aggregate_function_set_generic_property _duckdb_v2_aggregate_function_set_init_callback _duckdb_v2_aggregate_function_set_name _duckdb_v2_aggregate_function_set_property _duckdb_v2_aggregate_function_set_size_callback +_duckdb_v2_aggregate_function_set_stats_callback _duckdb_v2_aggregate_function_set_update_callback _duckdb_v2_aggregate_function_set_user_data _duckdb_v2_aggregate_function_size_get_bind_data _duckdb_v2_aggregate_function_size_get_user_data _duckdb_v2_aggregate_function_size_set_state_size +_duckdb_v2_aggregate_function_stats_get_arg_count +_duckdb_v2_aggregate_function_stats_get_arg_stats +_duckdb_v2_aggregate_function_stats_get_bind_data +_duckdb_v2_aggregate_function_stats_get_result_stats +_duckdb_v2_aggregate_function_stats_get_user_data _duckdb_v2_aggregate_function_update_get_arg _duckdb_v2_aggregate_function_update_get_arg_count _duckdb_v2_aggregate_function_update_get_bind_data @@ -843,15 +905,19 @@ _duckdb_v2_config_get_option_value _duckdb_v2_config_set_option_text _duckdb_v2_config_set_option_value _duckdb_v2_connection_create +_duckdb_v2_connection_create_secret _duckdb_v2_connection_describe_table _duckdb_v2_connection_destroy _duckdb_v2_connection_enable_profiling _duckdb_v2_connection_get_config _duckdb_v2_connection_get_factory _duckdb_v2_connection_get_file_system +_duckdb_v2_connection_get_profiling_information _duckdb_v2_connection_get_query_metrics +_duckdb_v2_connection_get_secret_by_name _duckdb_v2_connection_interrupt _duckdb_v2_connection_log +_duckdb_v2_connection_lookup_secret _duckdb_v2_connection_progress_get _duckdb_v2_connection_register_aggregate_function _duckdb_v2_connection_register_cast_function @@ -862,11 +928,16 @@ _duckdb_v2_connection_register_multi_file_function _duckdb_v2_connection_register_pragma_function _duckdb_v2_connection_register_replacement_scan _duckdb_v2_connection_register_scalar_function +_duckdb_v2_connection_register_secret_function _duckdb_v2_connection_register_table_function +_duckdb_v2_context_create_secret _duckdb_v2_context_get_config _duckdb_v2_context_get_factory _duckdb_v2_context_get_file_system +_duckdb_v2_context_get_object_cache +_duckdb_v2_context_get_secret_by_name _duckdb_v2_context_log +_duckdb_v2_context_lookup_secret _duckdb_v2_copy_from_bind_get_column_count _duckdb_v2_copy_from_bind_get_column_name _duckdb_v2_copy_from_bind_get_column_type @@ -944,6 +1015,28 @@ _duckdb_v2_copy_to_statistics_get_init_data _duckdb_v2_copy_to_statistics_get_user_data _duckdb_v2_copy_to_statistics_set_file_size _duckdb_v2_copy_to_statistics_set_row_count +_duckdb_v2_crypto_cipher_create +_duckdb_v2_crypto_cipher_destroy +_duckdb_v2_crypto_cipher_finalize +_duckdb_v2_crypto_cipher_init +_duckdb_v2_crypto_cipher_update +_duckdb_v2_crypto_hash +_duckdb_v2_crypto_hash_digest_size +_duckdb_v2_crypto_hmac +_duckdb_v2_crypto_provider_create +_duckdb_v2_crypto_provider_destroy +_duckdb_v2_crypto_provider_set_cipher_create_callback +_duckdb_v2_crypto_provider_set_cipher_destroy_callback +_duckdb_v2_crypto_provider_set_cipher_finalize_callback +_duckdb_v2_crypto_provider_set_cipher_init_callback +_duckdb_v2_crypto_provider_set_cipher_update_callback +_duckdb_v2_crypto_provider_set_hash_callback +_duckdb_v2_crypto_provider_set_hmac_callback +_duckdb_v2_crypto_provider_set_random_callback +_duckdb_v2_crypto_provider_set_user_data +_duckdb_v2_crypto_random_bytes +_duckdb_v2_crypto_supports_hash +_duckdb_v2_crypto_supports_hmac _duckdb_v2_custom_option_create _duckdb_v2_custom_option_destroy _duckdb_v2_custom_option_set_default_scope @@ -981,6 +1074,7 @@ _duckdb_v2_error_info_get_text _duckdb_v2_error_info_set_code _duckdb_v2_error_info_set_text _duckdb_v2_expression_cast_get_mode +_duckdb_v2_expression_check_statistics _duckdb_v2_expression_column_ref_get_index _duckdb_v2_expression_constant_get_value _duckdb_v2_expression_function_get_name @@ -992,6 +1086,7 @@ _duckdb_v2_expression_get_type _duckdb_v2_extension_register_aggregate_function _duckdb_v2_extension_register_cast_function _duckdb_v2_extension_register_copy_function +_duckdb_v2_extension_register_crypto_provider _duckdb_v2_extension_register_custom_option _duckdb_v2_extension_register_custom_type _duckdb_v2_extension_register_log_sink @@ -1000,6 +1095,7 @@ _duckdb_v2_extension_register_multi_file_function _duckdb_v2_extension_register_pragma_function _duckdb_v2_extension_register_replacement_scan _duckdb_v2_extension_register_scalar_function +_duckdb_v2_extension_register_secret_function _duckdb_v2_extension_register_table_function _duckdb_v2_factory_create_common_type _duckdb_v2_factory_create_type_from_id @@ -1048,7 +1144,10 @@ _duckdb_v2_instance_detach _duckdb_v2_instance_get_config _duckdb_v2_instance_get_factory _duckdb_v2_instance_get_file_system +_duckdb_v2_instance_get_object_cache _duckdb_v2_instance_log +_duckdb_v2_instance_open_shared +_duckdb_v2_instance_register_crypto_provider _duckdb_v2_instance_register_log_sink _duckdb_v2_instance_register_replacement_scan _duckdb_v2_instance_set_default @@ -1083,6 +1182,12 @@ _duckdb_v2_multi_file_function_set_file_extension _duckdb_v2_multi_file_function_set_name _duckdb_v2_multi_file_function_set_reader_type _duckdb_v2_multi_file_function_set_single_file_function +_duckdb_v2_object_cache_delete +_duckdb_v2_object_cache_entry_destroy +_duckdb_v2_object_cache_entry_get_data +_duckdb_v2_object_cache_get +_duckdb_v2_object_cache_get_or_create +_duckdb_v2_object_cache_put _duckdb_v2_option_destroy _duckdb_v2_option_get_alias _duckdb_v2_option_get_alias_count @@ -1155,6 +1260,7 @@ _duckdb_v2_scalar_function_exec_get_result _duckdb_v2_scalar_function_exec_get_row_count _duckdb_v2_scalar_function_exec_get_user_data _duckdb_v2_scalar_function_get_docs +_duckdb_v2_scalar_function_get_generic_property _duckdb_v2_scalar_function_get_signature _duckdb_v2_scalar_function_init_get_bind_data _duckdb_v2_scalar_function_init_get_user_data @@ -1162,14 +1268,44 @@ _duckdb_v2_scalar_function_init_set_init_data _duckdb_v2_scalar_function_resolve_types_set_return_type _duckdb_v2_scalar_function_set_bind_callback _duckdb_v2_scalar_function_set_exec_callback +_duckdb_v2_scalar_function_set_generic_property _duckdb_v2_scalar_function_set_init_callback _duckdb_v2_scalar_function_set_name _duckdb_v2_scalar_function_set_property _duckdb_v2_scalar_function_set_resolve_types_callback +_duckdb_v2_scalar_function_set_schema +_duckdb_v2_scalar_function_set_stats_callback _duckdb_v2_scalar_function_set_user_data +_duckdb_v2_scalar_function_stats_get_arg_count +_duckdb_v2_scalar_function_stats_get_arg_stats +_duckdb_v2_scalar_function_stats_get_bind_data +_duckdb_v2_scalar_function_stats_get_result_stats +_duckdb_v2_scalar_function_stats_get_user_data _duckdb_v2_schema_destroy _duckdb_v2_schema_get_count _duckdb_v2_schema_get_field +_duckdb_v2_secret_add_redacted_key +_duckdb_v2_secret_add_scope +_duckdb_v2_secret_clear_scope +_duckdb_v2_secret_create +_duckdb_v2_secret_destroy +_duckdb_v2_secret_function_add_named_parameter +_duckdb_v2_secret_function_create +_duckdb_v2_secret_function_destroy +_duckdb_v2_secret_function_set_create_callback +_duckdb_v2_secret_function_set_default +_duckdb_v2_secret_function_set_provider +_duckdb_v2_secret_function_set_type +_duckdb_v2_secret_function_set_user_data +_duckdb_v2_secret_get_key +_duckdb_v2_secret_get_key_count +_duckdb_v2_secret_get_property +_duckdb_v2_secret_get_scope +_duckdb_v2_secret_get_scope_count +_duckdb_v2_secret_get_value +_duckdb_v2_secret_is_key_redacted +_duckdb_v2_secret_set_property +_duckdb_v2_secret_set_value _duckdb_v2_sql_statement_destroy _duckdb_v2_sql_statement_get_parameter_count _duckdb_v2_sql_statement_get_parameter_name @@ -1181,11 +1317,22 @@ _duckdb_v2_statement_execute _duckdb_v2_statement_execute_arrow _duckdb_v2_statement_iterator_destroy _duckdb_v2_statement_iterator_next +_duckdb_v2_stats_assign +_duckdb_v2_stats_can_have_null +_duckdb_v2_stats_can_have_valid +_duckdb_v2_stats_create +_duckdb_v2_stats_destroy +_duckdb_v2_stats_get_value +_duckdb_v2_stats_merge +_duckdb_v2_stats_set_can_have_null +_duckdb_v2_stats_set_can_have_valid +_duckdb_v2_stats_set_value _duckdb_v2_table_description_destroy _duckdb_v2_table_description_get_column _duckdb_v2_table_description_get_column_count _duckdb_v2_table_description_get_qname _duckdb_v2_table_description_is_readonly +_duckdb_v2_table_function_add_virtual_column _duckdb_v2_table_function_bind_add_result_column _duckdb_v2_table_function_bind_set_cardinality _duckdb_v2_table_function_bind_set_order_preservation @@ -1228,6 +1375,10 @@ _duckdb_v2_table_function_init_local_get_column_index _duckdb_v2_table_function_init_local_get_global_state _duckdb_v2_table_function_init_local_get_user_data _duckdb_v2_table_function_init_local_set_local_state +_duckdb_v2_table_function_metrics_get_bind_data +_duckdb_v2_table_function_metrics_get_global_state +_duckdb_v2_table_function_metrics_get_user_data +_duckdb_v2_table_function_metrics_set _duckdb_v2_table_function_partition_data_get_bind_data _duckdb_v2_table_function_partition_data_get_global_state _duckdb_v2_table_function_partition_data_get_local_state @@ -1254,12 +1405,22 @@ _duckdb_v2_table_function_set_filter_pushdown_callback _duckdb_v2_table_function_set_get_bind_info_callback _duckdb_v2_table_function_set_init_global_callback _duckdb_v2_table_function_set_init_local_callback +_duckdb_v2_table_function_set_metrics_callback _duckdb_v2_table_function_set_name _duckdb_v2_table_function_set_partition_data_callback _duckdb_v2_table_function_set_partitioning_callback _duckdb_v2_table_function_set_progress_callback _duckdb_v2_table_function_set_projection_pushdown +_duckdb_v2_table_function_set_stats_callback +_duckdb_v2_table_function_set_to_string_callback _duckdb_v2_table_function_set_user_data +_duckdb_v2_table_function_stats_get_bind_data +_duckdb_v2_table_function_stats_get_column_index +_duckdb_v2_table_function_stats_get_result_stats +_duckdb_v2_table_function_stats_get_user_data +_duckdb_v2_table_function_to_string_get_bind_data +_duckdb_v2_table_function_to_string_get_user_data +_duckdb_v2_table_function_to_string_set _duckdb_v2_token_iterator_destroy _duckdb_v2_token_iterator_ends_unterminated _duckdb_v2_token_iterator_next @@ -1338,6 +1499,7 @@ _duckdb_v2_value_get_uuid _duckdb_v2_value_get_varchar _duckdb_v2_value_is_null _duckdb_v2_value_to_string +_duckdb_v2_value_variant_to_value _duckdb_v2_vector_cast _duckdb_v2_vector_constant_set_valid _duckdb_v2_vector_flat_get_validity_mutable diff --git a/duckdb_java.map b/duckdb_java.map index 972f0db48..ad28bf4fb 100644 --- a/duckdb_java.map +++ b/duckdb_java.map @@ -3,54 +3,6 @@ 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_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; - Java_org_duckdb_DuckDBNative_duckdb_1jdbc_1startup; Java_org_duckdb_DuckDBBindings_duckdb_1vector_1size; Java_org_duckdb_DuckDBBindings_duckdb_1create_1scalar_1function; @@ -107,15 +59,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; @@ -184,6 +127,117 @@ 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_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; + 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; + 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; + 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; @@ -758,6 +812,7 @@ DUCKDB_JAVA { duckdb_v2_aggregate_function_finalize_get_states; duckdb_v2_aggregate_function_finalize_get_user_data; duckdb_v2_aggregate_function_get_docs; + duckdb_v2_aggregate_function_get_generic_property; duckdb_v2_aggregate_function_get_signature; duckdb_v2_aggregate_function_init_get_bind_data; duckdb_v2_aggregate_function_init_get_state_count; @@ -767,15 +822,22 @@ DUCKDB_JAVA { duckdb_v2_aggregate_function_set_combine_callback; duckdb_v2_aggregate_function_set_destroy_callback; duckdb_v2_aggregate_function_set_finalize_callback; + duckdb_v2_aggregate_function_set_generic_property; duckdb_v2_aggregate_function_set_init_callback; duckdb_v2_aggregate_function_set_name; duckdb_v2_aggregate_function_set_property; duckdb_v2_aggregate_function_set_size_callback; + duckdb_v2_aggregate_function_set_stats_callback; duckdb_v2_aggregate_function_set_update_callback; duckdb_v2_aggregate_function_set_user_data; duckdb_v2_aggregate_function_size_get_bind_data; duckdb_v2_aggregate_function_size_get_user_data; duckdb_v2_aggregate_function_size_set_state_size; + duckdb_v2_aggregate_function_stats_get_arg_count; + duckdb_v2_aggregate_function_stats_get_arg_stats; + duckdb_v2_aggregate_function_stats_get_bind_data; + duckdb_v2_aggregate_function_stats_get_result_stats; + duckdb_v2_aggregate_function_stats_get_user_data; duckdb_v2_aggregate_function_update_get_arg; duckdb_v2_aggregate_function_update_get_arg_count; duckdb_v2_aggregate_function_update_get_bind_data; @@ -845,15 +907,19 @@ DUCKDB_JAVA { duckdb_v2_config_set_option_text; duckdb_v2_config_set_option_value; duckdb_v2_connection_create; + duckdb_v2_connection_create_secret; duckdb_v2_connection_describe_table; duckdb_v2_connection_destroy; duckdb_v2_connection_enable_profiling; duckdb_v2_connection_get_config; duckdb_v2_connection_get_factory; duckdb_v2_connection_get_file_system; + duckdb_v2_connection_get_profiling_information; duckdb_v2_connection_get_query_metrics; + duckdb_v2_connection_get_secret_by_name; duckdb_v2_connection_interrupt; duckdb_v2_connection_log; + duckdb_v2_connection_lookup_secret; duckdb_v2_connection_progress_get; duckdb_v2_connection_register_aggregate_function; duckdb_v2_connection_register_cast_function; @@ -864,11 +930,16 @@ DUCKDB_JAVA { duckdb_v2_connection_register_pragma_function; duckdb_v2_connection_register_replacement_scan; duckdb_v2_connection_register_scalar_function; + duckdb_v2_connection_register_secret_function; duckdb_v2_connection_register_table_function; + duckdb_v2_context_create_secret; duckdb_v2_context_get_config; duckdb_v2_context_get_factory; duckdb_v2_context_get_file_system; + duckdb_v2_context_get_object_cache; + duckdb_v2_context_get_secret_by_name; duckdb_v2_context_log; + duckdb_v2_context_lookup_secret; duckdb_v2_copy_from_bind_get_column_count; duckdb_v2_copy_from_bind_get_column_name; duckdb_v2_copy_from_bind_get_column_type; @@ -946,6 +1017,28 @@ DUCKDB_JAVA { duckdb_v2_copy_to_statistics_get_user_data; duckdb_v2_copy_to_statistics_set_file_size; duckdb_v2_copy_to_statistics_set_row_count; + duckdb_v2_crypto_cipher_create; + duckdb_v2_crypto_cipher_destroy; + duckdb_v2_crypto_cipher_finalize; + duckdb_v2_crypto_cipher_init; + duckdb_v2_crypto_cipher_update; + duckdb_v2_crypto_hash; + duckdb_v2_crypto_hash_digest_size; + duckdb_v2_crypto_hmac; + duckdb_v2_crypto_provider_create; + duckdb_v2_crypto_provider_destroy; + duckdb_v2_crypto_provider_set_cipher_create_callback; + duckdb_v2_crypto_provider_set_cipher_destroy_callback; + duckdb_v2_crypto_provider_set_cipher_finalize_callback; + duckdb_v2_crypto_provider_set_cipher_init_callback; + duckdb_v2_crypto_provider_set_cipher_update_callback; + duckdb_v2_crypto_provider_set_hash_callback; + duckdb_v2_crypto_provider_set_hmac_callback; + duckdb_v2_crypto_provider_set_random_callback; + duckdb_v2_crypto_provider_set_user_data; + duckdb_v2_crypto_random_bytes; + duckdb_v2_crypto_supports_hash; + duckdb_v2_crypto_supports_hmac; duckdb_v2_custom_option_create; duckdb_v2_custom_option_destroy; duckdb_v2_custom_option_set_default_scope; @@ -983,6 +1076,7 @@ DUCKDB_JAVA { duckdb_v2_error_info_set_code; duckdb_v2_error_info_set_text; duckdb_v2_expression_cast_get_mode; + duckdb_v2_expression_check_statistics; duckdb_v2_expression_column_ref_get_index; duckdb_v2_expression_constant_get_value; duckdb_v2_expression_function_get_name; @@ -994,6 +1088,7 @@ DUCKDB_JAVA { duckdb_v2_extension_register_aggregate_function; duckdb_v2_extension_register_cast_function; duckdb_v2_extension_register_copy_function; + duckdb_v2_extension_register_crypto_provider; duckdb_v2_extension_register_custom_option; duckdb_v2_extension_register_custom_type; duckdb_v2_extension_register_log_sink; @@ -1002,6 +1097,7 @@ DUCKDB_JAVA { duckdb_v2_extension_register_pragma_function; duckdb_v2_extension_register_replacement_scan; duckdb_v2_extension_register_scalar_function; + duckdb_v2_extension_register_secret_function; duckdb_v2_extension_register_table_function; duckdb_v2_factory_create_common_type; duckdb_v2_factory_create_type_from_id; @@ -1050,7 +1146,10 @@ DUCKDB_JAVA { duckdb_v2_instance_get_config; duckdb_v2_instance_get_factory; duckdb_v2_instance_get_file_system; + duckdb_v2_instance_get_object_cache; duckdb_v2_instance_log; + duckdb_v2_instance_open_shared; + duckdb_v2_instance_register_crypto_provider; duckdb_v2_instance_register_log_sink; duckdb_v2_instance_register_replacement_scan; duckdb_v2_instance_set_default; @@ -1085,6 +1184,12 @@ DUCKDB_JAVA { duckdb_v2_multi_file_function_set_name; duckdb_v2_multi_file_function_set_reader_type; duckdb_v2_multi_file_function_set_single_file_function; + duckdb_v2_object_cache_delete; + duckdb_v2_object_cache_entry_destroy; + duckdb_v2_object_cache_entry_get_data; + duckdb_v2_object_cache_get; + duckdb_v2_object_cache_get_or_create; + duckdb_v2_object_cache_put; duckdb_v2_option_destroy; duckdb_v2_option_get_alias; duckdb_v2_option_get_alias_count; @@ -1157,6 +1262,7 @@ DUCKDB_JAVA { duckdb_v2_scalar_function_exec_get_row_count; duckdb_v2_scalar_function_exec_get_user_data; duckdb_v2_scalar_function_get_docs; + duckdb_v2_scalar_function_get_generic_property; duckdb_v2_scalar_function_get_signature; duckdb_v2_scalar_function_init_get_bind_data; duckdb_v2_scalar_function_init_get_user_data; @@ -1164,14 +1270,44 @@ DUCKDB_JAVA { duckdb_v2_scalar_function_resolve_types_set_return_type; duckdb_v2_scalar_function_set_bind_callback; duckdb_v2_scalar_function_set_exec_callback; + duckdb_v2_scalar_function_set_generic_property; duckdb_v2_scalar_function_set_init_callback; duckdb_v2_scalar_function_set_name; duckdb_v2_scalar_function_set_property; duckdb_v2_scalar_function_set_resolve_types_callback; + duckdb_v2_scalar_function_set_schema; + duckdb_v2_scalar_function_set_stats_callback; duckdb_v2_scalar_function_set_user_data; + duckdb_v2_scalar_function_stats_get_arg_count; + duckdb_v2_scalar_function_stats_get_arg_stats; + duckdb_v2_scalar_function_stats_get_bind_data; + duckdb_v2_scalar_function_stats_get_result_stats; + duckdb_v2_scalar_function_stats_get_user_data; duckdb_v2_schema_destroy; duckdb_v2_schema_get_count; duckdb_v2_schema_get_field; + duckdb_v2_secret_add_redacted_key; + duckdb_v2_secret_add_scope; + duckdb_v2_secret_clear_scope; + duckdb_v2_secret_create; + duckdb_v2_secret_destroy; + duckdb_v2_secret_function_add_named_parameter; + duckdb_v2_secret_function_create; + duckdb_v2_secret_function_destroy; + duckdb_v2_secret_function_set_create_callback; + duckdb_v2_secret_function_set_default; + duckdb_v2_secret_function_set_provider; + duckdb_v2_secret_function_set_type; + duckdb_v2_secret_function_set_user_data; + duckdb_v2_secret_get_key; + duckdb_v2_secret_get_key_count; + duckdb_v2_secret_get_property; + duckdb_v2_secret_get_scope; + duckdb_v2_secret_get_scope_count; + duckdb_v2_secret_get_value; + duckdb_v2_secret_is_key_redacted; + duckdb_v2_secret_set_property; + duckdb_v2_secret_set_value; duckdb_v2_sql_statement_destroy; duckdb_v2_sql_statement_get_parameter_count; duckdb_v2_sql_statement_get_parameter_name; @@ -1183,11 +1319,22 @@ DUCKDB_JAVA { duckdb_v2_statement_execute_arrow; duckdb_v2_statement_iterator_destroy; duckdb_v2_statement_iterator_next; + duckdb_v2_stats_assign; + duckdb_v2_stats_can_have_null; + duckdb_v2_stats_can_have_valid; + duckdb_v2_stats_create; + duckdb_v2_stats_destroy; + duckdb_v2_stats_get_value; + duckdb_v2_stats_merge; + duckdb_v2_stats_set_can_have_null; + duckdb_v2_stats_set_can_have_valid; + duckdb_v2_stats_set_value; duckdb_v2_table_description_destroy; duckdb_v2_table_description_get_column; duckdb_v2_table_description_get_column_count; duckdb_v2_table_description_get_qname; duckdb_v2_table_description_is_readonly; + duckdb_v2_table_function_add_virtual_column; duckdb_v2_table_function_bind_add_result_column; duckdb_v2_table_function_bind_set_cardinality; duckdb_v2_table_function_bind_set_order_preservation; @@ -1230,6 +1377,10 @@ DUCKDB_JAVA { duckdb_v2_table_function_init_local_get_global_state; duckdb_v2_table_function_init_local_get_user_data; duckdb_v2_table_function_init_local_set_local_state; + duckdb_v2_table_function_metrics_get_bind_data; + duckdb_v2_table_function_metrics_get_global_state; + duckdb_v2_table_function_metrics_get_user_data; + duckdb_v2_table_function_metrics_set; duckdb_v2_table_function_partition_data_get_bind_data; duckdb_v2_table_function_partition_data_get_global_state; duckdb_v2_table_function_partition_data_get_local_state; @@ -1256,12 +1407,22 @@ DUCKDB_JAVA { duckdb_v2_table_function_set_get_bind_info_callback; duckdb_v2_table_function_set_init_global_callback; duckdb_v2_table_function_set_init_local_callback; + duckdb_v2_table_function_set_metrics_callback; duckdb_v2_table_function_set_name; duckdb_v2_table_function_set_partition_data_callback; duckdb_v2_table_function_set_partitioning_callback; duckdb_v2_table_function_set_progress_callback; duckdb_v2_table_function_set_projection_pushdown; + duckdb_v2_table_function_set_stats_callback; + duckdb_v2_table_function_set_to_string_callback; duckdb_v2_table_function_set_user_data; + duckdb_v2_table_function_stats_get_bind_data; + duckdb_v2_table_function_stats_get_column_index; + duckdb_v2_table_function_stats_get_result_stats; + duckdb_v2_table_function_stats_get_user_data; + duckdb_v2_table_function_to_string_get_bind_data; + duckdb_v2_table_function_to_string_get_user_data; + duckdb_v2_table_function_to_string_set; duckdb_v2_token_iterator_destroy; duckdb_v2_token_iterator_ends_unterminated; duckdb_v2_token_iterator_next; @@ -1340,6 +1501,7 @@ DUCKDB_JAVA { duckdb_v2_value_get_varchar; duckdb_v2_value_is_null; duckdb_v2_value_to_string; + duckdb_v2_value_variant_to_value; duckdb_v2_vector_cast; duckdb_v2_vector_constant_set_valid; duckdb_v2_vector_flat_get_validity_mutable; 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/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]: diff --git a/scripts/gen_ffm_bindings.py b/scripts/gen_ffm_bindings.py new file mode 100644 index 000000000..1f9be3447 --- /dev/null +++ b/scripts/gen_ffm_bindings.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +"""Generates src/main/java22/org/duckdb/DuckDBBindings.java from src/main/java/org/duckdb/DuckDBBindings.java: the +native methods (JNI) are replaced by the calls of the implementations of the C API calls with the Foreign Function and +Memory API (java.lang.foreign, JDK 22+). + +Usage: python3 scripts/gen_ffm_bindings.py +""" +import re +import sys + +SRC = 'src/main/java/org/duckdb/DuckDBBindings.java' +DST = 'src/main/java22/org/duckdb/DuckDBBindings.java' + +# the class of the implementation of a binding, by the name of the binding +RULES = [ + (r'duckdb_v2_arrow_(export_stream|register_scan_function|register_stream|release_stream|close_streams)', + 'FfmArrow'), + (r'duckdb_v2_chunked_result_create', 'FfmVectors'), + (r'duckdb_v2_.*', 'FfmV2'), + (r'duckdb_(create|destroy)_scalar_function|duckdb_scalar_function_.*|duckdb_register_scalar_function', + 'FfmFunctions'), + (r'duckdb_(bind|init|function)_.*|duckdb_(create|destroy)_table_function|duckdb_table_function_.*|' + r'duckdb_register_table_function', 'FfmFunctions'), + (r'duckdb_(create_logical_type|create_decimal_type|get_type_id|decimal_.*|create_list_type|create_array_type|' + r'create_struct_type|struct_type_.*|array_type_array_size|destroy_logical_type|enum_.*)', 'FfmTypes'), + (r'duckdb_(is_null_value|get_value_type|destroy_value|get_.*)', 'FfmValues'), + (r'duckdb_(vector_size|create_vector|destroy_vector|vector_.*|list_vector_.*|struct_vector_.*|array_vector_.*|' + r'validity_.*|create_data_chunk|destroy_data_chunk|data_chunk_.*|destroy_result|fetch_chunk|column_.*|' + r'result_error)', 'FfmVectors'), +] +# the implementation methods whose names differ from the binding names +RENAMES = {'duckdb_v2_chunked_result_create': 'createChunkedResult'} + +src = open(SRC).read() +pattern = re.compile(r'static native ([\w\[\]<>]+) (\w+)\(([^)]*)\)(\s*throws [\w, ]+)?;', re.S) + + +def target(name): + for rule, cls in RULES: + if re.fullmatch(rule, name): + return cls + print('No implementation for', name) + sys.exit(1) + + +def replace(m): + ret, name, params, throws = m.group(1), m.group(2), m.group(3), m.group(4) + args = ', '.join(p.strip().split()[-1] for p in params.split(',') if p.strip()) + call = '%s.%s(%s)' % (target(name), RENAMES.get(name, name), args) + decl = 'static %s %s(%s)%s' % (ret, name, params, throws or '') + if throws: + body = ('return %s;' if ret != 'void' else '%s;') % call + elif ret != 'void': + body = 'try {\n return %s;\n } catch (java.sql.SQLException e) {\n throw Ffm.sneaky(e);\n }' % call + else: + body = 'try {\n %s;\n } catch (java.sql.SQLException e) {\n throw Ffm.sneaky(e);\n }' % call + return '%s {\n %s\n }' % (decl, body) + + +out = pattern.sub(replace, src) +header = '// This file is generated by scripts/gen_ffm_bindings.py from src/main/java/org/duckdb/DuckDBBindings.java\n' +open(DST, 'w').write(header + out) +print('generated', len(pattern.findall(src)), 'bindings') diff --git a/scripts/gen_ffm_native.py b/scripts/gen_ffm_native.py new file mode 100644 index 000000000..bc60ecc6c --- /dev/null +++ b/scripts/gen_ffm_native.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +"""Generates src/main/java22/org/duckdb/Capi.java: the downcall handles of the C API v2 functions that are used by the +FFM implementation of the bindings (java.lang.foreign, JDK 22+). + +A function is generated if it is called as `Capi.(` in the Java sources of src/main/java22. + +Usage: python3 scripts/gen_ffm_native.py +""" +import glob +import re +import sys + +HEADER = 'src/duckdb/src/include/duckdb_v2.h' +JAVA22_DIR = 'src/main/java22/org/duckdb' +OUT = JAVA22_DIR + '/Capi.java' + +header = open(HEADER).read() + +# the enums (passed as int) and the handle typedefs (pointers) +enum_types = set(re.findall(r'\}\s*(DUCKDB_V2_[A-Z_0-9]+)\s*;', header)) +enum_types |= set(re.findall(r'typedef\s+enum\s+(DUCKDB_V2_[A-Z_0-9]+)', header)) + + +def java_type(ctype): + """Returns (java type, memory layout) of a C parameter type.""" + t = re.sub(r'\bconst\b', '', ctype).strip() + t = re.sub(r'\s+', ' ', t) + if '*' in t or t.endswith('_handle') or t.endswith('_fn') or t.endswith('_callback_fn'): + return 'MemorySegment', 'ADDRESS' + if t in ('bool', '_Bool'): + return 'boolean', 'JAVA_BOOLEAN' + if t in ('int8_t', 'uint8_t', 'char'): + return 'byte', 'JAVA_BYTE' + if t in ('int16_t', 'uint16_t'): + return 'short', 'JAVA_SHORT' + if t in ('int32_t', 'uint32_t', 'int', 'unsigned', 'unsigned int') or t in enum_types or t == 'DUCKDB_V2_ERROR': + return 'int', 'JAVA_INT' + if t in ('int64_t', 'uint64_t', 'idx_t', 'size_t'): + return 'long', 'JAVA_LONG' + if t == 'double': + return 'double', 'JAVA_DOUBLE' + if t == 'float': + return 'float', 'JAVA_FLOAT' + if t == 'void': + return 'void', None + return None, None + + +# all the functions of the header +functions = {} +for m in re.finditer(r'^DUCKDB_C_API\s+([\w ]+?\*?)\s*(duckdb_v2_[a-z0-9_]+)\(([^;]*?)\);', header, re.M | re.S): + ret, name, params = m.group(1).strip(), m.group(2), m.group(3) + plist = [] + for p in re.split(r',(?![^()]*\))', params): + p = re.sub(r'\s+', ' ', p.strip()) + if not p or p == 'void': + continue + pm = re.match(r'(.*?)(\w+)(\[\])?$', p) + ptype = pm.group(1).strip() if pm else p + pname = pm.group(2) if pm else 'p' + if pm and pm.group(3): + ptype += '*' + plist.append((ptype, pname)) + functions[name] = (ret, plist) + +# the functions that are used +used = set() +for f in glob.glob(JAVA22_DIR + '/*.java'): + if f == OUT: + continue + used |= set(re.findall(r'\bCapi\.(duckdb_v2_[a-z0-9_]+)\(', open(f).read())) + +missing = sorted(n for n in used if n not in functions) +if missing: + print('Unknown functions:', missing) + sys.exit(1) + +out = [] +out.append('''// This file is generated by scripts/gen_ffm_native.py, do not edit it. +package org.duckdb; + +import static java.lang.foreign.ValueLayout.*; + +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.MemorySegment; +import java.lang.invoke.MethodHandle; + +/** The downcalls of the C API v2 functions that the FFM bindings use. */ +final class Capi { + private Capi() { + } + + private static RuntimeException rethrow(Throwable t) { + if (t instanceof RuntimeException) { + return (RuntimeException) t; + } + if (t instanceof Error) { + throw (Error) t; + } + return new IllegalStateException(t); + } +''') +skipped = [] +for name in sorted(used): + ret, plist = functions[name] + rj, rl = java_type(ret) + jtypes = [java_type(t) for t, _ in plist] + if rj is None or any(j is None for j, _ in jtypes): + skipped.append((name, ret, plist)) + continue + args = ', '.join('%s a%d' % (j, i) for i, (j, _) in enumerate(jtypes)) + call_args = ', '.join('a%d' % i for i in range(len(jtypes))) + layouts = ', '.join(l for _, l in jtypes) + if rj == 'void': + fd = 'FunctionDescriptor.ofVoid(%s)' % layouts + else: + fd = 'FunctionDescriptor.of(%s%s)' % (rl, (', ' + layouts) if layouts else '') + out.append(''' + private static final class H_%(n)s { + static final MethodHandle MH = Ffm.downcall("%(n)s", %(fd)s); + } + + static %(rj)s %(n)s(%(args)s) { + try { + %(ret)sH_%(n)s.MH.invokeExact(%(call)s); + } catch (Throwable t) { + throw rethrow(t); + } + } +''' % dict(n=name, fd=fd, rj=rj, args=args, call=call_args, + ret='' if rj == 'void' else 'return (%s) ' % rj)) +out.append('}\n') +open(OUT, 'w').write(''.join(out)) +print('generated', len(used) - len(skipped), 'functions') +for n, r, p in skipped: + print('SKIPPED (unsupported type):', n, r, p) + sys.exit(1) diff --git a/scripts/update_exports.py b/scripts/update_exports.py new file mode 100644 index 000000000..c30805893 --- /dev/null +++ b/scripts/update_exports.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 +"""Updates the exports of the C API v2 functions in the symbol lists of the native library (duckdb_java.map, +duckdb_java.exp, duckdb_java.def): all the functions of src/duckdb/src/include/duckdb_v2.h are exported, so that they +can be called directly with the Foreign Function and Memory API. + +Usage: python3 scripts/update_exports.py +""" +import re + +HEADER = 'src/duckdb/src/include/duckdb_v2.h' + +header = open(HEADER).read() +functions = sorted(set(re.findall(r'^DUCKDB_C_API\s+[\w ]+?\*?\s*(duckdb_v2_[a-z0-9_]+)\(', header, re.M | re.S))) + +for path, fmt in [('duckdb_java.map', ' %s;'), ('duckdb_java.exp', '_%s'), ('duckdb_java.def', '%s')]: + lines = open(path).read().split('\n') + pattern = re.compile(r'^\s*_?duckdb_v2_\w+;?$') + idx = [i for i, line in enumerate(lines) if pattern.match(line)] + assert idx and idx == list(range(idx[0], idx[-1] + 1)), path + lines[idx[0]:idx[-1] + 1] = [fmt % name for name in functions] + open(path, 'w').write('\n'.join(lines)) + print(path, len(functions), 'functions') 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); 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_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_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 new file mode 100644 index 000000000..81f201760 --- /dev/null +++ b/src/jni/bindings_v2.cpp @@ -0,0 +1,1360 @@ +// 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 +#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 --- */ + +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); +} + +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), ); +} + +/* --- 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), ); +} + +/* --- 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), ); +} + +/* --- 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()); +} + +/* --- 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/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 4cf0f2c83..9e29d1f96 100644 --- a/src/jni/duckdb_java.cpp +++ b/src/jni/duckdb_java.cpp @@ -1,50 +1,8 @@ -#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/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" -#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; - 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) { @@ -73,1112 +31,3 @@ 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_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; - } - auto conn_ref = (ConnectionHolder *)env->GetDirectBufferAddress(conn_ref_buf); - if (conn_ref) { - delete conn_ref; - } -} - -#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; -} - -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); -} - -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)) { - } - - 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); - const std::string name = jstring_to_string(env, static_cast(jname)); - return ProfilerPrintFormat(name); -} - -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) { - throw InvalidInputException("Invalid connection"); - } - 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 564f6c252..000000000 --- a/src/jni/functions.cpp +++ /dev/null @@ -1,505 +0,0 @@ -// 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 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); - } catch (const std::exception &e) { - duckdb::ErrorData error(e); - ThrowJNI(env, error.Message().c_str()); - - return -1; - } -} - -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); - } 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()); - - } -} - -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_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); - } 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); - } 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 c7f72177b..000000000 --- a/src/jni/functions.hpp +++ /dev/null @@ -1,202 +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); - -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); - -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); - -void _duckdb_jdbc_arrow_close_streams(JNIEnv * env, jclass param0, jobject param1); - -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_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); - -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/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/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/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 7d4995e83..ef1ef1633 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); @@ -297,6 +276,347 @@ static native int duckdb_appender_create_ext(ByteBuffer connection, byte[] catal static native byte[] duckdb_result_error(ByteBuffer result); + // C API v2 + + 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; + + 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; + + // 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; + + // 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); + + // 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; + + // 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; + 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 diff --git a/src/main/java/org/duckdb/DuckDBConnection.java b/src/main/java/org/duckdb/DuckDBConnection.java index 2934c609f..22e810b4b 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; @@ -35,9 +36,17 @@ public final class DuckDBConnection implements java.sql.Connection { public static final String DEFAULT_SCHEMA = "main"; 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(); 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; @@ -82,27 +91,43 @@ 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); } } + 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(); @@ -143,8 +168,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(); } @@ -219,8 +244,10 @@ 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; + configRef = null; + factoryRef = null; notifyMonitor = (monitorName != null); } finally { connRefLock.unlock(); @@ -290,9 +317,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 { @@ -300,9 +324,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 { @@ -324,7 +345,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(); } @@ -335,7 +356,7 @@ public String getCatalog() throws SQLException { connRefLock.lock(); try { checkOpen(); - return DuckDBNative.duckdb_jdbc_get_catalog(connRef); + return DuckDBCore.getCatalog(this); } finally { connRefLock.unlock(); } @@ -346,7 +367,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(); } @@ -357,7 +378,7 @@ public String getSchema() throws SQLException { connRefLock.lock(); try { checkOpen(); - return DuckDBNative.duckdb_jdbc_get_schema(connRef); + return DuckDBCore.getSchema(this); } finally { connRefLock.unlock(); } @@ -582,7 +603,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 new file mode 100644 index 000000000..78b9d1ef3 --- /dev/null +++ b/src/main/java/org/duckdb/DuckDBCore.java @@ -0,0 +1,1585 @@ +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; + // the parsed statement, it is bound when the metadata is asked + ByteBuffer statement; + ByteBuffer outputSchema; + ByteBuffer parametersSchema; + // 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.statement = statement; + 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 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 + 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; + // the type details of the columns, they are the same for all the chunks + String[] detailCache; + + 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; + 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 connRef; + } + + private static long fieldCount(ByteBuffer schema) throws SQLException { + return schema == null ? 0 : duckdb_v2_schema_get_count(schema); + } + + private static boolean streamResultsOption(DuckDBConnection connection) { + try { + return duckdb_v2_config_get_bool_option(connection.config(), STREAM_RESULTS_OPTION) == 1; + } 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; + 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); + StatementRef ref = new StatementRef(connection, statementType, prepared, statement, parameterCount); + prepared = null; + statement = null; + return ref; + } finally { + if (prepared != null) { + duckdb_v2_prepared_statement_destroy(prepared); + } + if (statement != null) { + 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.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; + } + if (ref.parametersSchema != null) { + duckdb_v2_schema_destroy(ref.parametersSchema); + ref.parametersSchema = null; + } + } + } + + // 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(); + 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(connection); + 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, result, ref.statementType, ref.streaming); + } finally { + ref.conn.queryGate.release(); + } + } + + // --------------------------------------------------------------------------------------------------------- + // 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(); + } + } + + /** 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 + // --------------------------------------------------------------------------------------------------------- + + 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 = ref.conn.factory(); + 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(ref.conn); + ByteBuffer result = executePrepared(ref, params); + ResultRef res = completeResult(ref.conn, result, ref.statementType, streamResults); + res.statement = ref; + return res; + } 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(DuckDBConnection connection, 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); + 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(connection, stream ? result : null, schema, resultType, names, typeIds); + // 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); + } + } + + /** + * 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 + // --------------------------------------------------------------------------------------------------------- + + 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"; + } + } + + // 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); + } + 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"); + } + // 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); + 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, null, 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"); + } + conn(ref.connection.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 = ref.typeIds.length; + ByteBuffer factory = ref.connection.factory(); + DuckDBVector[] vectors = new DuckDBVector[columnCount]; + for (int col = 0; col < columnCount; col++) { + 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; + } + + 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); + return castToStrings(ref.connection.factory(), vec, rowCount); + } + + // 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; + } + + // 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: + 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: + if (type == null) { + return 0; + } + 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 { + 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); + 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) { + 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][]; + readStringData(duckdb_vector_get_data(vec, (long) rowCount * 16), nulls, rowCount, null, blobs); + 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]; + 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 + jvec.varlen_data = castToStrings(factory, vec, rowCount); + return jvec; + } + } + } finally { + duckdb_destroy_logical_type(type); + } + } + + /** + * 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); + 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)); + } + + 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/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/DuckDBLibrary.java b/src/main/java/org/duckdb/DuckDBLibrary.java new file mode 100644 index 000000000..13ed510d8 --- /dev/null +++ b/src/main/java/org/duckdb/DuckDBLibrary.java @@ -0,0 +1,143 @@ +package org.duckdb; + +import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.CodeSource; +import java.security.ProtectionDomain; + +/** + * Loads the native library of the driver. The library is called through JNI, see DuckDBBindings, there is another + * implementation of this class (and of DuckDBBindings) for Java 22 and newer that calls the C API of the library + * directly with the Foreign Function and Memory API. + */ +final class DuckDBLibrary { + private DuckDBLibrary() { + } + + private static final String ARCH_X86_64 = "amd64"; + private static final String ARCH_AARCH64 = "arm64"; + + private static final String OS_WINDOWS = "windows"; + private static final String OS_MACOS = "macos"; + private static final String OS_LINUX = "linux"; + + /** Loads the native library, it is loaded once. */ + static synchronized void load() { + if (loaded) { + return; + } + try { + loadNativeLibrary(); + } catch (Exception e) { + throw new RuntimeException(e); + } + loaded = true; + } + + private static boolean loaded = false; + + private static void loadNativeLibrary() throws Exception { + String libName = nativeLibName(); + URL libRes = DuckDBLibrary.class.getResource("/" + libName); + + // The current JAR has a native library bundled, in this case we unpack and load it. + // There is no fallback if the unpacking or loading fails. We expect that only + // the '-nolib' JAR can be used with an external native lib + if (null != libRes) { + unpackAndLoad(libRes); + return; + } + + // There is no native library inside the JAR file, so we try to load it by name + try { + System.loadLibrary("duckdb_java"); + } catch (UnsatisfiedLinkError e) { + // Native library cannot be loaded by name using ordinary JVM mechanisms, we try to load it directly + // from FS - from the same directory where the current JAR resides + try { + loadFromCurrentJarDir(libName); + } catch (Throwable t) { + e.printStackTrace(); + throw new IllegalStateException(t); + } + } + } + + private static String cpuArch() { + String prop = System.getProperty("os.arch").toLowerCase().trim(); + switch (prop) { + case "x86_64": + case "amd64": + return ARCH_X86_64; + case "aarch64": + case "arm64": + return ARCH_AARCH64; + default: + return prop.replaceAll("[^a-z0-9_\\-.]", ""); + } + } + + static String osName() { + String prop = System.getProperty("os.name").toLowerCase().trim(); + if (prop.startsWith("windows")) { + return OS_WINDOWS; + } else if (prop.startsWith("mac")) { + return OS_MACOS; + } else if (prop.startsWith("linux")) { + return OS_LINUX; + } else { + return prop.replaceAll("[^a-z0-9_\\-.]", ""); + } + } + + static String nativeLibName() { + return "libduckdb_java.so_" + osName() + "_" + cpuArch(); + } + + static Path currentJarDir() throws Exception { + ProtectionDomain pd = DuckDBLibrary.class.getProtectionDomain(); + CodeSource cs = pd.getCodeSource(); + URL loc = cs.getLocation(); + URI uri = loc.toURI(); + Path jarPath = Paths.get(uri); + Path dirPath = jarPath.getParent(); + return dirPath.toRealPath(); + } + + private static void unpackAndLoad(URL nativeLibRes) throws IOException { + Path tmpFile = Files.createTempFile("libduckdb_java", ".so"); + try (InputStream is = nativeLibRes.openStream()) { + Files.copy(is, tmpFile, REPLACE_EXISTING); + } + tmpFile.toFile().deleteOnExit(); + // Harmless on the officially supported platforms but required on some other. + tmpFile.toFile().setExecutable(true); + System.load(tmpFile.toAbsolutePath().toString()); + } + + private static void loadFromCurrentJarDir(String libName) throws Exception { + Path dir = currentJarDir(); + Path libPath = dir.resolve(libName); + if (Files.exists(libPath)) { + System.load(libPath.toAbsolutePath().toString()); + } else { + throw new FileNotFoundException("DuckDB JNI library not found, path: '" + libPath.toAbsolutePath() + "'"); + } + } + + // We use zero-length ByteBuffer-s as a hacky but cheap way to pass C++ pointers + // back and forth + + /* + * NB: if you change anything below, run `javah` on this class to re-generate + * the C header. CMake does this as well + */ +} diff --git a/src/main/java/org/duckdb/DuckDBNative.java b/src/main/java/org/duckdb/DuckDBNative.java index 92ce9d14c..0c15db2ee 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; @@ -19,222 +20,104 @@ final class DuckDBNative { - private static final String ARCH_X86_64 = "amd64"; - private static final String ARCH_AARCH64 = "arm64"; - - private static final String OS_WINDOWS = "windows"; - private static final String OS_MACOS = "macos"; - private static final String OS_LINUX = "linux"; - static { - try { - loadNativeLibrary(); - } catch (Exception e) { - throw new RuntimeException(e); - } + DuckDBLibrary.load(); } - private static void loadNativeLibrary() throws Exception { - String libName = nativeLibName(); - URL libRes = DuckDBNative.class.getResource("/" + libName); + // The statements, queries and results are implemented in Java on top of the C API v2 entry points of + // DuckDBBindings, see DuckDBCore - // The current JAR has a native library bundled, in this case we unpack and load it. - // There is no fallback if the unpacking or loading fails. We expect that only - // the '-nolib' JAR can be used with an external native lib - if (null != libRes) { - unpackAndLoad(libRes); - return; - } + // returns stmt_ref result reference object + static DuckDBCore.StatementRef duckdb_jdbc_prepare(DuckDBConnection conn, byte[] query) throws SQLException { + return DuckDBCore.prepare(conn, query); + } - // There is no native library inside the JAR file, so we try to load it by name + static void duckdb_jdbc_release(DuckDBCore.StatementRef stmt_ref) { try { - System.loadLibrary("duckdb_java"); - } catch (UnsatisfiedLinkError e) { - // Native library cannot be loaded by name using ordinary JVM mechanisms, we try to load it directly - // from FS - from the same directory where the current JAR resides - try { - loadFromCurrentJarDir(libName); - } catch (Throwable t) { - e.printStackTrace(); - throw new IllegalStateException(t); - } + DuckDBCore.release(stmt_ref); + } catch (SQLException e) { + // the statement is released, nothing else can be done } } - private static String cpuArch() { - String prop = System.getProperty("os.arch").toLowerCase().trim(); - switch (prop) { - case "x86_64": - case "amd64": - return ARCH_X86_64; - case "aarch64": - case "arm64": - return ARCH_AARCH64; - default: - return prop.replaceAll("[^a-z0-9_\\-.]", ""); - } + static DuckDBResultSetMetaData duckdb_jdbc_query_result_meta(DuckDBCore.ResultRef result_ref) throws SQLException { + return DuckDBCore.queryResultMeta(result_ref); } - static String osName() { - String prop = System.getProperty("os.name").toLowerCase().trim(); - if (prop.startsWith("windows")) { - return OS_WINDOWS; - } else if (prop.startsWith("mac")) { - return OS_MACOS; - } else if (prop.startsWith("linux")) { - return OS_LINUX; - } else { - return prop.replaceAll("[^a-z0-9_\\-.]", ""); - } + static DuckDBResultSetMetaData duckdb_jdbc_prepared_statement_meta(DuckDBCore.StatementRef stmt_ref) + throws SQLException { + return DuckDBCore.preparedStatementMeta(stmt_ref); } - static String nativeLibName() { - return "libduckdb_java.so_" + osName() + "_" + cpuArch(); + // returns res_ref result reference object + static DuckDBCore.ResultRef duckdb_jdbc_execute(DuckDBCore.StatementRef stmt_ref, Object[] params) + throws SQLException { + return DuckDBCore.execute(stmt_ref, params); } - static Path currentJarDir() throws Exception { - ProtectionDomain pd = DuckDBNative.class.getProtectionDomain(); - CodeSource cs = pd.getCodeSource(); - URL loc = cs.getLocation(); - URI uri = loc.toURI(); - Path jarPath = Paths.get(uri); - Path dirPath = jarPath.getParent(); - return dirPath.toRealPath(); + static ByteBuffer duckdb_jdbc_execute_capi(DuckDBCore.StatementRef stmt_ref, Object[] params) throws SQLException { + return DuckDBCore.executeChunked(stmt_ref, params); } - private static void unpackAndLoad(URL nativeLibRes) throws IOException { - Path tmpFile = Files.createTempFile("libduckdb_java", ".so"); - try (InputStream is = nativeLibRes.openStream()) { - Files.copy(is, tmpFile, REPLACE_EXISTING); - } - tmpFile.toFile().deleteOnExit(); - // Harmless on the officially supported platforms but required on some other. - tmpFile.toFile().setExecutable(true); - System.load(tmpFile.toAbsolutePath().toString()); - } - - private static void loadFromCurrentJarDir(String libName) throws Exception { - Path dir = currentJarDir(); - Path libPath = dir.resolve(libName); - if (Files.exists(libPath)) { - System.load(libPath.toAbsolutePath().toString()); - } else { - throw new FileNotFoundException("DuckDB JNI library not found, path: '" + libPath.toAbsolutePath() + "'"); - } + static DuckDBCore.PendingRef duckdb_jdbc_pending_query(DuckDBConnection conn, byte[] query) throws SQLException { + return DuckDBCore.pendingQuery(conn, query); } - // We use zero-length ByteBuffer-s as a hacky but cheap way to pass C++ pointers - // back and forth - - /* - * NB: if you change anything below, run `javah` on this class to re-generate - * 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); - - // returns stmt_ref result reference object - static native ByteBuffer duckdb_jdbc_prepare(ByteBuffer conn_ref, byte[] query) throws SQLException; - - static native void duckdb_jdbc_release(ByteBuffer stmt_ref); - - static native DuckDBResultSetMetaData duckdb_jdbc_query_result_meta(ByteBuffer result_ref) throws SQLException; - - static native DuckDBResultSetMetaData duckdb_jdbc_prepared_statement_meta(ByteBuffer stmt_ref) throws SQLException; - - // returns res_ref result reference object - static native ByteBuffer duckdb_jdbc_execute(ByteBuffer stmt_ref, Object[] params) throws SQLException; - - static native ByteBuffer duckdb_jdbc_execute_capi(ByteBuffer stmt_ref, Object[] params) throws SQLException; - - static native ByteBuffer duckdb_jdbc_pending_query(ByteBuffer conn_ref, byte[] query) throws SQLException; - - static native ByteBuffer duckdb_jdbc_execute_pending(ByteBuffer pending_ref) throws SQLException; - - static native void duckdb_jdbc_release_pending(ByteBuffer pending_ref) throws SQLException; - - static native void duckdb_jdbc_free_result(ByteBuffer res_ref); - - static native DuckDBVector[] duckdb_jdbc_fetch(ByteBuffer res_ref, ByteBuffer conn_ref) throws SQLException; - - static native String[] duckdb_jdbc_cast_result_to_strings(ByteBuffer res_ref, ByteBuffer conn_ref, long col_idx) - throws SQLException; - - static native int duckdb_jdbc_fetch_size(); - - static native long duckdb_jdbc_arrow_stream(ByteBuffer res_ref, ByteBuffer conn_ref, long batch_size); - - static native void duckdb_jdbc_arrow_register(ByteBuffer conn_ref, long arrow_array_stream_pointer, byte[] name); - - 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 native void duckdb_jdbc_interrupt(ByteBuffer conn_ref); - - static native QueryProgress duckdb_jdbc_query_progress(ByteBuffer 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 DuckDBCore.ResultRef duckdb_jdbc_execute_pending(DuckDBCore.PendingRef pending_ref) throws SQLException { + return DuckDBCore.executePending(pending_ref); + } - static native void duckdb_jdbc_appender_append_short(ByteBuffer appender_ref, short value) throws SQLException; + static void duckdb_jdbc_release_pending(DuckDBCore.PendingRef pending_ref) throws SQLException { + DuckDBCore.releasePending(pending_ref); + } - static native void duckdb_jdbc_appender_append_int(ByteBuffer appender_ref, int value) throws SQLException; + 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 void duckdb_jdbc_appender_append_long(ByteBuffer appender_ref, long value) throws SQLException; + static DuckDBVector[] duckdb_jdbc_fetch(DuckDBCore.ResultRef res_ref, ByteBuffer conn_ref) throws SQLException { + return DuckDBCore.fetch(res_ref); + } - static native void duckdb_jdbc_appender_append_float(ByteBuffer appender_ref, float value) 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 void duckdb_jdbc_appender_append_double(ByteBuffer appender_ref, double value) throws SQLException; + 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); + } - static native void duckdb_jdbc_appender_append_string(ByteBuffer appender_ref, byte[] value) throws SQLException; + static void duckdb_jdbc_arrow_register(DuckDBConnection conn, long arrow_array_stream_pointer, String name) + throws SQLException { + DuckDBCore.registerArrowStream(conn, arrow_array_stream_pointer, name); + } - static native void duckdb_jdbc_appender_append_bytes(ByteBuffer appender_ref, byte[] value) throws SQLException; + static void duckdb_jdbc_arrow_close_streams(ByteBuffer conn_ref) { + DuckDBBindings.duckdb_v2_arrow_close_streams(conn_ref); + } - static native void duckdb_jdbc_appender_append_timestamp(ByteBuffer appender_ref, long value) throws SQLException; + static int duckdb_jdbc_fetch_size() { + return (int) DuckDBBindings.duckdb_vector_size(); + } - static native void duckdb_jdbc_appender_append_decimal(ByteBuffer appender_ref, BigDecimal value) - throws SQLException; + static void duckdb_jdbc_interrupt(ByteBuffer conn_ref) throws SQLException { + DuckDBBindings.duckdb_v2_connection_interrupt(conn_ref); + } - static native void duckdb_jdbc_appender_append_null(ByteBuffer appender_ref) throws SQLException; + static QueryProgress duckdb_jdbc_query_progress(ByteBuffer conn_ref) throws SQLException { + 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); + } } 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..57b651364 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,14 +170,12 @@ 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 { conn.connRefLock.unlock(); } - - meta = DuckDBNative.duckdb_jdbc_prepared_statement_meta(stmtRef); } catch (SQLException e) { close(); throw e; @@ -193,7 +191,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 +204,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 +221,7 @@ public boolean execute() throws SQLException { connLock.lock(); connLock.unlock(); - ByteBuffer resultRef = null; + DuckDBCore.ResultRef resultRef = null; DuckDBPendingQuery pendingQuery = null; boolean queryFailed = false; @@ -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 @@ -1598,10 +1610,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..7f31efe42 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); @@ -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 8f25f2867..5715b7e1f 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(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..d331556a1 --- /dev/null +++ b/src/main/java/org/duckdb/DuckDBV2Appender.java @@ -0,0 +1,273 @@ +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 = 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 = 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(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/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); diff --git a/src/main/java22/org/duckdb/Capi.java b/src/main/java22/org/duckdb/Capi.java new file mode 100644 index 000000000..f7c4340b3 --- /dev/null +++ b/src/main/java22/org/duckdb/Capi.java @@ -0,0 +1,2886 @@ +// This file is generated by scripts/gen_ffm_native.py, do not edit it. +package org.duckdb; + +import static java.lang.foreign.ValueLayout.*; + +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.MemorySegment; +import java.lang.invoke.MethodHandle; + +/** The downcalls of the C API v2 functions that the FFM bindings use. */ +final class Capi { + private Capi() { + } + + private static RuntimeException rethrow(Throwable t) { + if (t instanceof RuntimeException) { + return (RuntimeException) t; + } + if (t instanceof Error) { + throw(Error) t; + } + return new IllegalStateException(t); + } + + private static final class H_duckdb_v2_arena_allocate { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_arena_allocate", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_arena_allocate(MemorySegment a0, long a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_arena_allocate.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_arrow_importer_append { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_arrow_importer_append", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_BOOLEAN, JAVA_BOOLEAN, ADDRESS)); + } + + static int duckdb_v2_arrow_importer_append(MemorySegment a0, MemorySegment a1, boolean a2, boolean a3, + MemorySegment a4) { + try { + return (int) H_duckdb_v2_arrow_importer_append.MH.invokeExact(a0, a1, a2, a3, a4); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_arrow_importer_create { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_arrow_importer_create", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_arrow_importer_create(MemorySegment a0, MemorySegment a1, long a2, MemorySegment a3, + MemorySegment a4) { + try { + return (int) H_duckdb_v2_arrow_importer_create.MH.invokeExact(a0, a1, a2, a3, a4); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_arrow_importer_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_arrow_importer_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_arrow_importer_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_arrow_importer_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_arrow_importer_get_schema { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_arrow_importer_get_schema", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_arrow_importer_get_schema(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_arrow_importer_get_schema.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_arrow_importer_next_chunk { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_arrow_importer_next_chunk", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_arrow_importer_next_chunk(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_arrow_importer_next_chunk.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_arrow_result_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_arrow_result_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_arrow_result_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_arrow_result_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_arrow_result_to_arrow_c_stream { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_arrow_result_to_arrow_c_stream", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_arrow_result_to_arrow_c_stream(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_arrow_result_to_arrow_c_stream.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_column_data_collection_append { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_column_data_collection_append", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_column_data_collection_append(MemorySegment a0, MemorySegment a1, MemorySegment a2, + MemorySegment a3) { + try { + return (int) H_duckdb_v2_column_data_collection_append.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_column_data_collection_append_state_create { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_column_data_collection_append_state_create", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_column_data_collection_append_state_create(MemorySegment a0, MemorySegment a1, + MemorySegment a2) { + try { + return (int) H_duckdb_v2_column_data_collection_append_state_create.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_column_data_collection_append_state_destroy { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_column_data_collection_append_state_destroy", + FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_column_data_collection_append_state_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_column_data_collection_append_state_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_column_data_collection_clear { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_column_data_collection_clear", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_column_data_collection_clear(MemorySegment a0, MemorySegment a1) { + try { + return (int) H_duckdb_v2_column_data_collection_clear.MH.invokeExact(a0, a1); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_column_data_collection_create { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_column_data_collection_create", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_column_data_collection_create(MemorySegment a0, MemorySegment a1, long a2, MemorySegment a3, + MemorySegment a4) { + try { + return (int) H_duckdb_v2_column_data_collection_create.MH.invokeExact(a0, a1, a2, a3, a4); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_column_data_collection_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_column_data_collection_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_column_data_collection_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_column_data_collection_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_column_data_collection_row_count { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_column_data_collection_row_count", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_column_data_collection_row_count(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_column_data_collection_row_count.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_config_get_option_by_index { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_config_get_option_by_index", + FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_config_get_option_by_index(MemorySegment a0, long a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_config_get_option_by_index.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_config_get_option_count { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_config_get_option_count", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_config_get_option_count(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_config_get_option_count.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_config_get_option_value { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_config_get_option_value", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_config_get_option_value(MemorySegment a0, MemorySegment a1, long a2, MemorySegment a3, + MemorySegment a4, MemorySegment a5) { + try { + return (int) H_duckdb_v2_config_get_option_value.MH.invokeExact(a0, a1, a2, a3, a4, a5); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_config_set_option_text { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_config_set_option_text", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, JAVA_LONG, JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_config_set_option_text(MemorySegment a0, MemorySegment a1, long a2, MemorySegment a3, long a4, + int a5, MemorySegment a6) { + try { + return (int) H_duckdb_v2_config_set_option_text.MH.invokeExact(a0, a1, a2, a3, a4, a5, a6); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_config_set_option_value { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_config_set_option_value", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_config_set_option_value(MemorySegment a0, MemorySegment a1, long a2, MemorySegment a3, int a4, + MemorySegment a5) { + try { + return (int) H_duckdb_v2_config_set_option_value.MH.invokeExact(a0, a1, a2, a3, a4, a5); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_connection_create { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_connection_create", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_connection_create(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_connection_create.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_connection_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_connection_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_connection_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_connection_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_connection_get_config { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_connection_get_config", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_connection_get_config(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_connection_get_config.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_connection_get_factory { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_connection_get_factory", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_connection_get_factory(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_connection_get_factory.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_connection_get_profiling_information { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_connection_get_profiling_information", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_connection_get_profiling_information(MemorySegment a0, MemorySegment a1, long a2, + MemorySegment a3, MemorySegment a4, MemorySegment a5) { + try { + return (int) H_duckdb_v2_connection_get_profiling_information.MH.invokeExact(a0, a1, a2, a3, a4, a5); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_connection_interrupt { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_connection_interrupt", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_connection_interrupt(MemorySegment a0, MemorySegment a1) { + try { + return (int) H_duckdb_v2_connection_interrupt.MH.invokeExact(a0, a1); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_connection_progress_get { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_connection_progress_get", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_connection_progress_get(MemorySegment a0, MemorySegment a1, MemorySegment a2, MemorySegment a3, + MemorySegment a4) { + try { + return (int) H_duckdb_v2_connection_progress_get.MH.invokeExact(a0, a1, a2, a3, a4); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_connection_register_custom_option { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_connection_register_custom_option", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_connection_register_custom_option(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_connection_register_custom_option.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_connection_register_scalar_function { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_connection_register_scalar_function", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_connection_register_scalar_function(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_connection_register_scalar_function.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_connection_register_table_function { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_connection_register_table_function", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_connection_register_table_function(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_connection_register_table_function.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_context_get_factory { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_context_get_factory", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_context_get_factory(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_context_get_factory.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_custom_option_create { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_custom_option_create", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_custom_option_create(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_custom_option_create.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_custom_option_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_custom_option_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_custom_option_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_custom_option_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_custom_option_set_default_scope { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_custom_option_set_default_scope", + FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_custom_option_set_default_scope(MemorySegment a0, int a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_custom_option_set_default_scope.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_custom_option_set_default_value { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_custom_option_set_default_value", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_custom_option_set_default_value(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_custom_option_set_default_value.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_custom_option_set_description { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_custom_option_set_description", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS)); + } + + static int duckdb_v2_custom_option_set_description(MemorySegment a0, MemorySegment a1, long a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_custom_option_set_description.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_custom_option_set_name { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_custom_option_set_name", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS)); + } + + static int duckdb_v2_custom_option_set_name(MemorySegment a0, MemorySegment a1, long a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_custom_option_set_name.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_custom_option_set_supports_scope { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_custom_option_set_supports_scope", + FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_INT, JAVA_BOOLEAN, ADDRESS)); + } + + static int duckdb_v2_custom_option_set_supports_scope(MemorySegment a0, int a1, boolean a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_custom_option_set_supports_scope.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_custom_option_set_type { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_custom_option_set_type", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_custom_option_set_type(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_custom_option_set_type.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_chunk_clear { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_data_chunk_clear", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_chunk_clear(MemorySegment a0, MemorySegment a1) { + try { + return (int) H_duckdb_v2_data_chunk_clear.MH.invokeExact(a0, a1); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_chunk_create { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_data_chunk_create", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_chunk_create(MemorySegment a0, MemorySegment a1, long a2, MemorySegment a3, + MemorySegment a4) { + try { + return (int) H_duckdb_v2_data_chunk_create.MH.invokeExact(a0, a1, a2, a3, a4); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_chunk_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_data_chunk_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_data_chunk_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_data_chunk_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_chunk_get_capacity { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_data_chunk_get_capacity", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_chunk_get_capacity(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_data_chunk_get_capacity.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_chunk_get_size { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_data_chunk_get_size", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_chunk_get_size(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_data_chunk_get_size.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_chunk_get_vector { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_data_chunk_get_vector", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_chunk_get_vector(MemorySegment a0, long a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_data_chunk_get_vector.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_chunk_get_vector_count { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_data_chunk_get_vector_count", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_chunk_get_vector_count(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_data_chunk_get_vector_count.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_environment_create { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_environment_create", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_environment_create(MemorySegment a0, MemorySegment a1) { + try { + return (int) H_duckdb_v2_environment_create.MH.invokeExact(a0, a1); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_environment_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_environment_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_environment_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_environment_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_error_info_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_error_info_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_error_info_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_error_info_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_error_info_get_code { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_error_info_get_code", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_error_info_get_code(MemorySegment a0, MemorySegment a1) { + try { + return (int) H_duckdb_v2_error_info_get_code.MH.invokeExact(a0, a1); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_error_info_get_raw_text { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_error_info_get_raw_text", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_error_info_get_raw_text(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_error_info_get_raw_text.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_error_info_get_text { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_error_info_get_text", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_error_info_get_text(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_error_info_get_text.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_error_info_set_code { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_error_info_set_code", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_INT)); + } + + static int duckdb_v2_error_info_set_code(MemorySegment a0, int a1) { + try { + return (int) H_duckdb_v2_error_info_set_code.MH.invokeExact(a0, a1); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_error_info_set_text { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_error_info_set_text", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG)); + } + + static int duckdb_v2_error_info_set_text(MemorySegment a0, MemorySegment a1, long a2) { + try { + return (int) H_duckdb_v2_error_info_set_text.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_factory_create_type_from_id { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_factory_create_type_from_id", + FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_INT, ADDRESS, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_factory_create_type_from_id(MemorySegment a0, int a1, MemorySegment a2, MemorySegment a3, + MemorySegment a4, long a5, MemorySegment a6, MemorySegment a7) { + try { + return (int) H_duckdb_v2_factory_create_type_from_id.MH.invokeExact(a0, a1, a2, a3, a4, a5, a6, a7); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_factory_create_type_from_text { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_factory_create_type_from_text", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_factory_create_type_from_text(MemorySegment a0, MemorySegment a1, long a2, MemorySegment a3, + MemorySegment a4) { + try { + return (int) H_duckdb_v2_factory_create_type_from_text.MH.invokeExact(a0, a1, a2, a3, a4); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_function_bind_get_arg_count { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_function_bind_get_arg_count", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_function_bind_get_arg_count(MemorySegment a0, MemorySegment a1, MemorySegment a2, + MemorySegment a3, MemorySegment a4, MemorySegment a5) { + try { + return (int) H_duckdb_v2_function_bind_get_arg_count.MH.invokeExact(a0, a1, a2, a3, a4, a5); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_function_bind_get_arg_name { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_function_bind_get_arg_name", + FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_function_bind_get_arg_name(MemorySegment a0, long a1, MemorySegment a2, MemorySegment a3, + MemorySegment a4) { + try { + return (int) H_duckdb_v2_function_bind_get_arg_name.MH.invokeExact(a0, a1, a2, a3, a4); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_function_bind_get_arg_value { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_function_bind_get_arg_value", + FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_function_bind_get_arg_value(MemorySegment a0, long a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_function_bind_get_arg_value.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_function_bind_get_user_data { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_function_bind_get_user_data", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_function_bind_get_user_data(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_function_bind_get_user_data.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_function_bind_set_bind_data { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_function_bind_set_bind_data", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_function_bind_set_bind_data(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_function_bind_set_bind_data.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_function_signature_add_parameter { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_function_signature_add_parameter", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS, JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_function_signature_add_parameter(MemorySegment a0, MemorySegment a1, long a2, MemorySegment a3, + MemorySegment a4, int a5, MemorySegment a6) { + try { + return (int) H_duckdb_v2_function_signature_add_parameter.MH.invokeExact(a0, a1, a2, a3, a4, a5, a6); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_function_signature_set_return_type { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_function_signature_set_return_type", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_function_signature_set_return_type(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_function_signature_set_return_type.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_instance_attach { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_instance_attach", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, + JAVA_LONG, ADDRESS, JAVA_BOOLEAN, ADDRESS)); + } + + static int duckdb_v2_instance_attach(MemorySegment a0, MemorySegment a1, long a2, MemorySegment a3, long a4, + MemorySegment a5, boolean a6, MemorySegment a7) { + try { + return (int) H_duckdb_v2_instance_attach.MH.invokeExact(a0, a1, a2, a3, a4, a5, a6, a7); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_instance_create_with_options { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_instance_create_with_options", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_instance_create_with_options(MemorySegment a0, MemorySegment a1, MemorySegment a2, + MemorySegment a3, MemorySegment a4, long a5, MemorySegment a6, + MemorySegment a7) { + try { + return (int) H_duckdb_v2_instance_create_with_options.MH.invokeExact(a0, a1, a2, a3, a4, a5, a6, a7); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_instance_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_instance_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_instance_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_instance_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_instance_get_config { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_instance_get_config", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_instance_get_config(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_instance_get_config.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_instance_get_factory { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_instance_get_factory", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_instance_get_factory(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_instance_get_factory.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_instance_open_shared { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_instance_open_shared", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS, ADDRESS, + ADDRESS, JAVA_LONG, ADDRESS, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_instance_open_shared(MemorySegment a0, MemorySegment a1, long a2, MemorySegment a3, + MemorySegment a4, MemorySegment a5, MemorySegment a6, long a7, + MemorySegment a8, MemorySegment a9, MemorySegment a10, + MemorySegment a11) { + try { + return (int) H_duckdb_v2_instance_open_shared.MH.invokeExact(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, + a11); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_logical_type_copy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_logical_type_copy", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_logical_type_copy(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_logical_type_copy.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_logical_type_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_logical_type_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_logical_type_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_logical_type_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_logical_type_get_id { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_logical_type_get_id", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_logical_type_get_id(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_logical_type_get_id.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_logical_type_get_param { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_logical_type_get_param", + FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_logical_type_get_param(MemorySegment a0, long a1, MemorySegment a2, MemorySegment a3, + MemorySegment a4, MemorySegment a5) { + try { + return (int) H_duckdb_v2_logical_type_get_param.MH.invokeExact(a0, a1, a2, a3, a4, a5); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_logical_type_get_param_count { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_logical_type_get_param_count", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_logical_type_get_param_count(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_logical_type_get_param_count.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_logical_type_is_equal { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_logical_type_is_equal", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_logical_type_is_equal(MemorySegment a0, MemorySegment a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_logical_type_is_equal.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_logical_type_to_text { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_logical_type_to_text", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_logical_type_to_text(MemorySegment a0, MemorySegment a1, long a2, MemorySegment a3, + MemorySegment a4) { + try { + return (int) H_duckdb_v2_logical_type_to_text.MH.invokeExact(a0, a1, a2, a3, a4); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_option_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_option_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_option_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_option_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_option_get_name { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_option_get_name", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_option_get_name(MemorySegment a0, MemorySegment a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_option_get_name.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_option_supports_scope { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_option_supports_scope", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_INT, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_option_supports_scope(MemorySegment a0, int a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_option_supports_scope.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_parse_sql { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_parse_sql", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, JAVA_BOOLEAN, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_parse_sql(MemorySegment a0, MemorySegment a1, long a2, boolean a3, MemorySegment a4, + MemorySegment a5) { + try { + return (int) H_duckdb_v2_parse_sql.MH.invokeExact(a0, a1, a2, a3, a4, a5); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_prepared_statement_create { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_prepared_statement_create", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_BOOLEAN, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_prepared_statement_create(MemorySegment a0, MemorySegment a1, boolean a2, MemorySegment a3, + MemorySegment a4) { + try { + return (int) H_duckdb_v2_prepared_statement_create.MH.invokeExact(a0, a1, a2, a3, a4); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_prepared_statement_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_prepared_statement_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_prepared_statement_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_prepared_statement_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_prepared_statement_execute { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_prepared_statement_execute", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_prepared_statement_execute(MemorySegment a0, MemorySegment a1, MemorySegment a2, + MemorySegment a3, long a4, MemorySegment a5, MemorySegment a6) { + try { + return (int) H_duckdb_v2_prepared_statement_execute.MH.invokeExact(a0, a1, a2, a3, a4, a5, a6); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_result_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_result_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_result_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_result_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_result_drain { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_result_drain", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_result_drain(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_result_drain.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_result_fetch_chunk { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_result_fetch_chunk", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_result_fetch_chunk(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_result_fetch_chunk.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_result_get_result_type { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_result_get_result_type", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_result_get_result_type(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_result_get_result_type.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_result_get_schema { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_result_get_schema", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_result_get_schema(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_result_get_schema.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_result_get_statement_type { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_result_get_statement_type", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_result_get_statement_type(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_result_get_statement_type.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_result_step { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_result_step", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_result_step(MemorySegment a0, MemorySegment a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_result_step.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_result_wait { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_result_wait", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_result_wait(MemorySegment a0, MemorySegment a1) { + try { + return (int) H_duckdb_v2_result_wait.MH.invokeExact(a0, a1); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_scalar_function_create { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_scalar_function_create", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_scalar_function_create(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_scalar_function_create.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_scalar_function_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_scalar_function_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_scalar_function_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_scalar_function_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_scalar_function_exec_get_arg { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_scalar_function_exec_get_arg", + FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_scalar_function_exec_get_arg(MemorySegment a0, long a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_scalar_function_exec_get_arg.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_scalar_function_exec_get_arg_count { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_scalar_function_exec_get_arg_count", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_scalar_function_exec_get_arg_count(MemorySegment a0, MemorySegment a1, MemorySegment a2, + MemorySegment a3, MemorySegment a4, MemorySegment a5) { + try { + return (int) H_duckdb_v2_scalar_function_exec_get_arg_count.MH.invokeExact(a0, a1, a2, a3, a4, a5); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_scalar_function_exec_get_init_data { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_scalar_function_exec_get_init_data", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_scalar_function_exec_get_init_data(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_scalar_function_exec_get_init_data.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_scalar_function_exec_get_result { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_scalar_function_exec_get_result", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_scalar_function_exec_get_result(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_scalar_function_exec_get_result.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_scalar_function_exec_get_row_count { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_scalar_function_exec_get_row_count", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_scalar_function_exec_get_row_count(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_scalar_function_exec_get_row_count.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_scalar_function_exec_get_user_data { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_scalar_function_exec_get_user_data", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_scalar_function_exec_get_user_data(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_scalar_function_exec_get_user_data.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_scalar_function_get_signature { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_scalar_function_get_signature", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_scalar_function_get_signature(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_scalar_function_get_signature.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_scalar_function_init_set_init_data { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_scalar_function_init_set_init_data", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_scalar_function_init_set_init_data(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_scalar_function_init_set_init_data.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_scalar_function_set_exec_callback { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_scalar_function_set_exec_callback", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_scalar_function_set_exec_callback(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_scalar_function_set_exec_callback.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_scalar_function_set_init_callback { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_scalar_function_set_init_callback", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_scalar_function_set_init_callback(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_scalar_function_set_init_callback.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_scalar_function_set_name { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_scalar_function_set_name", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS)); + } + + static int duckdb_v2_scalar_function_set_name(MemorySegment a0, MemorySegment a1, long a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_scalar_function_set_name.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_scalar_function_set_property { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_scalar_function_set_property", + FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_INT, JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_scalar_function_set_property(MemorySegment a0, int a1, int a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_scalar_function_set_property.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_scalar_function_set_user_data { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_scalar_function_set_user_data", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_scalar_function_set_user_data(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_scalar_function_set_user_data.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_schema_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_schema_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_schema_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_schema_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_schema_get_count { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_schema_get_count", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_schema_get_count(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_schema_get_count.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_schema_get_field { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_schema_get_field", + FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_schema_get_field(MemorySegment a0, long a1, MemorySegment a2, MemorySegment a3, + MemorySegment a4, MemorySegment a5) { + try { + return (int) H_duckdb_v2_schema_get_field.MH.invokeExact(a0, a1, a2, a3, a4, a5); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_sql_statement_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_sql_statement_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_sql_statement_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_sql_statement_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_sql_statement_get_parameter_count { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_sql_statement_get_parameter_count", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_sql_statement_get_parameter_count(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_sql_statement_get_parameter_count.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_sql_statement_get_type { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_sql_statement_get_type", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_sql_statement_get_type(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_sql_statement_get_type.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_statement_add_collection { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_statement_add_collection", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, + ADDRESS, ADDRESS, JAVA_LONG, ADDRESS)); + } + + static int duckdb_v2_statement_add_collection(MemorySegment a0, MemorySegment a1, long a2, MemorySegment a3, + MemorySegment a4, MemorySegment a5, long a6, MemorySegment a7) { + try { + return (int) H_duckdb_v2_statement_add_collection.MH.invokeExact(a0, a1, a2, a3, a4, a5, a6, a7); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_statement_bind { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_statement_bind", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_statement_bind(MemorySegment a0, MemorySegment a1, MemorySegment a2, MemorySegment a3, + MemorySegment a4) { + try { + return (int) H_duckdb_v2_statement_bind.MH.invokeExact(a0, a1, a2, a3, a4); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_statement_execute { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_statement_execute", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_statement_execute(MemorySegment a0, MemorySegment a1, MemorySegment a2, MemorySegment a3, + MemorySegment a4, long a5, MemorySegment a6, MemorySegment a7) { + try { + return (int) H_duckdb_v2_statement_execute.MH.invokeExact(a0, a1, a2, a3, a4, a5, a6, a7); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_statement_execute_arrow { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_statement_execute_arrow", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS, ADDRESS, JAVA_LONG, + JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_statement_execute_arrow(MemorySegment a0, MemorySegment a1, MemorySegment a2, MemorySegment a3, + MemorySegment a4, long a5, long a6, MemorySegment a7, + MemorySegment a8) { + try { + return (int) H_duckdb_v2_statement_execute_arrow.MH.invokeExact(a0, a1, a2, a3, a4, a5, a6, a7, a8); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_statement_iterator_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_statement_iterator_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_statement_iterator_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_statement_iterator_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_statement_iterator_next { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_statement_iterator_next", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_statement_iterator_next(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_statement_iterator_next.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_bind_add_result_column { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_table_function_bind_add_result_column", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_bind_add_result_column(MemorySegment a0, MemorySegment a1, long a2, + MemorySegment a3, MemorySegment a4) { + try { + return (int) H_duckdb_v2_table_function_bind_add_result_column.MH.invokeExact(a0, a1, a2, a3, a4); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_bind_set_cardinality { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_table_function_bind_set_cardinality", + FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, JAVA_BOOLEAN, ADDRESS)); + } + + static int duckdb_v2_table_function_bind_set_cardinality(MemorySegment a0, long a1, boolean a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_table_function_bind_set_cardinality.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_create { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_table_function_create", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_create(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_create.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_table_function_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_table_function_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_table_function_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_exec_get_bind_data { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_function_exec_get_bind_data", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_exec_get_bind_data(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_exec_get_bind_data.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_exec_get_global_state { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_function_exec_get_global_state", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_exec_get_global_state(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_exec_get_global_state.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_exec_get_local_state { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_function_exec_get_local_state", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_exec_get_local_state(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_exec_get_local_state.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_exec_get_output_chunk { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_function_exec_get_output_chunk", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_exec_get_output_chunk(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_exec_get_output_chunk.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_exec_get_user_data { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_function_exec_get_user_data", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_exec_get_user_data(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_exec_get_user_data.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_get_signature { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_function_get_signature", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_get_signature(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_get_signature.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_init_global_get_bind_data { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_function_init_global_get_bind_data", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_init_global_get_bind_data(MemorySegment a0, MemorySegment a1, + MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_init_global_get_bind_data.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_init_global_get_column_count { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_function_init_global_get_column_count", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_init_global_get_column_count(MemorySegment a0, MemorySegment a1, + MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_init_global_get_column_count.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_init_global_get_column_index { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_table_function_init_global_get_column_index", + FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_init_global_get_column_index(MemorySegment a0, long a1, MemorySegment a2, + MemorySegment a3) { + try { + return (int) H_duckdb_v2_table_function_init_global_get_column_index.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_init_global_get_user_data { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_function_init_global_get_user_data", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_init_global_get_user_data(MemorySegment a0, MemorySegment a1, + MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_init_global_get_user_data.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_init_global_set_global_state { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_function_init_global_set_global_state", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_init_global_set_global_state(MemorySegment a0, MemorySegment a1, + MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_init_global_set_global_state.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_init_global_set_max_threads { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_function_init_global_set_max_threads", + FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS)); + } + + static int duckdb_v2_table_function_init_global_set_max_threads(MemorySegment a0, long a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_init_global_set_max_threads.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_init_local_get_bind_data { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_function_init_local_get_bind_data", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_init_local_get_bind_data(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_init_local_get_bind_data.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_init_local_get_column_count { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_function_init_local_get_column_count", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_init_local_get_column_count(MemorySegment a0, MemorySegment a1, + MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_init_local_get_column_count.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_init_local_get_column_index { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_table_function_init_local_get_column_index", + FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_init_local_get_column_index(MemorySegment a0, long a1, MemorySegment a2, + MemorySegment a3) { + try { + return (int) H_duckdb_v2_table_function_init_local_get_column_index.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_init_local_get_user_data { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_function_init_local_get_user_data", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_init_local_get_user_data(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_init_local_get_user_data.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_init_local_set_local_state { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_function_init_local_set_local_state", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_init_local_set_local_state(MemorySegment a0, MemorySegment a1, + MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_init_local_set_local_state.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_set_bind_callback { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_function_set_bind_callback", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_set_bind_callback(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_set_bind_callback.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_set_exec_callback { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_function_set_exec_callback", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_set_exec_callback(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_set_exec_callback.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_set_init_global_callback { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_function_set_init_global_callback", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_set_init_global_callback(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_set_init_global_callback.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_set_init_local_callback { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_function_set_init_local_callback", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_set_init_local_callback(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_set_init_local_callback.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_set_name { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_table_function_set_name", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS)); + } + + static int duckdb_v2_table_function_set_name(MemorySegment a0, MemorySegment a1, long a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_table_function_set_name.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_set_projection_pushdown { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_function_set_projection_pushdown", + FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_BOOLEAN, ADDRESS)); + } + + static int duckdb_v2_table_function_set_projection_pushdown(MemorySegment a0, boolean a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_set_projection_pushdown.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_function_set_user_data { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_function_set_user_data", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_set_user_data(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_set_user_data.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_validate_utf8 { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_validate_utf8", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS)); + } + + static int duckdb_v2_validate_utf8(MemorySegment a0, long a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_validate_utf8.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_cast { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_value_cast", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_cast(MemorySegment a0, MemorySegment a1, MemorySegment a2, MemorySegment a3, + MemorySegment a4) { + try { + return (int) H_duckdb_v2_value_cast.MH.invokeExact(a0, a1, a2, a3, a4); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_bigint { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_value_create_bigint", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_bigint(MemorySegment a0, long a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_value_create_bigint.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_blob { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_create_blob", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_blob(MemorySegment a0, MemorySegment a1, long a2, MemorySegment a3, + MemorySegment a4) { + try { + return (int) H_duckdb_v2_value_create_blob.MH.invokeExact(a0, a1, a2, a3, a4); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_bool { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_value_create_bool", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_BOOLEAN, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_bool(MemorySegment a0, boolean a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_value_create_bool.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_date { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_value_create_date", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_INT, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_date(MemorySegment a0, int a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_value_create_date.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_decimal { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_create_decimal", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_INT, JAVA_INT, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_decimal(MemorySegment a0, MemorySegment a1, int a2, int a3, MemorySegment a4, + MemorySegment a5) { + try { + return (int) H_duckdb_v2_value_create_decimal.MH.invokeExact(a0, a1, a2, a3, a4, a5); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_double { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_value_create_double", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_DOUBLE, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_double(MemorySegment a0, double a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_value_create_double.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_float { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_value_create_float", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_FLOAT, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_float(MemorySegment a0, float a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_value_create_float.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_hugeint { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_value_create_hugeint", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_hugeint(MemorySegment a0, MemorySegment a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_value_create_hugeint.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_int { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_value_create_int", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_INT, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_int(MemorySegment a0, int a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_value_create_int.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_list { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_create_list", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_list(MemorySegment a0, MemorySegment a1, MemorySegment a2, long a3, + MemorySegment a4, MemorySegment a5) { + try { + return (int) H_duckdb_v2_value_create_list.MH.invokeExact(a0, a1, a2, a3, a4, a5); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_map { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_value_create_map", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_map(MemorySegment a0, MemorySegment a1, MemorySegment a2, MemorySegment a3, + MemorySegment a4, long a5, MemorySegment a6, MemorySegment a7) { + try { + return (int) H_duckdb_v2_value_create_map.MH.invokeExact(a0, a1, a2, a3, a4, a5, a6, a7); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_null { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_value_create_null", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_null(MemorySegment a0, MemorySegment a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_value_create_null.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_smallint { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_value_create_smallint", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_SHORT, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_smallint(MemorySegment a0, short a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_value_create_smallint.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_struct { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_create_struct", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, + ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_struct(MemorySegment a0, MemorySegment a1, MemorySegment a2, MemorySegment a3, + long a4, MemorySegment a5, MemorySegment a6) { + try { + return (int) H_duckdb_v2_value_create_struct.MH.invokeExact(a0, a1, a2, a3, a4, a5, a6); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_time { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_value_create_time", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_time(MemorySegment a0, long a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_value_create_time.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_timestamp { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_value_create_timestamp", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_timestamp(MemorySegment a0, long a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_value_create_timestamp.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_timestamp_ns { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_create_timestamp_ns", + FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_timestamp_ns(MemorySegment a0, long a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_value_create_timestamp_ns.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_timestamp_tz { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_create_timestamp_tz", + FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_timestamp_tz(MemorySegment a0, long a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_value_create_timestamp_tz.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_tinyint { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_value_create_tinyint", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_BYTE, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_tinyint(MemorySegment a0, byte a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_value_create_tinyint.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_type { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_value_create_type", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_type(MemorySegment a0, MemorySegment a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_value_create_type.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_ubigint { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_value_create_ubigint", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_ubigint(MemorySegment a0, long a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_value_create_ubigint.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_utinyint { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_value_create_utinyint", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_BYTE, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_utinyint(MemorySegment a0, byte a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_value_create_utinyint.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_uuid { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_value_create_uuid", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_uuid(MemorySegment a0, MemorySegment a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_value_create_uuid.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_create_varchar { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_create_varchar", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_varchar(MemorySegment a0, MemorySegment a1, long a2, MemorySegment a3, + MemorySegment a4) { + try { + return (int) H_duckdb_v2_value_create_varchar.MH.invokeExact(a0, a1, a2, a3, a4); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_value_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_value_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_get_bigint { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_get_bigint", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_bigint(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_value_get_bigint.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_get_bool { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_get_bool", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_bool(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_value_get_bool.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_get_date { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_get_date", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_date(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_value_get_date.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_get_decimal { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_get_decimal", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_decimal(MemorySegment a0, MemorySegment a1, MemorySegment a2, MemorySegment a3, + MemorySegment a4) { + try { + return (int) H_duckdb_v2_value_get_decimal.MH.invokeExact(a0, a1, a2, a3, a4); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_get_double { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_get_double", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_double(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_value_get_double.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_get_float { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_get_float", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_float(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_value_get_float.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_get_hugeint { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_get_hugeint", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_hugeint(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_value_get_hugeint.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_get_int { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_get_int", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_int(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_value_get_int.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_get_logical_type { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_value_get_logical_type", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_logical_type(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_value_get_logical_type.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_get_smallint { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_get_smallint", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_smallint(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_value_get_smallint.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_get_timestamp { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_get_timestamp", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_timestamp(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_value_get_timestamp.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_get_timestamp_ms { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_value_get_timestamp_ms", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_timestamp_ms(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_value_get_timestamp_ms.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_get_timestamp_ns { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_value_get_timestamp_ns", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_timestamp_ns(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_value_get_timestamp_ns.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_get_timestamp_sec { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_value_get_timestamp_sec", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_timestamp_sec(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_value_get_timestamp_sec.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_get_tinyint { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_get_tinyint", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_tinyint(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_value_get_tinyint.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_get_type { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_get_type", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_type(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_value_get_type.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_get_ubigint { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_get_ubigint", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_ubigint(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_value_get_ubigint.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_get_uhugeint { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_get_uhugeint", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_uhugeint(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_value_get_uhugeint.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_get_uint { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_get_uint", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_uint(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_value_get_uint.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_get_usmallint { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_get_usmallint", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_usmallint(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_value_get_usmallint.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_get_utinyint { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_get_utinyint", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_utinyint(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_value_get_utinyint.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_get_varchar { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_value_get_varchar", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_varchar(MemorySegment a0, MemorySegment a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_value_get_varchar.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_is_null { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_is_null", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_is_null(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_value_is_null.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_to_string { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_value_to_string", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_to_string(MemorySegment a0, MemorySegment a1, long a2, MemorySegment a3, + MemorySegment a4) { + try { + return (int) H_duckdb_v2_value_to_string.MH.invokeExact(a0, a1, a2, a3, a4); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_value_variant_to_value { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_value_variant_to_value", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_variant_to_value(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_value_variant_to_value.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_vector_cast { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_vector_cast", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, JAVA_INT, + ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_vector_cast(MemorySegment a0, MemorySegment a1, MemorySegment a2, int a3, MemorySegment a4, + MemorySegment a5, MemorySegment a6) { + try { + return (int) H_duckdb_v2_vector_cast.MH.invokeExact(a0, a1, a2, a3, a4, a5, a6); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_vector_flat_get_validity_mutable { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_vector_flat_get_validity_mutable", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_vector_flat_get_validity_mutable(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_vector_flat_get_validity_mutable.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_vector_flatten { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_vector_flatten", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_vector_flatten(MemorySegment a0, MemorySegment a1) { + try { + return (int) H_duckdb_v2_vector_flatten.MH.invokeExact(a0, a1); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_vector_get_arena { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_vector_get_arena", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_vector_get_arena(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_vector_get_arena.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_vector_get_child { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_vector_get_child", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_vector_get_child(MemorySegment a0, long a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_vector_get_child.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_vector_get_data_mutable { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_vector_get_data_mutable", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_vector_get_data_mutable(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_vector_get_data_mutable.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_vector_get_logical_type { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_vector_get_logical_type", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_vector_get_logical_type(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_vector_get_logical_type.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_vector_get_size { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_vector_get_size", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_vector_get_size(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_vector_get_size.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_vector_get_value { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_vector_get_value", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_vector_get_value(MemorySegment a0, long a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_vector_get_value.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_vector_get_vector_type { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_vector_get_vector_type", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_vector_get_vector_type(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_vector_get_vector_type.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_vector_get_view { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_vector_get_view", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_vector_get_view(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_vector_get_view.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_vector_reference { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_vector_reference", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_vector_reference(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_vector_reference.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_vector_set_size { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_vector_set_size", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS)); + } + + static int duckdb_v2_vector_set_size(MemorySegment a0, long a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_vector_set_size.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_vector_set_value { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_vector_set_value", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_vector_set_value(MemorySegment a0, long a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_vector_set_value.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } +} diff --git a/src/main/java22/org/duckdb/DuckDBBindings.java b/src/main/java22/org/duckdb/DuckDBBindings.java new file mode 100644 index 000000000..f8e64f10b --- /dev/null +++ b/src/main/java22/org/duckdb/DuckDBBindings.java @@ -0,0 +1,1663 @@ +// This file is generated by scripts/gen_ffm_bindings.py from src/main/java/org/duckdb/DuckDBBindings.java +package org.duckdb; + +import static org.duckdb.JdbcUtils.createSQLException; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.sql.SQLException; + +public class DuckDBBindings { + + static { + try { + Class.forName(DuckDBNative.class.getName()); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + } + + // common + + static long duckdb_vector_size() { + try { + return FfmVectors.duckdb_vector_size(); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + // scalar function + + static ByteBuffer duckdb_create_scalar_function() { + try { + return FfmFunctions.duckdb_create_scalar_function(); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_destroy_scalar_function(ByteBuffer scalarFunction) { + try { + FfmFunctions.duckdb_destroy_scalar_function(scalarFunction); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_scalar_function_set_name(ByteBuffer scalarFunction, byte[] name) { + try { + FfmFunctions.duckdb_scalar_function_set_name(scalarFunction, name); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_scalar_function_add_parameter(ByteBuffer scalarFunction, ByteBuffer logicalType) { + try { + FfmFunctions.duckdb_scalar_function_add_parameter(scalarFunction, logicalType); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_scalar_function_set_return_type(ByteBuffer scalarFunction, ByteBuffer logicalType) { + try { + FfmFunctions.duckdb_scalar_function_set_return_type(scalarFunction, logicalType); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_scalar_function_set_varargs(ByteBuffer scalarFunction, ByteBuffer logicalType) { + try { + FfmFunctions.duckdb_scalar_function_set_varargs(scalarFunction, logicalType); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_scalar_function_set_volatile(ByteBuffer scalarFunction) { + try { + FfmFunctions.duckdb_scalar_function_set_volatile(scalarFunction); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_scalar_function_set_special_handling(ByteBuffer scalarFunction) { + try { + FfmFunctions.duckdb_scalar_function_set_special_handling(scalarFunction); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static int duckdb_register_scalar_function(ByteBuffer connection, ByteBuffer scalarFunction) { + try { + return FfmFunctions.duckdb_register_scalar_function(connection, scalarFunction); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_scalar_function_set_extra_info(ByteBuffer scalarFunction, Object callback) { + try { + FfmFunctions.duckdb_scalar_function_set_extra_info(scalarFunction, callback); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_scalar_function_set_function(ByteBuffer scalarFunction) { + try { + FfmFunctions.duckdb_scalar_function_set_function(scalarFunction); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_scalar_function_set_error(ByteBuffer functionInfo, byte[] error) { + try { + FfmFunctions.duckdb_scalar_function_set_error(functionInfo, error); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + // table function bind + + static void duckdb_bind_add_result_column(ByteBuffer bind_info, byte[] name, ByteBuffer logical_type) { + try { + FfmFunctions.duckdb_bind_add_result_column(bind_info, name, logical_type); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static long duckdb_bind_get_parameter_count(ByteBuffer bind_info) { + try { + return FfmFunctions.duckdb_bind_get_parameter_count(bind_info); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static ByteBuffer duckdb_bind_get_parameter(ByteBuffer bind_info, long index) { + try { + return FfmFunctions.duckdb_bind_get_parameter(bind_info, index); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static ByteBuffer duckdb_bind_get_named_parameter(ByteBuffer bind_info, byte[] name) { + try { + return FfmFunctions.duckdb_bind_get_named_parameter(bind_info, name); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_bind_set_bind_data(ByteBuffer bind_info, Object bind_data) { + try { + FfmFunctions.duckdb_bind_set_bind_data(bind_info, bind_data); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_bind_set_cardinality(ByteBuffer bind_info, long cardinality, boolean is_exact) { + try { + FfmFunctions.duckdb_bind_set_cardinality(bind_info, cardinality, is_exact); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_bind_set_error(ByteBuffer bind_info, byte[] error) { + try { + FfmFunctions.duckdb_bind_set_error(bind_info, error); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + // table function init + + static Object duckdb_init_get_bind_data(ByteBuffer init_info) { + try { + return FfmFunctions.duckdb_init_get_bind_data(init_info); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_init_set_init_data(ByteBuffer init_info, Object init_data) { + try { + FfmFunctions.duckdb_init_set_init_data(init_info, init_data); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static long duckdb_init_get_column_count(ByteBuffer init_info) { + try { + return FfmFunctions.duckdb_init_get_column_count(init_info); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static long duckdb_init_get_column_index(ByteBuffer init_info, long column_index) { + try { + return FfmFunctions.duckdb_init_get_column_index(init_info, column_index); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_init_set_max_threads(ByteBuffer init_info, long max_threads) { + try { + FfmFunctions.duckdb_init_set_max_threads(init_info, max_threads); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_init_set_error(ByteBuffer init_info, byte[] error) { + try { + FfmFunctions.duckdb_init_set_error(init_info, error); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + // table function + + static ByteBuffer duckdb_create_table_function() { + try { + return FfmFunctions.duckdb_create_table_function(); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_destroy_table_function(ByteBuffer table_function) { + try { + FfmFunctions.duckdb_destroy_table_function(table_function); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_table_function_set_name(ByteBuffer table_function, byte[] name) { + try { + FfmFunctions.duckdb_table_function_set_name(table_function, name); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_table_function_add_parameter(ByteBuffer table_function, ByteBuffer logical_type) { + try { + FfmFunctions.duckdb_table_function_add_parameter(table_function, logical_type); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_table_function_add_named_parameter(ByteBuffer table_function, byte[] name, + ByteBuffer logical_type) { + try { + FfmFunctions.duckdb_table_function_add_named_parameter(table_function, name, logical_type); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_table_function_set_extra_info(ByteBuffer table_function, DuckDBTableFunctionWrapper callback) { + try { + FfmFunctions.duckdb_table_function_set_extra_info(table_function, callback); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_table_function_set_bind(ByteBuffer table_function) { + try { + FfmFunctions.duckdb_table_function_set_bind(table_function); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_table_function_set_init(ByteBuffer table_function) { + try { + FfmFunctions.duckdb_table_function_set_init(table_function); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_table_function_set_local_init(ByteBuffer table_function) { + try { + FfmFunctions.duckdb_table_function_set_local_init(table_function); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_table_function_set_function(ByteBuffer table_function) { + try { + FfmFunctions.duckdb_table_function_set_function(table_function); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_table_function_supports_projection_pushdown(ByteBuffer table_function, boolean pushdown) { + try { + FfmFunctions.duckdb_table_function_supports_projection_pushdown(table_function, pushdown); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static int duckdb_register_table_function(ByteBuffer connection, ByteBuffer table_function) { + try { + return FfmFunctions.duckdb_register_table_function(connection, table_function); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static Object duckdb_function_get_bind_data(ByteBuffer table_function_info) { + try { + return FfmFunctions.duckdb_function_get_bind_data(table_function_info); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static Object duckdb_function_get_init_data(ByteBuffer table_function_info) { + try { + return FfmFunctions.duckdb_function_get_init_data(table_function_info); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static Object duckdb_function_get_local_init_data(ByteBuffer table_function_info) { + try { + return FfmFunctions.duckdb_function_get_local_init_data(table_function_info); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_function_set_error(ByteBuffer table_function_info, byte[] error) { + try { + FfmFunctions.duckdb_function_set_error(table_function_info, error); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + // logical type + + static ByteBuffer duckdb_create_logical_type(int duckdb_type) { + try { + return FfmTypes.duckdb_create_logical_type(duckdb_type); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static ByteBuffer duckdb_create_decimal_type(int width, int scale) { + try { + return FfmTypes.duckdb_create_decimal_type(width, scale); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static int duckdb_get_type_id(ByteBuffer logical_type) { + try { + return FfmTypes.duckdb_get_type_id(logical_type); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static int duckdb_decimal_width(ByteBuffer logical_type) { + try { + return FfmTypes.duckdb_decimal_width(logical_type); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static int duckdb_decimal_scale(ByteBuffer logical_type) { + try { + return FfmTypes.duckdb_decimal_scale(logical_type); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static int duckdb_decimal_internal_type(ByteBuffer logical_type) { + try { + return FfmTypes.duckdb_decimal_internal_type(logical_type); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static ByteBuffer duckdb_create_list_type(ByteBuffer logical_type) { + try { + return FfmTypes.duckdb_create_list_type(logical_type); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static ByteBuffer duckdb_create_array_type(ByteBuffer logical_type, long array_size) { + try { + return FfmTypes.duckdb_create_array_type(logical_type, array_size); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static ByteBuffer duckdb_create_struct_type(ByteBuffer[] member_types, byte[][] member_names) { + try { + return FfmTypes.duckdb_create_struct_type(member_types, member_names); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static long duckdb_struct_type_child_count(ByteBuffer logical_type) { + try { + return FfmTypes.duckdb_struct_type_child_count(logical_type); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static byte[] duckdb_struct_type_child_name(ByteBuffer logical_type, long index) { + try { + return FfmTypes.duckdb_struct_type_child_name(logical_type, index); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static long duckdb_array_type_array_size(ByteBuffer logical_type) { + try { + return FfmTypes.duckdb_array_type_array_size(logical_type); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_destroy_logical_type(ByteBuffer logical_type) { + try { + FfmTypes.duckdb_destroy_logical_type(logical_type); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static int duckdb_enum_internal_type(ByteBuffer logical_type) { + try { + return FfmTypes.duckdb_enum_internal_type(logical_type); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static long duckdb_enum_dictionary_size(ByteBuffer logical_type) { + try { + return FfmTypes.duckdb_enum_dictionary_size(logical_type); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static byte[] duckdb_enum_dictionary_value(ByteBuffer logical_type, long index) { + try { + return FfmTypes.duckdb_enum_dictionary_value(logical_type, index); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + // vector + + static ByteBuffer duckdb_create_vector(ByteBuffer logical_type) { + try { + return FfmVectors.duckdb_create_vector(logical_type); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_destroy_vector(ByteBuffer vector) { + try { + FfmVectors.duckdb_destroy_vector(vector); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static ByteBuffer duckdb_vector_get_column_type(ByteBuffer vector) { + try { + return FfmVectors.duckdb_vector_get_column_type(vector); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static ByteBuffer duckdb_vector_get_data(ByteBuffer vector, long size_bytes) { + try { + return FfmVectors.duckdb_vector_get_data(vector, size_bytes); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static ByteBuffer duckdb_vector_get_data_zeroed(ByteBuffer vector, long size_bytes) { + try { + return FfmVectors.duckdb_vector_get_data_zeroed(vector, size_bytes); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static ByteBuffer duckdb_vector_get_validity(ByteBuffer vector, long vector_size_elems) { + try { + return FfmVectors.duckdb_vector_get_validity(vector, vector_size_elems); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_vector_ensure_validity_writable(ByteBuffer vector) { + try { + FfmVectors.duckdb_vector_ensure_validity_writable(vector); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_vector_assign_string_element_len(ByteBuffer vector, long index, byte[] str) { + try { + FfmVectors.duckdb_vector_assign_string_element_len(vector, index, str); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_vector_assign_string_elements(ByteBuffer vector, long index, byte[] data, long[] lengths, + int dataLength) { + try { + FfmVectors.duckdb_vector_assign_string_elements(vector, index, data, lengths, dataLength); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static byte[] duckdb_vector_get_string(ByteBuffer vectorData, long row) { + try { + return FfmVectors.duckdb_vector_get_string(vectorData, row); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static ByteBuffer duckdb_list_vector_get_child(ByteBuffer vector) { + try { + return FfmVectors.duckdb_list_vector_get_child(vector); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static long duckdb_list_vector_get_size(ByteBuffer vector) { + try { + return FfmVectors.duckdb_list_vector_get_size(vector); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static int duckdb_list_vector_set_size(ByteBuffer vector, long size) { + try { + return FfmVectors.duckdb_list_vector_set_size(vector, size); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static int duckdb_list_vector_reserve(ByteBuffer vector, long capacity) { + try { + return FfmVectors.duckdb_list_vector_reserve(vector, capacity); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static ByteBuffer duckdb_struct_vector_get_child(ByteBuffer vector, long index) { + try { + return FfmVectors.duckdb_struct_vector_get_child(vector, index); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static ByteBuffer duckdb_array_vector_get_child(ByteBuffer vector) { + try { + return FfmVectors.duckdb_array_vector_get_child(vector); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + // validity + + static boolean duckdb_validity_row_is_valid(ByteBuffer validity, long row) { + try { + return FfmVectors.duckdb_validity_row_is_valid(validity, row); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_validity_set_row_validity(ByteBuffer validity, long row, boolean valid) { + try { + FfmVectors.duckdb_validity_set_row_validity(validity, row, valid); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + // data chunk + + static ByteBuffer duckdb_create_data_chunk(ByteBuffer[] logical_types) { + try { + return FfmVectors.duckdb_create_data_chunk(logical_types); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_destroy_data_chunk(ByteBuffer chunk) { + try { + FfmVectors.duckdb_destroy_data_chunk(chunk); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_data_chunk_reset(ByteBuffer chunk) { + try { + FfmVectors.duckdb_data_chunk_reset(chunk); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static long duckdb_data_chunk_get_column_count(ByteBuffer chunk) { + try { + return FfmVectors.duckdb_data_chunk_get_column_count(chunk); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static ByteBuffer duckdb_data_chunk_get_vector(ByteBuffer chunk, long col_idx) { + try { + return FfmVectors.duckdb_data_chunk_get_vector(chunk, col_idx); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static long duckdb_data_chunk_get_size(ByteBuffer chunk) { + try { + return FfmVectors.duckdb_data_chunk_get_size(chunk); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_data_chunk_set_size(ByteBuffer chunk, long size) { + try { + FfmVectors.duckdb_data_chunk_set_size(chunk, size); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + // value + + static boolean duckdb_is_null_value(ByteBuffer value) { + try { + return FfmValues.duckdb_is_null_value(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static int duckdb_get_value_type(ByteBuffer value) { + try { + return FfmValues.duckdb_get_value_type(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static void duckdb_destroy_value(ByteBuffer value) { + try { + FfmValues.duckdb_destroy_value(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static boolean duckdb_get_bool(ByteBuffer value) { + try { + return FfmValues.duckdb_get_bool(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static byte duckdb_get_int8(ByteBuffer value) { + try { + return FfmValues.duckdb_get_int8(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static short duckdb_get_uint8(ByteBuffer value) { + try { + return FfmValues.duckdb_get_uint8(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static short duckdb_get_int16(ByteBuffer value) { + try { + return FfmValues.duckdb_get_int16(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static int duckdb_get_uint16(ByteBuffer value) { + try { + return FfmValues.duckdb_get_uint16(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static int duckdb_get_int32(ByteBuffer value) { + try { + return FfmValues.duckdb_get_int32(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static long duckdb_get_uint32(ByteBuffer value) { + try { + return FfmValues.duckdb_get_uint32(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static long duckdb_get_int64(ByteBuffer value) { + try { + return FfmValues.duckdb_get_int64(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static long duckdb_get_uint64(ByteBuffer value) { + try { + return FfmValues.duckdb_get_uint64(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static BigInteger duckdb_get_hugeint(ByteBuffer value) { + try { + return FfmValues.duckdb_get_hugeint(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static BigInteger duckdb_get_uhugeint(ByteBuffer value) { + try { + return FfmValues.duckdb_get_uhugeint(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static BigInteger duckdb_get_bignum(ByteBuffer value) { + try { + return FfmValues.duckdb_get_bignum(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static BigDecimal duckdb_get_decimal(ByteBuffer value) { + try { + return FfmValues.duckdb_get_decimal(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static float duckdb_get_float(ByteBuffer value) { + try { + return FfmValues.duckdb_get_float(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static double duckdb_get_double(ByteBuffer value) { + try { + return FfmValues.duckdb_get_double(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static int duckdb_get_date(ByteBuffer value) { + try { + return FfmValues.duckdb_get_date(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static long duckdb_get_time(ByteBuffer value) { + try { + return FfmValues.duckdb_get_time(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static long duckdb_get_time_ns(ByteBuffer value) { + try { + return FfmValues.duckdb_get_time_ns(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static long duckdb_get_time_tz(ByteBuffer value) { + try { + return FfmValues.duckdb_get_time_tz(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static long duckdb_get_timestamp(ByteBuffer value) { + try { + return FfmValues.duckdb_get_timestamp(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static long duckdb_get_timestamp_tz(ByteBuffer value) { + try { + return FfmValues.duckdb_get_timestamp_tz(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static long duckdb_get_timestamp_s(ByteBuffer value) { + try { + return FfmValues.duckdb_get_timestamp_s(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static long duckdb_get_timestamp_ms(ByteBuffer value) { + try { + return FfmValues.duckdb_get_timestamp_ms(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static long duckdb_get_timestamp_ns(ByteBuffer value) { + try { + return FfmValues.duckdb_get_timestamp_ns(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static byte[] duckdb_get_varchar(ByteBuffer value) { + try { + return FfmValues.duckdb_get_varchar(value); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + // result + + static void duckdb_destroy_result(ByteBuffer result) { + try { + FfmVectors.duckdb_destroy_result(result); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static ByteBuffer duckdb_fetch_chunk(ByteBuffer result) { + try { + return FfmVectors.duckdb_fetch_chunk(result); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static byte[] duckdb_column_name(ByteBuffer result, long col) { + try { + return FfmVectors.duckdb_column_name(result, col); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static int duckdb_column_type(ByteBuffer result, long col) { + try { + return FfmVectors.duckdb_column_type(result, col); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static long duckdb_column_count(ByteBuffer result) { + try { + return FfmVectors.duckdb_column_count(result); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + static byte[] duckdb_result_error(ByteBuffer result) { + try { + return FfmVectors.duckdb_result_error(result); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + // C API v2 + + static void duckdb_v2_connection_interrupt(ByteBuffer conn) throws SQLException { + FfmV2.duckdb_v2_connection_interrupt(conn); + } + + static QueryProgress duckdb_v2_connection_progress_get(ByteBuffer conn) throws SQLException { + return FfmV2.duckdb_v2_connection_progress_get(conn); + } + + static ByteBuffer duckdb_v2_parse_sql(ByteBuffer conn, byte[] sql) throws SQLException { + return FfmV2.duckdb_v2_parse_sql(conn, sql); + } + + // returns null when there are no more statements + static ByteBuffer duckdb_v2_statement_iterator_next(ByteBuffer iterator) throws SQLException { + return FfmV2.duckdb_v2_statement_iterator_next(iterator); + } + + static void duckdb_v2_statement_iterator_destroy(ByteBuffer iterator) throws SQLException { + FfmV2.duckdb_v2_statement_iterator_destroy(iterator); + } + + static void duckdb_v2_sql_statement_destroy(ByteBuffer statement) throws SQLException { + FfmV2.duckdb_v2_sql_statement_destroy(statement); + } + + static int duckdb_v2_sql_statement_get_type(ByteBuffer statement) throws SQLException { + return FfmV2.duckdb_v2_sql_statement_get_type(statement); + } + + static long duckdb_v2_sql_statement_get_parameter_count(ByteBuffer statement) throws SQLException { + return FfmV2.duckdb_v2_sql_statement_get_parameter_count(statement); + } + + static ByteBuffer duckdb_v2_prepared_statement_create(ByteBuffer conn, ByteBuffer statement, + boolean require_cacheable) throws SQLException { + return FfmV2.duckdb_v2_prepared_statement_create(conn, statement, require_cacheable); + } + + static void duckdb_v2_prepared_statement_destroy(ByteBuffer prepared) throws SQLException { + FfmV2.duckdb_v2_prepared_statement_destroy(prepared); + } + + // the values are borrowed for the call + static ByteBuffer duckdb_v2_prepared_statement_execute(ByteBuffer prepared, ByteBuffer[] values) + throws SQLException { + return FfmV2.duckdb_v2_prepared_statement_execute(prepared, values); + } + + static ByteBuffer duckdb_v2_statement_execute(ByteBuffer conn, ByteBuffer statement, ByteBuffer[] values) + throws SQLException { + return FfmV2.duckdb_v2_statement_execute(conn, statement, values); + } + + // returns the output schema and the parameters schema + static ByteBuffer[] duckdb_v2_statement_bind(ByteBuffer conn, ByteBuffer statement) throws SQLException { + return FfmV2.duckdb_v2_statement_bind(conn, statement); + } + + static void duckdb_v2_schema_destroy(ByteBuffer schema) throws SQLException { + FfmV2.duckdb_v2_schema_destroy(schema); + } + + static long duckdb_v2_schema_get_count(ByteBuffer schema) throws SQLException { + return FfmV2.duckdb_v2_schema_get_count(schema); + } + + static byte[] duckdb_v2_schema_get_field_name(ByteBuffer schema, long index) throws SQLException { + return FfmV2.duckdb_v2_schema_get_field_name(schema, index); + } + + // the returned type is borrowed from the schema and must not be destroyed + static ByteBuffer duckdb_v2_schema_get_field_type(ByteBuffer schema, long index) throws SQLException { + return FfmV2.duckdb_v2_schema_get_field_type(schema, index); + } + + static void duckdb_v2_result_destroy(ByteBuffer result) throws SQLException { + FfmV2.duckdb_v2_result_destroy(result); + } + + static ByteBuffer duckdb_v2_result_get_schema(ByteBuffer result) throws SQLException { + return FfmV2.duckdb_v2_result_get_schema(result); + } + + static int duckdb_v2_result_get_result_type(ByteBuffer result) throws SQLException { + return FfmV2.duckdb_v2_result_get_result_type(result); + } + + static int duckdb_v2_result_get_statement_type(ByteBuffer result) throws SQLException { + return FfmV2.duckdb_v2_result_get_statement_type(result); + } + + static void duckdb_v2_result_wait(ByteBuffer result) throws SQLException { + FfmV2.duckdb_v2_result_wait(result); + } + + static long duckdb_v2_result_drain(ByteBuffer result) throws SQLException { + return FfmV2.duckdb_v2_result_drain(result); + } + + // the step status is written to status_out[0], the chunk is null unless the status is RESULT_STEP_CHUNK + static ByteBuffer duckdb_v2_result_step(ByteBuffer result, int[] status_out) throws SQLException { + return FfmV2.duckdb_v2_result_step(result, status_out); + } + + // returns null at the end of the result + static ByteBuffer duckdb_v2_result_fetch_chunk(ByteBuffer result) throws SQLException { + return FfmV2.duckdb_v2_result_fetch_chunk(result); + } + + // factory and values + + // the returned factory is borrowed from the connection + static ByteBuffer duckdb_v2_connection_get_factory(ByteBuffer conn) throws SQLException { + return FfmV2.duckdb_v2_connection_get_factory(conn); + } + + static ByteBuffer duckdb_v2_factory_create_type_from_text(ByteBuffer factory, byte[] text) throws SQLException { + return FfmV2.duckdb_v2_factory_create_type_from_text(factory, text); + } + + static void duckdb_v2_value_destroy(ByteBuffer value) throws SQLException { + FfmV2.duckdb_v2_value_destroy(value); + } + + static ByteBuffer duckdb_v2_value_create_null(ByteBuffer factory, ByteBuffer type) throws SQLException { + return FfmV2.duckdb_v2_value_create_null(factory, type); + } + + static ByteBuffer duckdb_v2_value_create_bool(ByteBuffer factory, boolean value) throws SQLException { + return FfmV2.duckdb_v2_value_create_bool(factory, value); + } + + static ByteBuffer duckdb_v2_value_create_tinyint(ByteBuffer factory, byte value) throws SQLException { + return FfmV2.duckdb_v2_value_create_tinyint(factory, value); + } + + static ByteBuffer duckdb_v2_value_create_smallint(ByteBuffer factory, short value) throws SQLException { + return FfmV2.duckdb_v2_value_create_smallint(factory, value); + } + + static ByteBuffer duckdb_v2_value_create_int(ByteBuffer factory, int value) throws SQLException { + return FfmV2.duckdb_v2_value_create_int(factory, value); + } + + static ByteBuffer duckdb_v2_value_create_bigint(ByteBuffer factory, long value) throws SQLException { + return FfmV2.duckdb_v2_value_create_bigint(factory, value); + } + + static ByteBuffer duckdb_v2_value_create_float(ByteBuffer factory, float value) throws SQLException { + return FfmV2.duckdb_v2_value_create_float(factory, value); + } + + static ByteBuffer duckdb_v2_value_create_double(ByteBuffer factory, double value) throws SQLException { + return FfmV2.duckdb_v2_value_create_double(factory, value); + } + + static ByteBuffer duckdb_v2_value_create_date(ByteBuffer factory, int days) throws SQLException { + return FfmV2.duckdb_v2_value_create_date(factory, days); + } + + static ByteBuffer duckdb_v2_value_create_time(ByteBuffer factory, long micros) throws SQLException { + return FfmV2.duckdb_v2_value_create_time(factory, micros); + } + + static ByteBuffer duckdb_v2_value_create_timestamp(ByteBuffer factory, long micros) throws SQLException { + return FfmV2.duckdb_v2_value_create_timestamp(factory, micros); + } + + static ByteBuffer duckdb_v2_value_create_timestamp_ns(ByteBuffer factory, long nanos) throws SQLException { + return FfmV2.duckdb_v2_value_create_timestamp_ns(factory, nanos); + } + + static ByteBuffer duckdb_v2_value_create_timestamp_tz(ByteBuffer factory, long micros) throws SQLException { + return FfmV2.duckdb_v2_value_create_timestamp_tz(factory, micros); + } + + static ByteBuffer duckdb_v2_value_create_hugeint(ByteBuffer factory, long lower, long upper) throws SQLException { + return FfmV2.duckdb_v2_value_create_hugeint(factory, lower, upper); + } + + static ByteBuffer duckdb_v2_value_create_uuid(ByteBuffer factory, long lower, long upper) throws SQLException { + return FfmV2.duckdb_v2_value_create_uuid(factory, lower, upper); + } + + static ByteBuffer duckdb_v2_value_create_decimal(ByteBuffer factory, long lower, long upper, int width, int scale) + throws SQLException { + return FfmV2.duckdb_v2_value_create_decimal(factory, lower, upper, width, scale); + } + + static ByteBuffer duckdb_v2_value_create_varchar(ByteBuffer factory, byte[] value) throws SQLException { + return FfmV2.duckdb_v2_value_create_varchar(factory, value); + } + + static ByteBuffer duckdb_v2_value_create_blob(ByteBuffer factory, byte[] value) throws SQLException { + return FfmV2.duckdb_v2_value_create_blob(factory, value); + } + + // the child values are borrowed for the call + static ByteBuffer duckdb_v2_value_create_list(ByteBuffer factory, ByteBuffer childType, ByteBuffer[] children) + throws SQLException { + return FfmV2.duckdb_v2_value_create_list(factory, childType, children); + } + + static ByteBuffer duckdb_v2_value_create_struct(ByteBuffer factory, byte[][] names, ByteBuffer[] children) + throws SQLException { + return FfmV2.duckdb_v2_value_create_struct(factory, names, children); + } + + static ByteBuffer duckdb_v2_value_create_map(ByteBuffer factory, ByteBuffer keyType, ByteBuffer valueType, + ByteBuffer[] keys, ByteBuffer[] values) throws SQLException { + return FfmV2.duckdb_v2_value_create_map(factory, keyType, valueType, keys, values); + } + + static ByteBuffer duckdb_v2_value_create_type(ByteBuffer factory, ByteBuffer type) throws SQLException { + return FfmV2.duckdb_v2_value_create_type(factory, type); + } + + static byte[] duckdb_v2_value_to_string(ByteBuffer value) throws SQLException { + return FfmV2.duckdb_v2_value_to_string(value); + } + + // vectors + + // forces the vector (not its children) into the flat representation, in place + static void duckdb_v2_vector_flatten(ByteBuffer vector) throws SQLException { + FfmV2.duckdb_v2_vector_flatten(vector); + } + + // the returned value is owned by the caller + static ByteBuffer duckdb_v2_vector_get_value(ByteBuffer vector, long row) throws SQLException { + return FfmV2.duckdb_v2_vector_get_value(vector, row); + } + + // logical type parameters: the child types of nested types come back as TYPE values + + static long duckdb_v2_logical_type_get_param_count(ByteBuffer type) throws SQLException { + return FfmV2.duckdb_v2_logical_type_get_param_count(type); + } + + // the returned value is owned by the caller + static ByteBuffer duckdb_v2_logical_type_get_param_value(ByteBuffer type, long index) throws SQLException { + return FfmV2.duckdb_v2_logical_type_get_param_value(type, index); + } + + // returns null for a positional parameter + static byte[] duckdb_v2_logical_type_get_param_name(ByteBuffer type, long index) throws SQLException { + return FfmV2.duckdb_v2_logical_type_get_param_name(type, index); + } + + // unwraps the type of a TYPE value, the returned type is owned by the caller + static ByteBuffer duckdb_v2_value_get_type(ByteBuffer value) throws SQLException { + return FfmV2.duckdb_v2_value_get_type(value); + } + + // configuration + + // the returned config is borrowed from the connection + static ByteBuffer duckdb_v2_connection_get_config(ByteBuffer conn) throws SQLException { + return FfmV2.duckdb_v2_connection_get_config(conn); + } + + // the returned value is owned by the caller + static ByteBuffer duckdb_v2_config_get_option_value(ByteBuffer config, byte[] name) throws SQLException { + return FfmV2.duckdb_v2_config_get_option_value(config, name); + } + + // transitional: wraps the result into a chunked result of the bindings API that takes the ownership of the result + static ByteBuffer duckdb_v2_chunked_result_create(ByteBuffer result) throws SQLException { + return FfmVectors.createChunkedResult(result); + } + + // variants + + // the returned value is owned by the caller + static ByteBuffer duckdb_v2_value_variant_to_value(ByteBuffer value) throws SQLException { + return FfmV2.duckdb_v2_value_variant_to_value(value); + } + + // the returned type is owned by the caller + static ByteBuffer duckdb_v2_value_get_logical_type(ByteBuffer value) throws SQLException { + return FfmV2.duckdb_v2_value_get_logical_type(value); + } + + static void duckdb_v2_vector_set_value(ByteBuffer vector, long row, ByteBuffer value) throws SQLException { + FfmV2.duckdb_v2_vector_set_value(vector, row, value); + } + + static void duckdb_v2_vector_set_size(ByteBuffer vector, long size) throws SQLException { + FfmV2.duckdb_v2_vector_set_size(vector, size); + } + + // appending + + // the returned type is owned by the caller + static ByteBuffer duckdb_v2_logical_type_copy(ByteBuffer type) throws SQLException { + return FfmV2.duckdb_v2_logical_type_copy(type); + } + + static long duckdb_v2_vector_get_size(ByteBuffer vector) throws SQLException { + return FfmV2.duckdb_v2_vector_get_size(vector); + } + + static ByteBuffer duckdb_v2_column_data_collection_create(ByteBuffer factory, ByteBuffer[] types) + throws SQLException { + return FfmV2.duckdb_v2_column_data_collection_create(factory, types); + } + + static void duckdb_v2_column_data_collection_destroy(ByteBuffer collection) throws SQLException { + FfmV2.duckdb_v2_column_data_collection_destroy(collection); + } + + static void duckdb_v2_column_data_collection_clear(ByteBuffer collection) throws SQLException { + FfmV2.duckdb_v2_column_data_collection_clear(collection); + } + + static long duckdb_v2_column_data_collection_row_count(ByteBuffer collection) throws SQLException { + return FfmV2.duckdb_v2_column_data_collection_row_count(collection); + } + + static ByteBuffer duckdb_v2_column_data_collection_append_state_create(ByteBuffer collection) throws SQLException { + return FfmV2.duckdb_v2_column_data_collection_append_state_create(collection); + } + + static void duckdb_v2_column_data_collection_append_state_destroy(ByteBuffer state) throws SQLException { + FfmV2.duckdb_v2_column_data_collection_append_state_destroy(state); + } + + // the chunk is borrowed for the call + static void duckdb_v2_column_data_collection_append(ByteBuffer collection, ByteBuffer state, ByteBuffer chunk) + throws SQLException { + FfmV2.duckdb_v2_column_data_collection_append(collection, state, chunk); + } + + // binds the collection to the statement under the name, the collection must outlive the statement executions + static void duckdb_v2_statement_add_collection(ByteBuffer statement, byte[] name, ByteBuffer collection, + byte[][] column_names) throws SQLException { + FfmV2.duckdb_v2_statement_add_collection(statement, name, collection, column_names); + } + + // 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 ByteBuffer duckdb_v2_environment_create() throws SQLException { + return FfmV2.duckdb_v2_environment_create(); + } + + static void duckdb_v2_environment_destroy(ByteBuffer environment) throws SQLException { + FfmV2.duckdb_v2_environment_destroy(environment); + } + + static ByteBuffer duckdb_v2_instance_create_with_options(ByteBuffer environment, byte[][] names, byte[][] values) + throws SQLException { + return FfmV2.duckdb_v2_instance_create_with_options(environment, names, values); + } + + // opens the shared instance of the path, the initializer (can be null) is called when the instance is created + static ByteBuffer duckdb_v2_instance_open_shared(ByteBuffer environment, byte[] path, byte[][] names, + byte[][] values, InstanceInit init) throws SQLException { + return FfmV2.duckdb_v2_instance_open_shared(environment, path, names, values, init); + } + + // the name can be null + static void duckdb_v2_instance_attach(ByteBuffer instance, byte[] name, byte[] path, boolean makeDefault) + throws SQLException { + FfmV2.duckdb_v2_instance_attach(instance, name, path, makeDefault); + } + + static void duckdb_v2_instance_destroy(ByteBuffer instance) throws SQLException { + FfmV2.duckdb_v2_instance_destroy(instance); + } + + // the returned config is borrowed from the instance + static ByteBuffer duckdb_v2_instance_get_config(ByteBuffer instance) throws SQLException { + return FfmV2.duckdb_v2_instance_get_config(instance); + } + + static ByteBuffer duckdb_v2_connection_create(ByteBuffer instance) throws SQLException { + return FfmV2.duckdb_v2_connection_create(instance); + } + + static void duckdb_v2_connection_destroy(ByteBuffer conn) throws SQLException { + FfmV2.duckdb_v2_connection_destroy(conn); + } + + // configuration + + static final int SCOPE_DEFAULT = 0; + static final int SCOPE_GLOBAL = 1; + static final int SCOPE_SESSION = 2; + + static void duckdb_v2_config_set_option_text(ByteBuffer config, byte[] name, byte[] value, int scope) + throws SQLException { + FfmV2.duckdb_v2_config_set_option_text(config, name, value, scope); + } + + // the value is borrowed for the call + static void duckdb_v2_config_set_option_value(ByteBuffer config, byte[] name, ByteBuffer value, int scope) + throws SQLException { + FfmV2.duckdb_v2_config_set_option_value(config, name, value, scope); + } + + static long duckdb_v2_config_get_option_count(ByteBuffer config) throws SQLException { + return FfmV2.duckdb_v2_config_get_option_count(config); + } + + // the returned option is owned by the caller + static ByteBuffer duckdb_v2_config_get_option_by_index(ByteBuffer config, long index) throws SQLException { + return FfmV2.duckdb_v2_config_get_option_by_index(config, index); + } + + static byte[] duckdb_v2_option_get_name(ByteBuffer option) throws SQLException { + return FfmV2.duckdb_v2_option_get_name(option); + } + + static boolean duckdb_v2_option_supports_scope(ByteBuffer option, int scope) throws SQLException { + return FfmV2.duckdb_v2_option_supports_scope(option, scope); + } + + static void duckdb_v2_option_destroy(ByteBuffer option) throws SQLException { + FfmV2.duckdb_v2_option_destroy(option); + } + + // the scope that the value comes from is written to scope_out[0], scope_out can be null + static ByteBuffer duckdb_v2_config_get_option_value_scoped(ByteBuffer config, byte[] name, int[] scope_out) + throws SQLException { + return FfmV2.duckdb_v2_config_get_option_value_scoped(config, name, scope_out); + } + + // custom options + + static ByteBuffer duckdb_v2_custom_option_create(ByteBuffer factory) throws SQLException { + return FfmV2.duckdb_v2_custom_option_create(factory); + } + + static void duckdb_v2_custom_option_destroy(ByteBuffer option) throws SQLException { + FfmV2.duckdb_v2_custom_option_destroy(option); + } + + static void duckdb_v2_custom_option_set_name(ByteBuffer option, byte[] name) throws SQLException { + FfmV2.duckdb_v2_custom_option_set_name(option, name); + } + + // the type is borrowed for the call + static void duckdb_v2_custom_option_set_type(ByteBuffer option, ByteBuffer type) throws SQLException { + FfmV2.duckdb_v2_custom_option_set_type(option, type); + } + + // the value is borrowed for the call + static void duckdb_v2_custom_option_set_default_value(ByteBuffer option, ByteBuffer value) throws SQLException { + FfmV2.duckdb_v2_custom_option_set_default_value(option, value); + } + + static void duckdb_v2_custom_option_set_description(ByteBuffer option, byte[] description) throws SQLException { + FfmV2.duckdb_v2_custom_option_set_description(option, description); + } + + static void duckdb_v2_custom_option_set_default_scope(ByteBuffer option, int scope) throws SQLException { + FfmV2.duckdb_v2_custom_option_set_default_scope(option, scope); + } + + static void duckdb_v2_custom_option_set_supports_scope(ByteBuffer option, int scope, boolean supported) + throws SQLException { + FfmV2.duckdb_v2_custom_option_set_supports_scope(option, scope, supported); + } + + static void duckdb_v2_connection_register_custom_option(ByteBuffer conn, ByteBuffer option) throws SQLException { + FfmV2.duckdb_v2_connection_register_custom_option(conn, option); + } + + // 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 long duckdb_v2_arrow_export_stream(ByteBuffer conn, ByteBuffer helper, ByteBuffer statement, + ByteBuffer collection, long batch_size) throws SQLException { + return FfmArrow.duckdb_v2_arrow_export_stream(conn, helper, statement, collection, batch_size); + } + + // registers the table function that scans the registered Arrow streams + static void duckdb_v2_arrow_register_scan_function(ByteBuffer conn) throws SQLException { + FfmArrow.duckdb_v2_arrow_register_scan_function(conn); + } + + // moves the stream (the address of an ArrowArrayStream) out of its struct and registers it, returns its id + static long duckdb_v2_arrow_register_stream(ByteBuffer conn, long stream_address) throws SQLException { + return FfmArrow.duckdb_v2_arrow_register_stream(conn, stream_address); + } + + // releases the registered stream, if it is not consumed or released yet + static void duckdb_v2_arrow_release_stream(long id) { + try { + FfmArrow.duckdb_v2_arrow_release_stream(id); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + // closes the exported and the registered streams of the connection that are not released by their consumers yet + static void duckdb_v2_arrow_close_streams(ByteBuffer conn) { + try { + FfmArrow.duckdb_v2_arrow_close_streams(conn); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + // profiling + + // the profiling information of the last query of the connection, the format is "" for the default one + static byte[] duckdb_v2_connection_get_profiling_information(ByteBuffer conn, byte[] format) throws SQLException { + return FfmV2.duckdb_v2_connection_get_profiling_information(conn, format); + } + + // 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 byte[] duckdb_v2_vector_get_long_strings(ByteBuffer data, int[] rows, int count, int[] offsets_out) + throws SQLException { + return FfmV2.duckdb_v2_vector_get_long_strings(data, rows, count, offsets_out); + } + + // casts the rows of the source vector to the type of the target vector, the target is replaced by the result + static void duckdb_v2_vector_cast(ByteBuffer factory, ByteBuffer source, ByteBuffer target) throws SQLException { + FfmV2.duckdb_v2_vector_cast(factory, source, target); + } + + // bulk reads + + // the names of all the fields of the schema + static byte[][] duckdb_v2_schema_get_field_names(ByteBuffer schema) throws SQLException { + return FfmV2.duckdb_v2_schema_get_field_names(schema); + } + + // the type IDs (of the C API v1) of all the fields of the schema + static int[] duckdb_v2_schema_get_field_type_ids(ByteBuffer schema) throws SQLException { + return FfmV2.duckdb_v2_schema_get_field_type_ids(schema); + } + + // reads a BOOLEAN option: 1 or 0, or -1 if the option is not set or is not a BOOLEAN + static int duckdb_v2_config_get_bool_option(ByteBuffer config, byte[] name) throws SQLException { + return FfmV2.duckdb_v2_config_get_bool_option(config, name); + } + + // 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 + DUCKDB_TYPE_BOOLEAN(1, 1), + // int8_t + DUCKDB_TYPE_TINYINT(2, 1), + // int16_t + DUCKDB_TYPE_SMALLINT(3, 2), + // int32_t + DUCKDB_TYPE_INTEGER(4, 4), + // int64_t + DUCKDB_TYPE_BIGINT(5, 8), + // uint8_t + DUCKDB_TYPE_UTINYINT(6, 1), + // uint16_t + DUCKDB_TYPE_USMALLINT(7, 2), + // uint32_t + DUCKDB_TYPE_UINTEGER(8, 4), + // uint64_t + DUCKDB_TYPE_UBIGINT(9, 8), + // float + DUCKDB_TYPE_FLOAT(10, 4), + // double + DUCKDB_TYPE_DOUBLE(11, 8), + // duckdb_timestamp (microseconds) + DUCKDB_TYPE_TIMESTAMP(12, 8), + // duckdb_date + DUCKDB_TYPE_DATE(13, 4), + // duckdb_time + DUCKDB_TYPE_TIME(14, 8), + // duckdb_interval + DUCKDB_TYPE_INTERVAL(15), + // duckdb_hugeint + DUCKDB_TYPE_HUGEINT(16, 16), + // duckdb_uhugeint + DUCKDB_TYPE_UHUGEINT(32, 16), + // const char* + DUCKDB_TYPE_VARCHAR(17, 16), + // duckdb_blob + DUCKDB_TYPE_BLOB(18, 16), + // duckdb_decimal + DUCKDB_TYPE_DECIMAL(19, 0), + // duckdb_timestamp_s (seconds) + DUCKDB_TYPE_TIMESTAMP_S(20, 8), + // duckdb_timestamp_ms (milliseconds) + DUCKDB_TYPE_TIMESTAMP_MS(21, 8), + // duckdb_timestamp_ns (nanoseconds) + DUCKDB_TYPE_TIMESTAMP_NS(22, 8), + // enum type, only useful as logical type + DUCKDB_TYPE_ENUM(23, 0), + // list type, only useful as logical type + DUCKDB_TYPE_LIST(24, 16), + // struct type, only useful as logical type + DUCKDB_TYPE_STRUCT(25, 0), + // map type, only useful as logical type + DUCKDB_TYPE_MAP(26, 16), + // duckdb_array, only useful as logical type + DUCKDB_TYPE_ARRAY(33, 0), + // duckdb_hugeint + DUCKDB_TYPE_UUID(27, 16), + // union type, only useful as logical type + DUCKDB_TYPE_UNION(28), + // duckdb_bit + DUCKDB_TYPE_BIT(29), + // duckdb_time_tz + DUCKDB_TYPE_TIME_TZ(30, 8), + // duckdb_timestamp (microseconds) + DUCKDB_TYPE_TIMESTAMP_TZ(31, 8), + // enum type, only useful as logical type + DUCKDB_TYPE_ANY(34), + // duckdb_varint + DUCKDB_TYPE_VARINT(35), + // enum type, only useful as logical type + DUCKDB_TYPE_SQLNULL(36), + // enum type, only useful as logical type + DUCKDB_TYPE_STRING_LITERAL(37), + // enum type, only useful as logical type + DUCKDB_TYPE_INTEGER_LITERAL(38), + // duckdb_time_ns (nanoseconds) + // DUCKDB_TYPE_TIME_NS = 39, + // WKB blob + DUCKDB_TYPE_GEOMETRY(40, 16); + + final int typeId; + final long widthBytes; + final CAPIType[] typeArray; + + private static final CAPIType[] BY_TYPE_ID; + + static { + int max = 0; + CAPIType[] values = CAPIType.values(); + for (CAPIType ct : values) { + if (ct.typeId > max) { + max = ct.typeId; + } + } + BY_TYPE_ID = new CAPIType[max + 1]; + for (CAPIType ct : values) { + BY_TYPE_ID[ct.typeId] = ct; + } + } + + CAPIType(int typeId) { + this(typeId, 0); + } + + CAPIType(int typeId, long widthBytes) { + this.typeId = typeId; + this.widthBytes = widthBytes; + this.typeArray = new CAPIType[] {this}; + } + + static CAPIType capiTypeFromTypeId(int typeId) throws SQLException { + if (typeId >= 0 && typeId < BY_TYPE_ID.length && BY_TYPE_ID[typeId] != null) { + return BY_TYPE_ID[typeId]; + } + throw createSQLException("Invalid unknown ID not found: " + typeId, ErrorCode.BINDINGS_UNKNOWN_ID); + } + } +} diff --git a/src/main/java22/org/duckdb/DuckDBLibrary.java b/src/main/java22/org/duckdb/DuckDBLibrary.java new file mode 100644 index 000000000..8c9a06ea7 --- /dev/null +++ b/src/main/java22/org/duckdb/DuckDBLibrary.java @@ -0,0 +1,150 @@ +package org.duckdb; + +import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.lang.foreign.Arena; +import java.lang.foreign.SymbolLookup; +import java.net.URI; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.CodeSource; +import java.security.ProtectionDomain; + +/** + * Loads the native library of the driver, the Java 22 and newer implementation of this class (and of DuckDBBindings). + * The C API of the library is called directly with the Foreign Function and Memory API, without JNI, so the library + * is opened with the dynamic linker and is not loaded as a JNI library. + */ +final class DuckDBLibrary { + private DuckDBLibrary() { + } + + private static final String ARCH_X86_64 = "amd64"; + private static final String ARCH_AARCH64 = "arm64"; + + private static final String OS_WINDOWS = "windows"; + private static final String OS_MACOS = "macos"; + private static final String OS_LINUX = "linux"; + + /** Loads the native library, it is loaded once. */ + static synchronized void load() { + if (loaded) { + return; + } + try { + loadNativeLibrary(); + } catch (Exception e) { + throw new RuntimeException(e); + } + loaded = true; + } + + private static boolean loaded = false; + + private static void open(Path path) { + Ffm.setLookup(SymbolLookup.libraryLookup(path.toAbsolutePath(), Arena.global())); + } + + private static void loadNativeLibrary() throws Exception { + String libName = nativeLibName(); + URL libRes = DuckDBLibrary.class.getResource("/" + libName); + + // The current JAR has a native library bundled, in this case we unpack and load it. + // There is no fallback if the unpacking or loading fails. We expect that only + // the '-nolib' JAR can be used with an external native lib + if (null != libRes) { + unpackAndLoad(libRes); + return; + } + + // There is no native library inside the JAR file, so we try to load it by name + try { + System.loadLibrary("duckdb_java"); + Ffm.setLookup(SymbolLookup.loaderLookup()); + } catch (UnsatisfiedLinkError e) { + // Native library cannot be loaded by name using ordinary JVM mechanisms, we try to load it directly + // from FS - from the same directory where the current JAR resides + try { + loadFromCurrentJarDir(libName); + } catch (Throwable t) { + e.printStackTrace(); + throw new IllegalStateException(t); + } + } + } + + private static String cpuArch() { + String prop = System.getProperty("os.arch").toLowerCase().trim(); + switch (prop) { + case "x86_64": + case "amd64": + return ARCH_X86_64; + case "aarch64": + case "arm64": + return ARCH_AARCH64; + default: + return prop.replaceAll("[^a-z0-9_\\-.]", ""); + } + } + + static String osName() { + String prop = System.getProperty("os.name").toLowerCase().trim(); + if (prop.startsWith("windows")) { + return OS_WINDOWS; + } else if (prop.startsWith("mac")) { + return OS_MACOS; + } else if (prop.startsWith("linux")) { + return OS_LINUX; + } else { + return prop.replaceAll("[^a-z0-9_\\-.]", ""); + } + } + + static String nativeLibName() { + return "libduckdb_java.so_" + osName() + "_" + cpuArch(); + } + + static Path currentJarDir() throws Exception { + ProtectionDomain pd = DuckDBLibrary.class.getProtectionDomain(); + CodeSource cs = pd.getCodeSource(); + URL loc = cs.getLocation(); + URI uri = loc.toURI(); + Path jarPath = Paths.get(uri); + Path dirPath = jarPath.getParent(); + return dirPath.toRealPath(); + } + + private static void unpackAndLoad(URL nativeLibRes) throws IOException { + Path tmpFile = Files.createTempFile("libduckdb_java", ".so"); + try (InputStream is = nativeLibRes.openStream()) { + Files.copy(is, tmpFile, REPLACE_EXISTING); + } + tmpFile.toFile().deleteOnExit(); + // Harmless on the officially supported platforms but required on some other. + tmpFile.toFile().setExecutable(true); + open(tmpFile); + } + + private static void loadFromCurrentJarDir(String libName) throws Exception { + Path dir = currentJarDir(); + Path libPath = dir.resolve(libName); + if (Files.exists(libPath)) { + open(libPath); + } else { + throw new FileNotFoundException("DuckDB JNI library not found, path: '" + libPath.toAbsolutePath() + "'"); + } + } + + // We use zero-length ByteBuffer-s as a hacky but cheap way to pass C++ pointers + // back and forth + + /* + * NB: if you change anything below, run `javah` on this class to re-generate + * the C header. CMake does this as well + */ +} diff --git a/src/main/java22/org/duckdb/Ffm.java b/src/main/java22/org/duckdb/Ffm.java new file mode 100644 index 000000000..85d2eb16b --- /dev/null +++ b/src/main/java22/org/duckdb/Ffm.java @@ -0,0 +1,240 @@ +package org.duckdb; + +import static java.lang.foreign.ValueLayout.ADDRESS; +import static java.lang.foreign.ValueLayout.JAVA_BYTE; +import static java.lang.foreign.ValueLayout.JAVA_INT; +import static java.lang.foreign.ValueLayout.JAVA_LONG; + +import java.lang.foreign.Arena; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.Linker; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.SymbolLookup; +import java.lang.invoke.MethodHandle; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.sql.SQLTimeoutException; + +/** + * The support of the bindings that call the C API of the native library directly with the Foreign Function and Memory + * API, without JNI. The handles of the C API are passed around as direct byte buffers that hold the pointer + * (the same as the JNI bindings do), the buffers have no content. + */ +final class Ffm { + private Ffm() { + } + + static final Linker LINKER = Linker.nativeLinker(); + static final MemorySegment NULL = MemorySegment.NULL; + static final int ERROR_NONE = 0; + // DUCKDB_V2_ERROR_RUNTIME_INTERRUPT + private static final int ERROR_INTERRUPT = 8003; + + private static volatile SymbolLookup lookup; + + /** Sets the library whose symbols are called, see {@link DuckDBLibrary}. */ + static void setLookup(SymbolLookup lookup) { + Ffm.lookup = lookup; + } + + /** The downcall of the function of the library. */ + static MethodHandle downcall(String name, FunctionDescriptor descriptor) { + SymbolLookup l = lookup; + if (l == null) { + throw new IllegalStateException("The native library is not loaded"); + } + MemorySegment symbol = + l.find(name).orElseThrow(() -> new UnsatisfiedLinkError("The native library has no function " + name)); + return LINKER.downcallHandle(symbol, descriptor); + } + + // --------------------------------------------------------------------------------------------------------- + // Handles + // --------------------------------------------------------------------------------------------------------- + + /** The pointer of a handle buffer, NULL for null. */ + static MemorySegment ptr(ByteBuffer handle) { + if (handle == null) { + return NULL; + } + return MemorySegment.ofBuffer(handle); + } + + /** The pointer of a handle buffer that must not be null. */ + static MemorySegment ptrNonNull(ByteBuffer handle, String what) throws SQLException { + if (handle == null) { + throw new SQLException("Invalid " + what + " buffer"); + } + MemorySegment res = MemorySegment.ofBuffer(handle); + if (res.address() == 0) { + throw new SQLException("Invalid " + what); + } + return res; + } + + /** The handle buffer of the pointer, null for NULL. */ + static ByteBuffer handle(MemorySegment pointer) { + if (pointer.address() == 0) { + return null; + } + return MemorySegment.ofAddress(pointer.address()).reinterpret(0).asByteBuffer(); + } + + /** The handle buffer of the address, null for 0. */ + static ByteBuffer handle(long address) { + if (address == 0) { + return null; + } + return MemorySegment.ofAddress(address).reinterpret(0).asByteBuffer(); + } + + /** The buffer of the native memory of the specified size, in the native byte order. */ + static ByteBuffer data(MemorySegment pointer, long size) { + if (pointer.address() == 0) { + return null; + } + return MemorySegment.ofAddress(pointer.address()) + .reinterpret(size) + .asByteBuffer() + .order(ByteOrder.nativeOrder()); + } + + // --------------------------------------------------------------------------------------------------------- + // Memory + // --------------------------------------------------------------------------------------------------------- + + /** The out parameter that holds a pointer, it is set to NULL. */ + static MemorySegment outPtr(Arena arena) { + return arena.allocate(ADDRESS); + } + + static MemorySegment outLong(Arena arena) { + return arena.allocate(JAVA_LONG); + } + + static MemorySegment outInt(Arena arena) { + return arena.allocate(JAVA_INT); + } + + /** Copies the bytes to the native memory, a zero length array is passed as NULL. */ + static MemorySegment bytes(Arena arena, byte[] value) { + if (value == null || value.length == 0) { + return NULL; + } + MemorySegment res = arena.allocate(value.length); + MemorySegment.copy(value, 0, res, JAVA_BYTE, 0, value.length); + return res; + } + + static long len(byte[] value) { + return value == null ? 0 : value.length; + } + + /** The bytes of the native memory. */ + static byte[] toBytes(MemorySegment pointer, long length) { + if (length == 0 || pointer.address() == 0) { + return new byte[0]; + } + return MemorySegment.ofAddress(pointer.address()).reinterpret(length).toArray(JAVA_BYTE); + } + + static String toString(MemorySegment pointer, long length) { + return new String(toBytes(pointer, length), StandardCharsets.UTF_8); + } + + // --------------------------------------------------------------------------------------------------------- + // Errors + // --------------------------------------------------------------------------------------------------------- + + /** + * Throws the exception if the C API call has failed. The error info is read from the slot and is destroyed. The + * call is expected to be made with the pointer of the slot, that is an out parameter. + */ + static void check(int state, MemorySegment errSlot) throws SQLException { + if (state == ERROR_NONE) { + return; + } + throw error(state, errSlot); + } + + static SQLException error(int state, MemorySegment errSlot) { + MemorySegment info = errSlot.get(ADDRESS, 0); + if (info.address() == 0) { + return new SQLException("Unknown error, code: " + state); + } + try (Arena arena = Arena.ofConfined()) { + MemorySegment code = outInt(arena); + int errorCode = state; + if (Capi.duckdb_v2_error_info_get_code(info, code) == ERROR_NONE) { + errorCode = code.get(JAVA_INT, 0); + } + MemorySegment text = outPtr(arena); + MemorySegment textLen = outLong(arena); + String message = "Unknown error, code: " + errorCode; + if (Capi.duckdb_v2_error_info_get_text(info, text, textLen) == ERROR_NONE) { + message = toString(text.get(ADDRESS, 0), textLen.get(JAVA_LONG, 0)); + } + return errorCode == ERROR_INTERRUPT ? new SQLTimeoutException(message) : new SQLException(message); + } finally { + try (Arena arena = Arena.ofConfined()) { + MemorySegment holder = arena.allocate(ADDRESS); + holder.set(ADDRESS, 0, info); + Capi.duckdb_v2_error_info_destroy(holder); + } + } + } + + /** The code and the message without the type of an error of the C API, the error info is destroyed. */ + static final class RawError { + final int code; + final String message; + + RawError(int code, String message) { + this.code = code; + this.message = message; + } + } + + static RawError rawError(int state, MemorySegment errSlot) { + MemorySegment info = errSlot.get(ADDRESS, 0); + if (info.address() == 0) { + return new RawError(state, "Unknown error, code: " + state); + } + try (Arena arena = Arena.ofConfined()) { + MemorySegment code = outInt(arena); + int errorCode = state; + if (Capi.duckdb_v2_error_info_get_code(info, code) == ERROR_NONE) { + errorCode = code.get(JAVA_INT, 0); + } + MemorySegment text = outPtr(arena); + MemorySegment textLen = outLong(arena); + String message = "Unknown error, code: " + errorCode; + if (Capi.duckdb_v2_error_info_get_raw_text(info, text, textLen) == ERROR_NONE) { + message = toString(text.get(ADDRESS, 0), textLen.get(JAVA_LONG, 0)); + } + return new RawError(errorCode, message); + } finally { + try (Arena arena = Arena.ofConfined()) { + MemorySegment holder = arena.allocate(ADDRESS); + holder.set(ADDRESS, 0, info); + Capi.duckdb_v2_error_info_destroy(holder); + } + } + } + + /** The buffer itself, it must be not null. */ + static ByteBuffer ptrNonNullBuffer(ByteBuffer buffer, String what) throws SQLException { + if (buffer == null) { + throw new SQLException("Invalid " + what + " buffer"); + } + return buffer; + } + + /** Throws the exception as it is, whether it is checked or not. */ + @SuppressWarnings("unchecked") + static RuntimeException sneaky(Throwable t) throws T { + throw(T) t; + } +} diff --git a/src/main/java22/org/duckdb/FfmArrow.java b/src/main/java22/org/duckdb/FfmArrow.java new file mode 100644 index 000000000..959a3dd31 --- /dev/null +++ b/src/main/java22/org/duckdb/FfmArrow.java @@ -0,0 +1,761 @@ +package org.duckdb; + +import static java.lang.foreign.ValueLayout.ADDRESS; +import static java.lang.foreign.ValueLayout.JAVA_INT; +import static java.lang.foreign.ValueLayout.JAVA_LONG; + +import java.lang.foreign.Arena; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.MemorySegment; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicLong; + +/** + * The Arrow streams. An Arrow stream is a C structure with callbacks (the Arrow C stream interface), the streams that + * are exported to the consumers and the callbacks of the table function that scans a registered stream are the upcalls + * of the functions of this class. + */ +final class FfmArrow { + private FfmArrow() { + } + + private static final int EIO = 5; + private static final int EINVAL = 22; + private static final int ERROR_INPUT_INVALID = 2001; + private static final int KIND_POSITIONAL_ONLY = 0; + private static final int TYPE_ID_BIGINT = 14; + private static final long ARROW_SCAN_BATCH_SIZE = 2048; + + // struct ArrowArrayStream { get_schema, get_next, get_last_error, release, private_data } + private static final long STREAM_SIZE = 40; + private static final long STREAM_GET_SCHEMA = 0; + private static final long STREAM_GET_NEXT = 8; + private static final long STREAM_GET_LAST_ERROR = 16; + private static final long STREAM_RELEASE = 24; + private static final long STREAM_PRIVATE_DATA = 32; + // struct ArrowSchema, the release callback is at the offset 56, struct ArrowArray, it is at the offset 64 + private static final long SCHEMA_SIZE = 72; + private static final long SCHEMA_RELEASE = 56; + private static final long ARRAY_SIZE = 80; + private static final long ARRAY_RELEASE = 64; + + // The calls of the function pointers of the streams + private static final MethodHandle CALL_GET_SCHEMA = + Ffm.LINKER.downcallHandle(FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS)); + private static final MethodHandle CALL_GET_NEXT = + Ffm.LINKER.downcallHandle(FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS)); + private static final MethodHandle CALL_GET_LAST_ERROR = + Ffm.LINKER.downcallHandle(FunctionDescriptor.of(ADDRESS, ADDRESS)); + private static final MethodHandle CALL_RELEASE = Ffm.LINKER.downcallHandle(FunctionDescriptor.ofVoid(ADDRESS)); + + private static MemorySegment fn(MemorySegment struct, long offset) { + return struct.get(ADDRESS, offset); + } + + private static int callGetSchema(MemorySegment stream, MemorySegment out) { + try { + return (int) CALL_GET_SCHEMA.invokeExact(fn(stream, STREAM_GET_SCHEMA), stream, out); + } catch (Throwable t) { + throw Ffm.sneaky(t); + } + } + + private static int callGetNext(MemorySegment stream, MemorySegment out) { + try { + return (int) CALL_GET_NEXT.invokeExact(fn(stream, STREAM_GET_NEXT), stream, out); + } catch (Throwable t) { + throw Ffm.sneaky(t); + } + } + + private static String callGetLastError(MemorySegment stream) { + try { + MemorySegment error = + (MemorySegment) CALL_GET_LAST_ERROR.invokeExact(fn(stream, STREAM_GET_LAST_ERROR), stream); + if (error.address() == 0) { + return null; + } + return MemorySegment.ofAddress(error.address()).reinterpret(Long.MAX_VALUE).getString(0); + } catch (Throwable t) { + throw Ffm.sneaky(t); + } + } + + private static void callRelease(MemorySegment struct, long releaseOffset) { + MemorySegment release = fn(struct, releaseOffset); + if (release.address() == 0) { + return; + } + try { + CALL_RELEASE.invokeExact(release, struct); + } catch (Throwable t) { + throw Ffm.sneaky(t); + } + } + + private static boolean released(MemorySegment struct, long releaseOffset) { + return fn(struct, releaseOffset).address() == 0; + } + + private static MemorySegment stub(String name, FunctionDescriptor descriptor, MethodType type) { + try { + MethodHandle target = MethodHandles.lookup().findStatic(FfmArrow.class, name, type); + return Ffm.LINKER.upcallStub(target, descriptor, Arena.global()); + } catch (ReflectiveOperationException e) { + throw new ExceptionInInitializerError(e); + } + } + + // --------------------------------------------------------------------------------------------------------- + // The exported streams + // --------------------------------------------------------------------------------------------------------- + + private static final class Exported { + final Arena arena = Arena.ofShared(); + // the stream that is handed out + final MemorySegment stream = arena.allocate(STREAM_SIZE, 8); + // the stream of the Arrow result + final MemorySegment inner = arena.allocate(STREAM_SIZE, 8); + ByteBuffer statement; + ByteBuffer collection; + ByteBuffer connection; + ByteBuffer helper; + MemorySegment connectionKey; + MemorySegment lastError = Ffm.NULL; + boolean closed; + long id; + + synchronized void close() { + closed = true; + if (!released(inner, STREAM_RELEASE)) { + callRelease(inner, STREAM_RELEASE); + inner.set(ADDRESS, STREAM_RELEASE, Ffm.NULL); + } + try { + if (statement != null) { + FfmV2.duckdb_v2_sql_statement_destroy(statement); + statement = null; + } + if (collection != null) { + FfmV2.duckdb_v2_column_data_collection_destroy(collection); + collection = null; + } + if (helper != null) { + FfmV2.duckdb_v2_connection_destroy(helper); + helper = null; + } + } catch (SQLException e) { + // nothing else can be done + } + } + + synchronized void setLastError(String message) { + byte[] bytes = (message + "\0").getBytes(StandardCharsets.UTF_8); + lastError = arena.allocate(bytes.length); + MemorySegment.copy(bytes, 0, lastError, java.lang.foreign.ValueLayout.JAVA_BYTE, 0, bytes.length); + } + } + + private static final ConcurrentHashMap EXPORTED = new ConcurrentHashMap<>(); + private static final AtomicLong NEXT_ID = new AtomicLong(1); + private static final Object REGISTRY_LOCK = new Object(); + // the exported streams by the address of the connection that they are closed with + private static final ConcurrentHashMap> BY_CONNECTION = new ConcurrentHashMap<>(); + + private static final MemorySegment EXPORT_GET_SCHEMA = + stub("exportGetSchema", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS), + MethodType.methodType(int.class, MemorySegment.class, MemorySegment.class)); + private static final MemorySegment EXPORT_GET_NEXT = + stub("exportGetNext", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS), + MethodType.methodType(int.class, MemorySegment.class, MemorySegment.class)); + private static final MemorySegment EXPORT_GET_LAST_ERROR = + stub("exportGetLastError", FunctionDescriptor.of(ADDRESS, ADDRESS), + MethodType.methodType(MemorySegment.class, MemorySegment.class)); + private static final MemorySegment EXPORT_RELEASE = stub("exportRelease", FunctionDescriptor.ofVoid(ADDRESS), + MethodType.methodType(void.class, MemorySegment.class)); + + private static Exported exported(MemorySegment stream) { + MemorySegment s = stream.reinterpret(STREAM_SIZE); + return EXPORTED.get(s.get(JAVA_LONG, STREAM_PRIVATE_DATA)); + } + + private static int forward(Exported self, boolean schema, MemorySegment out) { + synchronized (self) { + if (self.closed || released(self.inner, STREAM_RELEASE)) { + self.setLastError("Connection Error: Connection was closed"); + return EIO; + } + int res = schema ? callGetSchema(self.inner, out) : callGetNext(self.inner, out); + if (res != 0) { + String error = callGetLastError(self.inner); + self.setLastError(error != null ? error : "unable to read the result"); + } + return res; + } + } + + @SuppressWarnings("unused") + private static int exportGetSchema(MemorySegment stream, MemorySegment out) { + try { + MemorySegment s = stream.reinterpret(STREAM_SIZE); + if (released(s, STREAM_RELEASE)) { + return EINVAL; + } + Exported self = exported(stream); + out.reinterpret(SCHEMA_SIZE).set(ADDRESS, SCHEMA_RELEASE, Ffm.NULL); + return forward(self, true, out); + } catch (Throwable t) { + return EIO; + } + } + + @SuppressWarnings("unused") + private static int exportGetNext(MemorySegment stream, MemorySegment out) { + try { + MemorySegment s = stream.reinterpret(STREAM_SIZE); + if (released(s, STREAM_RELEASE)) { + return EINVAL; + } + Exported self = exported(stream); + out.reinterpret(ARRAY_SIZE).set(ADDRESS, ARRAY_RELEASE, Ffm.NULL); + return forward(self, false, out); + } catch (Throwable t) { + return EIO; + } + } + + @SuppressWarnings("unused") + private static MemorySegment exportGetLastError(MemorySegment stream) { + try { + MemorySegment s = stream.reinterpret(STREAM_SIZE); + if (released(s, STREAM_RELEASE)) { + return Ffm.NULL; + } + Exported self = exported(stream); + synchronized (self) { + return self.lastError; + } + } catch (Throwable t) { + return Ffm.NULL; + } + } + + @SuppressWarnings("unused") + private static void exportRelease(MemorySegment stream) { + try { + MemorySegment s = stream.reinterpret(STREAM_SIZE); + if (released(s, STREAM_RELEASE)) { + return; + } + Exported self = exported(stream); + s.set(ADDRESS, STREAM_RELEASE, Ffm.NULL); + EXPORTED.remove(self.id); + synchronized (REGISTRY_LOCK) { + List streams = BY_CONNECTION.get(self.connectionKey.address()); + if (streams != null) { + streams.remove(self); + if (streams.isEmpty()) { + BY_CONNECTION.remove(self.connectionKey.address()); + } + } + } + self.close(); + // the memory of the stream is released with its arena + self.arena.close(); + } catch (Throwable t) { + // the callback must not throw + } + } + + /** + * 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. + */ + static long duckdb_v2_arrow_export_stream(ByteBuffer conn, ByteBuffer helper, ByteBuffer statement, + ByteBuffer collection, long batchSize) throws SQLException { + MemorySegment connPtr = Ffm.ptrNonNull(conn, "connection"); + Exported exported = new Exported(); + try (Arena a = Arena.ofConfined()) { + MemorySegment result = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_statement_execute_arrow(Ffm.ptrNonNull(helper, "connection"), + Ffm.ptrNonNull(statement, "statement"), Ffm.NULL, Ffm.NULL, + Ffm.NULL, 0, batchSize, result, err), + err); + int state = Capi.duckdb_v2_arrow_result_to_arrow_c_stream(result, exported.inner, err); + if (state != Ffm.ERROR_NONE) { + MemorySegment handle = result.get(ADDRESS, 0); + if (handle.address() != 0) { + Capi.duckdb_v2_arrow_result_destroy(result); + } + exported.arena.close(); + throw Ffm.error(state, err); + } + } catch (SQLException | RuntimeException e) { + exported.arena.close(); + throw e; + } + exported.statement = statement; + exported.collection = collection; + exported.helper = helper; + exported.connection = conn; + exported.connectionKey = connPtr; + exported.id = NEXT_ID.getAndIncrement(); + exported.stream.set(ADDRESS, STREAM_GET_SCHEMA, EXPORT_GET_SCHEMA); + exported.stream.set(ADDRESS, STREAM_GET_NEXT, EXPORT_GET_NEXT); + exported.stream.set(ADDRESS, STREAM_GET_LAST_ERROR, EXPORT_GET_LAST_ERROR); + exported.stream.set(ADDRESS, STREAM_RELEASE, EXPORT_RELEASE); + exported.stream.set(JAVA_LONG, STREAM_PRIVATE_DATA, exported.id); + EXPORTED.put(exported.id, exported); + synchronized (REGISTRY_LOCK) { + BY_CONNECTION.computeIfAbsent(connPtr.address(), k -> new ArrayList<>()).add(exported); + } + return exported.stream.address(); + } + + // --------------------------------------------------------------------------------------------------------- + // The registered streams + // --------------------------------------------------------------------------------------------------------- + + /** A stream of Java that is registered with a connection, it is scanned by the table function. */ + private static final class Registered { + final Arena arena = Arena.ofShared(); + final MemorySegment stream = arena.allocate(STREAM_SIZE, 8); + long id; + long connection; + boolean closed; + + synchronized void release() { + if (!closed) { + closed = true; + if (!released(stream, STREAM_RELEASE)) { + callRelease(stream, STREAM_RELEASE); + stream.set(ADDRESS, STREAM_RELEASE, Ffm.NULL); + } + arena.close(); + } + } + + // Moves the stream into the destination struct, returns false if it is released already + synchronized boolean take(MemorySegment destination) { + if (closed || released(stream, STREAM_RELEASE)) { + return false; + } + MemorySegment.copy(stream, 0, destination, 0, STREAM_SIZE); + stream.set(ADDRESS, STREAM_RELEASE, Ffm.NULL); + return true; + } + } + + private static final ConcurrentHashMap REGISTERED = new ConcurrentHashMap<>(); + + /** The bind data of the scan: the registered stream. */ + private static final class ScanBind { + final Registered state; + + ScanBind(Registered state) { + this.state = state; + } + } + + /** The global state of the scan, the stream is released when it is destroyed. */ + private static final class ScanGlobal implements AutoCloseable { + final Arena arena = Arena.ofShared(); + final MemorySegment taken = arena.allocate(STREAM_SIZE, 8); + MemorySegment importer = Ffm.NULL; + boolean finished; + + @Override + public void close() { + if (!released(taken, STREAM_RELEASE)) { + callRelease(taken, STREAM_RELEASE); + taken.set(ADDRESS, STREAM_RELEASE, Ffm.NULL); + } + if (importer.address() != 0) { + try (Arena a = Arena.ofConfined()) { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, importer); + Capi.duckdb_v2_arrow_importer_destroy(holder); + } + importer = Ffm.NULL; + } + arena.close(); + } + } + + private static final MemorySegment SCAN_BIND_STUB = + stub("scanBind", FunctionDescriptor.ofVoid(ADDRESS, ADDRESS, ADDRESS, ADDRESS), + MethodType.methodType(void.class, MemorySegment.class, MemorySegment.class, MemorySegment.class, + MemorySegment.class)); + private static final MemorySegment SCAN_INIT_STUB = + stub("scanInitGlobal", FunctionDescriptor.ofVoid(ADDRESS, ADDRESS, ADDRESS), + MethodType.methodType(void.class, MemorySegment.class, MemorySegment.class, MemorySegment.class)); + private static final MemorySegment SCAN_EXEC_STUB = + stub("scanExec", FunctionDescriptor.ofVoid(ADDRESS, ADDRESS, ADDRESS), + MethodType.methodType(void.class, MemorySegment.class, MemorySegment.class, MemorySegment.class)); + + private static String streamError(MemorySegment stream, String fallback) { + String error = callGetLastError(stream); + return error != null ? error : fallback; + } + + // Resolves the schema into an importer, the schema is released + private static MemorySegment createImporter(MemorySegment context, MemorySegment schema, MemorySegment err) { + try (Arena a = Arena.ofConfined()) { + MemorySegment importer = Ffm.outPtr(a); + MemorySegment callErr = Ffm.outPtr(a); + int state = Capi.duckdb_v2_arrow_importer_create(context, schema, ARROW_SCAN_BATCH_SIZE, importer, callErr); + callRelease(schema, SCHEMA_RELEASE); + if (state != Ffm.ERROR_NONE) { + Ffm.RawError error = Ffm.rawError(state, callErr); + FfmFunctions.setCallbackError(err, error.code, error.message); + return Ffm.NULL; + } + return importer.get(ADDRESS, 0); + } + } + + @SuppressWarnings("unused") + private static void scanBind(MemorySegment info, MemorySegment result, MemorySegment context, MemorySegment err) { + try (Arena a = Arena.ofConfined()) { + MemorySegment value = Ffm.outPtr(a); + MemorySegment id = Ffm.outLong(a); + MemorySegment callErr = Ffm.outPtr(a); + int state = Capi.duckdb_v2_function_bind_get_arg_value(info, 0, value, callErr); + if (state == Ffm.ERROR_NONE) { + state = Capi.duckdb_v2_value_get_bigint(value.get(ADDRESS, 0), id, callErr); + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, value.get(ADDRESS, 0)); + Capi.duckdb_v2_value_destroy(holder); + } + if (state != Ffm.ERROR_NONE) { + Ffm.RawError error = Ffm.rawError(state, callErr); + FfmFunctions.setCallbackError(err, error.code, error.message); + return; + } + Registered registered = REGISTERED.get(id.get(JAVA_LONG, 0)); + if (registered == null) { + FfmFunctions.setCallbackError(err, ERROR_INPUT_INVALID, "This stream has been released"); + return; + } + MemorySegment schema = a.allocate(SCHEMA_SIZE, 8); + synchronized (registered) { + if (registered.closed || released(registered.stream, STREAM_RELEASE)) { + FfmFunctions.setCallbackError(err, ERROR_INPUT_INVALID, "This stream has been released"); + return; + } + if (callGetSchema(registered.stream, schema) != 0) { + FfmFunctions.setCallbackError(err, ERROR_INPUT_INVALID, + streamError(registered.stream, "unable to read the schema")); + return; + } + } + MemorySegment importer = createImporter(context, schema, err); + if (importer.address() == 0) { + return; + } + MemorySegment resolved = Ffm.outPtr(a); + try { + state = Capi.duckdb_v2_arrow_importer_get_schema(importer, resolved, callErr); + } finally { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, importer); + Capi.duckdb_v2_arrow_importer_destroy(holder); + } + if (state != Ffm.ERROR_NONE) { + Ffm.RawError error = Ffm.rawError(state, callErr); + FfmFunctions.setCallbackError(err, error.code, error.message); + return; + } + MemorySegment resolvedSchema = resolved.get(ADDRESS, 0); + try { + MemorySegment count = Ffm.outLong(a); + Capi.duckdb_v2_schema_get_count(resolvedSchema, count, Ffm.NULL); + if (count.get(JAVA_LONG, 0) == 0) { + FfmFunctions.setCallbackError(err, ERROR_INPUT_INVALID, + "Provided table/dataframe must have at least one column"); + return; + } + for (long i = 0; i < count.get(JAVA_LONG, 0); i++) { + MemorySegment name = Ffm.outPtr(a); + MemorySegment nameLen = Ffm.outLong(a); + MemorySegment type = Ffm.outPtr(a); + state = Capi.duckdb_v2_schema_get_field(resolvedSchema, i, name, nameLen, type, callErr); + if (state == Ffm.ERROR_NONE) { + state = Capi.duckdb_v2_table_function_bind_add_result_column( + result, name.get(ADDRESS, 0), nameLen.get(JAVA_LONG, 0), type.get(ADDRESS, 0), callErr); + } + if (state != Ffm.ERROR_NONE) { + Ffm.RawError error = Ffm.rawError(state, callErr); + FfmFunctions.setCallbackError(err, error.code, error.message); + return; + } + } + } finally { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, resolvedSchema); + Capi.duckdb_v2_schema_destroy(holder); + } + state = Capi.duckdb_v2_function_bind_set_bind_data(info, FfmFunctions.opaque(a, new ScanBind(registered)), + callErr); + if (state != Ffm.ERROR_NONE) { + Ffm.RawError error = Ffm.rawError(state, callErr); + FfmFunctions.setCallbackError(err, error.code, error.message); + } + } catch (Throwable t) { + FfmFunctions.setCallbackError(err, ERROR_INPUT_INVALID, String.valueOf(t.getMessage())); + } + } + + @SuppressWarnings("unused") + private static void scanInitGlobal(MemorySegment info, MemorySegment context, MemorySegment err) { + ScanGlobal global = new ScanGlobal(); + boolean ok = false; + try (Arena a = Arena.ofConfined()) { + MemorySegment bind = Ffm.outPtr(a); + MemorySegment callErr = Ffm.outPtr(a); + int state = Capi.duckdb_v2_table_function_init_global_get_bind_data(info, bind, callErr); + if (state != Ffm.ERROR_NONE) { + Ffm.RawError error = Ffm.rawError(state, callErr); + FfmFunctions.setCallbackError(err, error.code, error.message); + return; + } + Object bindData = FfmFunctions.objectOf(bind.get(ADDRESS, 0)); + if (!(bindData instanceof ScanBind)) { + FfmFunctions.setCallbackError(err, ERROR_INPUT_INVALID, "Invalid bind data"); + return; + } + // only the stream of the first scan can be read + if (!((ScanBind) bindData).state.take(global.taken)) { + FfmFunctions.setCallbackError(err, ERROR_INPUT_INVALID, "This stream has been released"); + return; + } + MemorySegment schema = a.allocate(SCHEMA_SIZE, 8); + if (callGetSchema(global.taken, schema) != 0) { + FfmFunctions.setCallbackError(err, ERROR_INPUT_INVALID, + streamError(global.taken, "unable to read the schema")); + return; + } + global.importer = createImporter(context, schema, err); + if (global.importer.address() == 0) { + return; + } + Capi.duckdb_v2_table_function_init_global_set_max_threads(info, 1, Ffm.NULL); + state = Capi.duckdb_v2_table_function_init_global_set_global_state(info, FfmFunctions.opaque(a, global), + callErr); + if (state != Ffm.ERROR_NONE) { + Ffm.RawError error = Ffm.rawError(state, callErr); + FfmFunctions.setCallbackError(err, error.code, error.message); + return; + } + ok = true; + } catch (Throwable t) { + FfmFunctions.setCallbackError(err, ERROR_INPUT_INVALID, String.valueOf(t.getMessage())); + } finally { + if (!ok) { + global.close(); + } + } + } + + @SuppressWarnings("unused") + private static void scanExec(MemorySegment info, MemorySegment context, MemorySegment err) { + try (Arena a = Arena.ofConfined()) { + MemorySegment globalPtr = Ffm.outPtr(a); + MemorySegment callErr = Ffm.outPtr(a); + int state = Capi.duckdb_v2_table_function_exec_get_global_state(info, globalPtr, callErr); + if (state != Ffm.ERROR_NONE) { + Ffm.RawError error = Ffm.rawError(state, callErr); + FfmFunctions.setCallbackError(err, error.code, error.message); + return; + } + Object globalObject = FfmFunctions.objectOf(globalPtr.get(ADDRESS, 0)); + if (!(globalObject instanceof ScanGlobal)) { + FfmFunctions.setCallbackError(err, ERROR_INPUT_INVALID, "Invalid global state"); + return; + } + ScanGlobal global = (ScanGlobal) globalObject; + MemorySegment chunk = Ffm.outPtr(a); + MemorySegment array = a.allocate(ARRAY_SIZE, 8); + while (true) { + state = Capi.duckdb_v2_arrow_importer_next_chunk(global.importer, chunk, callErr); + if (state != Ffm.ERROR_NONE) { + Ffm.RawError error = Ffm.rawError(state, callErr); + FfmFunctions.setCallbackError(err, error.code, error.message); + return; + } + if (chunk.get(ADDRESS, 0).address() != 0) { + break; + } + if (global.finished) { + // an empty output chunk is the end of the scan + return; + } + array.fill((byte) 0); + if (callGetNext(global.taken, array) != 0) { + FfmFunctions.setCallbackError(err, ERROR_INPUT_INVALID, + streamError(global.taken, "unable to read the stream")); + return; + } + boolean end = released(array, ARRAY_RELEASE); + if (end) { + global.finished = true; + } + state = + Capi.duckdb_v2_arrow_importer_append(global.importer, end ? Ffm.NULL : array, true, end, callErr); + if (state != Ffm.ERROR_NONE) { + if (!end && !released(array, ARRAY_RELEASE)) { + callRelease(array, ARRAY_RELEASE); + } + Ffm.RawError error = Ffm.rawError(state, callErr); + FfmFunctions.setCallbackError(err, error.code, error.message); + return; + } + } + MemorySegment imported = chunk.get(ADDRESS, 0); + try { + MemorySegment output = Ffm.outPtr(a); + state = Capi.duckdb_v2_table_function_exec_get_output_chunk(info, output, callErr); + if (state != Ffm.ERROR_NONE) { + Ffm.RawError error = Ffm.rawError(state, callErr); + FfmFunctions.setCallbackError(err, error.code, error.message); + return; + } + MemorySegment columns = Ffm.outLong(a); + MemorySegment rows = Ffm.outLong(a); + Capi.duckdb_v2_data_chunk_get_vector_count(imported, columns, Ffm.NULL); + Capi.duckdb_v2_data_chunk_get_size(imported, rows, Ffm.NULL); + MemorySegment target = Ffm.outPtr(a); + MemorySegment source = Ffm.outPtr(a); + for (long i = 0; i < columns.get(JAVA_LONG, 0); i++) { + state = Capi.duckdb_v2_data_chunk_get_vector(output.get(ADDRESS, 0), i, target, callErr); + if (state == Ffm.ERROR_NONE) { + state = Capi.duckdb_v2_data_chunk_get_vector(imported, i, source, callErr); + } + if (state == Ffm.ERROR_NONE) { + state = + Capi.duckdb_v2_vector_reference(target.get(ADDRESS, 0), source.get(ADDRESS, 0), callErr); + } + if (state == Ffm.ERROR_NONE) { + state = Capi.duckdb_v2_vector_set_size(target.get(ADDRESS, 0), rows.get(JAVA_LONG, 0), callErr); + } + if (state != Ffm.ERROR_NONE) { + Ffm.RawError error = Ffm.rawError(state, callErr); + FfmFunctions.setCallbackError(err, error.code, error.message); + return; + } + } + } finally { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, imported); + Capi.duckdb_v2_data_chunk_destroy(holder); + } + } catch (Throwable t) { + FfmFunctions.setCallbackError(err, ERROR_INPUT_INVALID, String.valueOf(t.getMessage())); + } + } + + /** Registers the table function that scans the registered streams. */ + static void duckdb_v2_arrow_register_scan_function(ByteBuffer conn) throws SQLException { + MemorySegment connPtr = Ffm.ptrNonNull(conn, "connection"); + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_connection_get_factory(connPtr, out, err), err); + MemorySegment factory = out.get(ADDRESS, 0); + Ffm.check(Capi.duckdb_v2_table_function_create(factory, out, err), err); + MemorySegment function = out.get(ADDRESS, 0); + try { + byte[] name = "__jdbc_arrow_stream_scan".getBytes(StandardCharsets.UTF_8); + Ffm.check(Capi.duckdb_v2_table_function_set_name(function, Ffm.bytes(a, name), name.length, err), err); + MemorySegment bigint = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_factory_create_type_from_id(factory, TYPE_ID_BIGINT, Ffm.NULL, Ffm.NULL, + Ffm.NULL, 0, bigint, err), + err); + try { + Ffm.check(Capi.duckdb_v2_table_function_get_signature(function, out, err), err); + byte[] param = "stream_id".getBytes(StandardCharsets.UTF_8); + Ffm.check(Capi.duckdb_v2_function_signature_add_parameter(out.get(ADDRESS, 0), Ffm.bytes(a, param), + param.length, bigint.get(ADDRESS, 0), + Ffm.NULL, KIND_POSITIONAL_ONLY, err), + err); + } finally { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, bigint.get(ADDRESS, 0)); + Capi.duckdb_v2_logical_type_destroy(holder); + } + Ffm.check(Capi.duckdb_v2_table_function_set_bind_callback(function, SCAN_BIND_STUB, err), err); + Ffm.check(Capi.duckdb_v2_table_function_set_init_global_callback(function, SCAN_INIT_STUB, err), err); + Ffm.check(Capi.duckdb_v2_table_function_set_exec_callback(function, SCAN_EXEC_STUB, err), err); + Ffm.check(Capi.duckdb_v2_connection_register_table_function(connPtr, function, err), err); + } finally { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, function); + Capi.duckdb_v2_table_function_destroy(holder); + } + } + } + + /** Moves the stream out of the struct of Java and registers it with the connection, returns its id. */ + static long duckdb_v2_arrow_register_stream(ByteBuffer conn, long streamAddress) throws SQLException { + MemorySegment connPtr = Ffm.ptrNonNull(conn, "connection"); + if (streamAddress == 0) { + throw new SQLException("Invalid Input Error: This stream has been released"); + } + MemorySegment source = MemorySegment.ofAddress(streamAddress).reinterpret(STREAM_SIZE); + if (released(source, STREAM_RELEASE)) { + throw new SQLException("Invalid Input Error: This stream has been released"); + } + Registered registered = new Registered(); + MemorySegment.copy(source, 0, registered.stream, 0, STREAM_SIZE); + source.set(ADDRESS, STREAM_RELEASE, Ffm.NULL); + registered.connection = connPtr.address(); + registered.id = NEXT_ID.getAndIncrement(); + REGISTERED.put(registered.id, registered); + return registered.id; + } + + static void duckdb_v2_arrow_release_stream(long id) throws SQLException { + Registered registered = REGISTERED.remove(id); + if (registered != null) { + registered.release(); + } + } + + /** Closes the exported and the registered streams of the connection that are not released yet. */ + static void duckdb_v2_arrow_close_streams(ByteBuffer conn) throws SQLException { + if (conn == null) { + return; + } + long key = MemorySegment.ofBuffer(conn).address(); + List registeredStreams = new ArrayList<>(); + for (Registered registered : REGISTERED.values()) { + if (registered.connection == key && REGISTERED.remove(registered.id, registered)) { + registeredStreams.add(registered); + } + } + for (Registered registered : registeredStreams) { + registered.release(); + } + List streams; + synchronized (REGISTRY_LOCK) { + streams = BY_CONNECTION.remove(key); + } + if (streams != null) { + // the last stream that was created is the first one that is closed + for (int i = streams.size() - 1; i >= 0; i--) { + streams.get(i).close(); + } + } + } +} diff --git a/src/main/java22/org/duckdb/FfmFunctions.java b/src/main/java22/org/duckdb/FfmFunctions.java new file mode 100644 index 000000000..bf305d1da --- /dev/null +++ b/src/main/java22/org/duckdb/FfmFunctions.java @@ -0,0 +1,1248 @@ +package org.duckdb; + +import static java.lang.foreign.ValueLayout.ADDRESS; +import static java.lang.foreign.ValueLayout.JAVA_BOOLEAN; +import static java.lang.foreign.ValueLayout.JAVA_LONG; + +import java.lang.foreign.Arena; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.MemorySegment; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicLong; + +/** + * The bindings of the scalar functions and of the table functions. The callbacks of the C API are the upcalls of the + * functions of this class, the Java objects of the functions are passed to the C API as the ids of a registry. + */ +final class FfmFunctions { + private FfmFunctions() { + } + + private static final int ERROR_INPUT_INVALID = 2001; + private static final int ERROR_QUERY_BINDER = 5003; + private static final int KIND_POSITIONAL_ONLY = 0; + private static final int KIND_POSITIONAL_VARIADIC = 2; + private static final int KIND_NAMED_VARIADIC = 4; + private static final int PROPERTY_STABILITY = 65536; + private static final int PROPERTY_STABILITY_VOLATILE = 65537; + private static final int PROPERTY_NULL_HANDLING = 65792; + private static final int PROPERTY_NULL_HANDLING_SPECIAL = 65793; + private static final int TYPE_ID_ANY = 3; + private static final int TYPE_ID_VARCHAR = 25; + + // --------------------------------------------------------------------------------------------------------- + // Registries + // --------------------------------------------------------------------------------------------------------- + + // The objects that are passed to the C API as the user data: the pointer of the user data is the id + private static final ConcurrentHashMap OBJECTS = new ConcurrentHashMap<>(); + private static final AtomicLong NEXT_ID = new AtomicLong(1); + + // The objects that are passed to Java as the buffers (specs and infos of the callbacks): the key is the address + private static final ConcurrentHashMap TOKENS = new ConcurrentHashMap<>(); + + private static long register(Object object) { + long id = NEXT_ID.getAndIncrement(); + OBJECTS.put(id, object); + return id; + } + + private static Object object(MemorySegment userData) { + return OBJECTS.get(userData.address()); + } + + /** The object that is registered with the user data. */ + static Object objectOf(MemorySegment userData) { + return object(userData); + } + + /** A buffer for the object, that is valid until the arena is closed. */ + private static ByteBuffer token(Arena arena, Object object) { + MemorySegment segment = arena.allocate(8, 8); + TOKENS.put(segment.address(), object); + return segment.asByteBuffer(); + } + + private static void untoken(ByteBuffer buffer) { + TOKENS.remove(MemorySegment.ofBuffer(buffer).address()); + } + + private static T get(ByteBuffer buffer, Class type, String what) throws SQLException { + if (buffer == null) { + throw new SQLException("Invalid " + what + " buffer"); + } + Object res = TOKENS.get(MemorySegment.ofBuffer(buffer).address()); + if (!type.isInstance(res)) { + throw new SQLException("Invalid " + what); + } + return type.cast(res); + } + + // The state objects: the Java object of the bind data, of the init data and of the local init data is closed when + // the state is destroyed (the same as in the C API v1) + private static final class State { + final Object object; + + State(Object object) { + this.object = object; + } + } + + private static final class ScalarState { ByteBuffer input; } + + private static final MemorySegment DESTROY_STUB = stub("destroyObject", FunctionDescriptor.ofVoid(ADDRESS), + MethodType.methodType(void.class, MemorySegment.class)); + + @SuppressWarnings("unused") + private static void destroyObject(MemorySegment data) { + Object object = OBJECTS.remove(data.address()); + try { + if (object instanceof State) { + DuckDBTableFunctionWrapper.closeTableFunctionState(((State) object).object); + } else if (object instanceof ScalarState) { + ByteBuffer input = ((ScalarState) object).input; + if (input != null) { + FfmVectors.duckdb_destroy_data_chunk(input); + } + } else if (object instanceof AutoCloseable) { + ((AutoCloseable) object).close(); + } + } catch (Throwable t) { + // the callback must not throw + } + } + + private static MemorySegment stub(String name, FunctionDescriptor descriptor, MethodType type) { + try { + MethodHandle target = MethodHandles.lookup().findStatic(FfmFunctions.class, name, type); + return Ffm.LINKER.upcallStub(target, descriptor, Arena.global()); + } catch (ReflectiveOperationException e) { + throw new ExceptionInInitializerError(e); + } + } + + /** The opaque user data (the pointer, the destroy callback and the equals callback) of the registered object. */ + static MemorySegment opaque(Arena arena, Object object) { + MemorySegment res = arena.allocate(24, 8); + res.set(ADDRESS, 0, MemorySegment.ofAddress(register(object))); + res.set(ADDRESS, 8, DESTROY_STUB); + res.set(ADDRESS, 16, Ffm.NULL); + return res; + } + + /** Sets the error of the C API callback, err is the pointer of the error info handle. */ + static void setCallbackError(MemorySegment err, int code, String message) { + if (err.address() == 0) { + return; + } + MemorySegment info = err.reinterpret(8).get(ADDRESS, 0); + if (info.address() == 0) { + return; + } + byte[] bytes = (message == null ? "" : message).getBytes(StandardCharsets.UTF_8); + try (Arena a = Arena.ofConfined()) { + Capi.duckdb_v2_error_info_set_code(info, code); + Capi.duckdb_v2_error_info_set_text(info, Ffm.bytes(a, bytes), bytes.length); + } + } + + private static void setError(MemorySegment err, Ffm.RawError error) { + setCallbackError(err, error.code, error.message); + } + + // A spec of the Java side that holds copies of the logical types + private static final class Types { + private final List types = new ArrayList<>(); + + ByteBuffer copy(ByteBuffer type) throws SQLException { + Ffm.ptrNonNull(type, "logical type"); + ByteBuffer res = FfmTypes.isInvalid(type) ? type : FfmV2.duckdb_v2_logical_type_copy(type); + types.add(res); + return res; + } + + void destroy() { + for (ByteBuffer type : types) { + try { + FfmTypes.duckdb_destroy_logical_type(type); + } catch (SQLException e) { + // nothing else can be done + } + } + types.clear(); + } + } + + private static boolean isValid(ByteBuffer type) { + return type != null && !FfmTypes.isInvalid(type); + } + + // --------------------------------------------------------------------------------------------------------- + // Scalar functions + // --------------------------------------------------------------------------------------------------------- + + private static final class ScalarSpec { + final Types types = new Types(); + String name = ""; + final List parameters = new ArrayList<>(); + ByteBuffer returnType; + ByteBuffer varargs; + boolean isVolatile; + boolean specialHandling; + boolean hasFunction; + Object callback; + } + + private static final class ScalarInfo { + boolean hasError; + String error; + } + + private static final MemorySegment SCALAR_INIT_STUB = + stub("scalarInit", FunctionDescriptor.ofVoid(ADDRESS, ADDRESS, ADDRESS), + MethodType.methodType(void.class, MemorySegment.class, MemorySegment.class, MemorySegment.class)); + + private static final MemorySegment SCALAR_EXEC_STUB = + stub("scalarExec", FunctionDescriptor.ofVoid(ADDRESS, ADDRESS, ADDRESS), + MethodType.methodType(void.class, MemorySegment.class, MemorySegment.class, MemorySegment.class)); + + @SuppressWarnings("unused") + private static void scalarInit(MemorySegment info, MemorySegment context, MemorySegment err) { + try (Arena a = Arena.ofConfined()) { + MemorySegment initErr = Ffm.outPtr(a); + int state = Capi.duckdb_v2_scalar_function_init_set_init_data(info, opaque(a, new ScalarState()), initErr); + if (state != Ffm.ERROR_NONE) { + setError(err, Ffm.rawError(state, initErr)); + } + } catch (Throwable t) { + setCallbackError(err, ERROR_INPUT_INVALID, String.valueOf(t.getMessage())); + } + } + + // The arguments are referenced by the vectors of the input chunk, that is created on the first call + private static void prepareInput(MemorySegment info, MemorySegment context, ScalarState state) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment fixed = a.allocate(32, 8); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_scalar_function_exec_get_arg_count(info, fixed, fixed.asSlice(8), + fixed.asSlice(16), fixed.asSlice(24), err), + err); + int count = (int) (fixed.get(JAVA_LONG, 0) + fixed.get(JAVA_LONG, 8) + fixed.get(JAVA_LONG, 16) + + fixed.get(JAVA_LONG, 24)); + MemorySegment[] args = new MemorySegment[count]; + MemorySegment out = Ffm.outPtr(a); + for (int i = 0; i < count; i++) { + Ffm.check(Capi.duckdb_v2_scalar_function_exec_get_arg(info, i, out, err), err); + args[i] = out.get(ADDRESS, 0); + } + if (state.input == null) { + MemorySegment types = a.allocate(Math.max(1, count) * 8L, 8); + MemorySegment[] owned = new MemorySegment[count]; + try { + for (int i = 0; i < count; i++) { + Ffm.check(Capi.duckdb_v2_vector_get_logical_type(args[i], out, err), err); + owned[i] = out.get(ADDRESS, 0); + types.setAtIndex(ADDRESS, i, owned[i]); + } + MemorySegment factory = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_context_get_factory(context, factory, err), err); + Ffm.check(Capi.duckdb_v2_data_chunk_create(factory.get(ADDRESS, 0), types, count, out, err), err); + state.input = Ffm.handle(out.get(ADDRESS, 0)); + } finally { + for (MemorySegment type : owned) { + if (type != null) { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, type); + Capi.duckdb_v2_logical_type_destroy(holder); + } + } + } + } + MemorySegment input = Ffm.ptr(state.input); + for (int i = 0; i < count; i++) { + Ffm.check(Capi.duckdb_v2_vector_flatten(args[i], err), err); + Ffm.check(Capi.duckdb_v2_data_chunk_get_vector(input, i, out, err), err); + Ffm.check(Capi.duckdb_v2_vector_reference(out.get(ADDRESS, 0), args[i], err), err); + } + } + } + + @SuppressWarnings("unused") + private static void scalarExec(MemorySegment info, MemorySegment context, MemorySegment err) { + try (Arena a = Arena.ofConfined()) { + MemorySegment ptrs = a.allocate(16, 8); + MemorySegment rows = Ffm.outLong(a); + MemorySegment execErr = Ffm.outPtr(a); + int state = Capi.duckdb_v2_scalar_function_exec_get_user_data(info, ptrs, execErr); + if (state == Ffm.ERROR_NONE) { + state = Capi.duckdb_v2_scalar_function_exec_get_init_data(info, ptrs.asSlice(8), execErr); + } + if (state == Ffm.ERROR_NONE) { + state = Capi.duckdb_v2_scalar_function_exec_get_row_count(info, rows, execErr); + } + if (state != Ffm.ERROR_NONE) { + setError(err, Ffm.rawError(state, execErr)); + return; + } + Object callback = object(ptrs.get(ADDRESS, 0)); + if (!(callback instanceof DuckDBScalarFunctionWrapper)) { + setCallbackError(err, ERROR_INPUT_INVALID, "Scalar function callback not found"); + return; + } + Object stateObject = object(ptrs.get(ADDRESS, 8)); + if (!(stateObject instanceof ScalarState)) { + setCallbackError(err, ERROR_INPUT_INVALID, "Scalar function state not found"); + return; + } + ScalarState scalarState = (ScalarState) stateObject; + prepareInput(info, context, scalarState); + + MemorySegment output = Ffm.outPtr(a); + if (Capi.duckdb_v2_scalar_function_exec_get_result(info, output, execErr) != Ffm.ERROR_NONE) { + setCallbackError(err, ERROR_INPUT_INVALID, "Unable to get function result vector"); + return; + } + ScalarInfo scalarInfo = new ScalarInfo(); + ByteBuffer infoBuf = token(a, scalarInfo); + long[] rowCount = new long[] {Ffm.ptr(scalarState.input).address(), rows.get(JAVA_LONG, 0)}; + FfmVectors.SCALAR_INPUT_ROW_COUNT.set(rowCount); + try { + ((DuckDBScalarFunctionWrapper) callback) + .execute(infoBuf, scalarState.input, Ffm.handle(output.get(ADDRESS, 0))); + } finally { + FfmVectors.SCALAR_INPUT_ROW_COUNT.remove(); + untoken(infoBuf); + } + if (scalarInfo.hasError) { + setCallbackError(err, ERROR_INPUT_INVALID, scalarInfo.error); + } + } catch (Throwable t) { + setCallbackError(err, ERROR_INPUT_INVALID, "Java callback system error"); + } + } + + static ByteBuffer duckdb_create_scalar_function() throws SQLException { + MemorySegment segment = Arena.ofAuto().allocate(8, 8); + TOKENS.put(segment.address(), new ScalarSpec()); + return segment.asByteBuffer(); + } + + static void duckdb_destroy_scalar_function(ByteBuffer scalarFunction) throws SQLException { + ScalarSpec spec = get(scalarFunction, ScalarSpec.class, "scalar function"); + TOKENS.remove(MemorySegment.ofBuffer(scalarFunction).address()); + spec.types.destroy(); + } + + static void duckdb_scalar_function_set_name(ByteBuffer scalarFunction, byte[] name) throws SQLException { + ScalarSpec spec = get(scalarFunction, ScalarSpec.class, "scalar function"); + if (name == null) { + throw new SQLException("Invalid scalar function name"); + } + spec.name = new String(name, StandardCharsets.UTF_8); + } + + static void duckdb_scalar_function_add_parameter(ByteBuffer scalarFunction, ByteBuffer logicalType) + throws SQLException { + ScalarSpec spec = get(scalarFunction, ScalarSpec.class, "scalar function"); + spec.parameters.add(spec.types.copy(logicalType)); + } + + static void duckdb_scalar_function_set_return_type(ByteBuffer scalarFunction, ByteBuffer logicalType) + throws SQLException { + ScalarSpec spec = get(scalarFunction, ScalarSpec.class, "scalar function"); + spec.returnType = spec.types.copy(logicalType); + } + + static void duckdb_scalar_function_set_varargs(ByteBuffer scalarFunction, ByteBuffer logicalType) + throws SQLException { + ScalarSpec spec = get(scalarFunction, ScalarSpec.class, "scalar function"); + spec.varargs = spec.types.copy(logicalType); + } + + static void duckdb_scalar_function_set_volatile(ByteBuffer scalarFunction) throws SQLException { + get(scalarFunction, ScalarSpec.class, "scalar function").isVolatile = true; + } + + static void duckdb_scalar_function_set_special_handling(ByteBuffer scalarFunction) throws SQLException { + get(scalarFunction, ScalarSpec.class, "scalar function").specialHandling = true; + } + + static void duckdb_scalar_function_set_extra_info(ByteBuffer scalarFunction, Object callback) throws SQLException { + if (callback == null) { + throw new SQLException("Specified callback must be not null"); + } + get(scalarFunction, ScalarSpec.class, "scalar function").callback = callback; + } + + static void duckdb_scalar_function_set_function(ByteBuffer scalarFunction) throws SQLException { + get(scalarFunction, ScalarSpec.class, "scalar function").hasFunction = true; + } + + static void duckdb_scalar_function_set_error(ByteBuffer functionInfo, byte[] error) throws SQLException { + ScalarInfo info = get(functionInfo, ScalarInfo.class, "scalar function info"); + if (error == null) { + throw new SQLException("Invalid scalar function error"); + } + info.hasError = true; + info.error = new String(error, StandardCharsets.UTF_8); + } + + private static boolean ok(int state) { + return state == Ffm.ERROR_NONE; + } + + static int duckdb_register_scalar_function(ByteBuffer connection, ByteBuffer scalarFunction) throws SQLException { + MemorySegment conn = Ffm.ptrNonNull(connection, "connection"); + ScalarSpec spec = get(scalarFunction, ScalarSpec.class, "scalar function"); + if (spec.name.isEmpty() || !spec.hasFunction || !isValid(spec.returnType)) { + return 1; + } + int returnTypeId = FfmTypes.typeId(Ffm.ptr(spec.returnType)); + if (returnTypeId == FfmTypes.T_INVALID || returnTypeId == FfmTypes.T_ANY) { + return 1; + } + for (ByteBuffer parameter : spec.parameters) { + if (!isValid(parameter)) { + return 1; + } + } + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + if (!ok(Capi.duckdb_v2_connection_get_factory(conn, out, Ffm.NULL))) { + return 1; + } + MemorySegment factory = out.get(ADDRESS, 0); + if (!ok(Capi.duckdb_v2_scalar_function_create(factory, out, Ffm.NULL))) { + return 1; + } + MemorySegment function = out.get(ADDRESS, 0); + try { + byte[] name = spec.name.getBytes(StandardCharsets.UTF_8); + if (!ok(Capi.duckdb_v2_scalar_function_set_name(function, Ffm.bytes(a, name), name.length, Ffm.NULL)) || + !ok(Capi.duckdb_v2_scalar_function_get_signature(function, out, Ffm.NULL))) { + return 1; + } + MemorySegment signature = out.get(ADDRESS, 0); + for (int i = 0; i < spec.parameters.size(); i++) { + byte[] paramName = ("col" + i).getBytes(StandardCharsets.UTF_8); + if (!ok(Capi.duckdb_v2_function_signature_add_parameter( + signature, Ffm.bytes(a, paramName), paramName.length, Ffm.ptr(spec.parameters.get(i)), + Ffm.NULL, KIND_POSITIONAL_ONLY, Ffm.NULL))) { + return 1; + } + } + if (isValid(spec.varargs)) { + if (!ok(Capi.duckdb_v2_function_signature_add_parameter(signature, Ffm.bytes(a, "args".getBytes()), + 4, Ffm.ptr(spec.varargs), Ffm.NULL, + KIND_POSITIONAL_VARIADIC, Ffm.NULL)) || + !ok(Capi.duckdb_v2_function_signature_add_parameter( + signature, Ffm.bytes(a, "kwargs".getBytes()), 6, Ffm.ptr(spec.varargs), Ffm.NULL, + KIND_NAMED_VARIADIC, Ffm.NULL))) { + return 1; + } + } + if (!ok(Capi.duckdb_v2_function_signature_set_return_type(signature, Ffm.ptr(spec.returnType), + Ffm.NULL))) { + return 1; + } + if (spec.isVolatile && !ok(Capi.duckdb_v2_scalar_function_set_property( + function, PROPERTY_STABILITY, PROPERTY_STABILITY_VOLATILE, Ffm.NULL))) { + return 1; + } + if (spec.specialHandling && + !ok(Capi.duckdb_v2_scalar_function_set_property(function, PROPERTY_NULL_HANDLING, + PROPERTY_NULL_HANDLING_SPECIAL, Ffm.NULL))) { + return 1; + } + if (!ok(Capi.duckdb_v2_scalar_function_set_init_callback(function, SCALAR_INIT_STUB, Ffm.NULL)) || + !ok(Capi.duckdb_v2_scalar_function_set_exec_callback(function, SCALAR_EXEC_STUB, Ffm.NULL))) { + return 1; + } + long id = register(spec.callback); + MemorySegment opaque = a.allocate(24, 8); + opaque.set(ADDRESS, 0, MemorySegment.ofAddress(id)); + opaque.set(ADDRESS, 8, DESTROY_STUB); + opaque.set(ADDRESS, 16, Ffm.NULL); + if (!ok(Capi.duckdb_v2_scalar_function_set_user_data(function, opaque, Ffm.NULL))) { + OBJECTS.remove(id); + return 1; + } + if (!ok(Capi.duckdb_v2_connection_register_scalar_function(conn, function, Ffm.NULL))) { + return 1; + } + return 0; + } finally { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, function); + Capi.duckdb_v2_scalar_function_destroy(holder); + } + } + } + + // --------------------------------------------------------------------------------------------------------- + // Table functions + // --------------------------------------------------------------------------------------------------------- + + private static final class TableSpec { + final Types types = new Types(); + String name = ""; + final List parameters = new ArrayList<>(); + final List namedNames = new ArrayList<>(); + final List namedTypes = new ArrayList<>(); + Object callback; + boolean hasBind; + boolean hasInit; + boolean hasLocalInit; + boolean hasFunction; + boolean projectionPushdown; + } + + // The user data of the registered table function + private static final class TableUser { + String name; + DuckDBTableFunctionWrapper callback; + final List namedNames = new ArrayList<>(); + final List namedTypes = new ArrayList<>(); + boolean hasLocalInit; + } + + private static final class BindInfo { + MemorySegment info; + MemorySegment result; + MemorySegment context; + TableUser user; + long positionalCount; + final List namedNames = new ArrayList<>(); + final List namedValues = new ArrayList<>(); + Object bindData; + boolean hasError; + String error; + } + + private static final class InitInfo { + MemorySegment global = Ffm.NULL; + MemorySegment local = Ffm.NULL; + Object initData; + boolean hasError; + String error; + } + + private static final class FunctionInfo { + MemorySegment info; + boolean hasLocalInit; + boolean hasError; + String error; + } + + private static boolean namesEqual(String a, String b) { + return a.length() == b.length() && a.toLowerCase(Locale.ROOT).equals(b.toLowerCase(Locale.ROOT)); + } + + private static String quoteIdentifier(String name) { + return "\"" + name.replace("\"", "\"\"") + "\""; + } + + private static String valueToSqlString(ByteBuffer value) throws SQLException { + if (FfmValues.duckdb_is_null_value(value)) { + return "NULL"; + } + String text = new String(FfmV2.duckdb_v2_value_to_string(value), StandardCharsets.UTF_8); + ByteBuffer type = FfmV2.duckdb_v2_value_get_logical_type(value); + int typeId = typeIdV2(type); + FfmTypes.duckdb_destroy_logical_type(type); + if (typeId != TYPE_ID_VARCHAR) { + return text; + } + return "'" + text.replace("'", "''") + "'"; + } + + private static int typeIdV2(ByteBuffer type) { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outInt(a); + if (Capi.duckdb_v2_logical_type_get_id(Ffm.ptr(type), out, Ffm.NULL) != Ffm.ERROR_NONE) { + return 0; + } + return out.get(java.lang.foreign.ValueLayout.JAVA_INT, 0); + } + } + + private static String typeToString(ByteBuffer type) { + try (Arena a = Arena.ofConfined()) { + MemorySegment len = Ffm.outLong(a); + MemorySegment t = Ffm.ptr(type); + if (Capi.duckdb_v2_logical_type_to_text(t, Ffm.NULL, 0, len, Ffm.NULL) != Ffm.ERROR_NONE) { + return ""; + } + MemorySegment text = a.allocate(len.get(JAVA_LONG, 0) + 1); + if (Capi.duckdb_v2_logical_type_to_text(t, text, len.get(JAVA_LONG, 0) + 1, len, Ffm.NULL) != + Ffm.ERROR_NONE) { + return ""; + } + return Ffm.toString(text, len.get(JAVA_LONG, 0)); + } + } + + private static boolean typesEqual(ByteBuffer left, ByteBuffer right) { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = a.allocate(JAVA_BOOLEAN); + return Capi.duckdb_v2_logical_type_is_equal(Ffm.ptr(left), Ffm.ptr(right), out, Ffm.NULL) == + Ffm.ERROR_NONE && + out.get(JAVA_BOOLEAN, 0); + } + } + + // The named parameters that are passed to the function are checked and cast to the declared types + private static boolean resolveNamedParameters(BindInfo bind, MemorySegment err) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment counts = a.allocate(32, 8); + MemorySegment callErr = Ffm.outPtr(a); + int state = Capi.duckdb_v2_function_bind_get_arg_count(bind.info, counts, counts.asSlice(8), + counts.asSlice(16), counts.asSlice(24), callErr); + if (state != Ffm.ERROR_NONE) { + setError(err, Ffm.rawError(state, callErr)); + return false; + } + bind.positionalCount = counts.get(JAVA_LONG, 0) + counts.get(JAVA_LONG, 8); + long total = bind.positionalCount + counts.get(JAVA_LONG, 16) + counts.get(JAVA_LONG, 24); + for (long i = bind.positionalCount; i < total; i++) { + MemorySegment name = Ffm.outPtr(a); + MemorySegment nameLen = Ffm.outLong(a); + state = Capi.duckdb_v2_function_bind_get_arg_name(bind.info, i, name, nameLen, callErr); + if (state != Ffm.ERROR_NONE) { + setError(err, Ffm.rawError(state, callErr)); + return false; + } + String passedName = Ffm.toString(name.get(ADDRESS, 0), nameLen.get(JAVA_LONG, 0)); + int declared = -1; + for (int j = 0; j < bind.user.namedNames.size(); j++) { + if (namesEqual(bind.user.namedNames.get(j), passedName)) { + declared = j; + break; + } + } + if (declared < 0) { + setCallbackError(err, ERROR_QUERY_BINDER, + "Invalid named parameter " + quoteIdentifier(passedName) + " for function " + + bind.user.name); + return false; + } + String declaredName = bind.user.namedNames.get(declared); + for (String passed : bind.namedNames) { + if (namesEqual(passed, declaredName)) { + setCallbackError(err, ERROR_QUERY_BINDER, + "Named parameter " + quoteIdentifier(declaredName) + + " was passed more than once in function call to " + bind.user.name); + return false; + } + } + MemorySegment valueOut = Ffm.outPtr(a); + state = Capi.duckdb_v2_function_bind_get_arg_value(bind.info, i, valueOut, callErr); + if (state != Ffm.ERROR_NONE) { + setError(err, Ffm.rawError(state, callErr)); + return false; + } + ByteBuffer passedValue = Ffm.handle(valueOut.get(ADDRESS, 0)); + ByteBuffer passedType = null; + try { + passedType = FfmV2.duckdb_v2_value_get_logical_type(passedValue); + ByteBuffer declaredType = bind.user.namedTypes.get(declared); + if (typesEqual(passedType, declaredType)) { + bind.namedNames.add(declaredName); + bind.namedValues.add(passedValue); + passedValue = null; + continue; + } + MemorySegment factory = Ffm.outPtr(a); + state = Capi.duckdb_v2_context_get_factory(bind.context, factory, callErr); + if (state != Ffm.ERROR_NONE) { + setError(err, Ffm.rawError(state, callErr)); + return false; + } + MemorySegment casted = Ffm.outPtr(a); + state = Capi.duckdb_v2_value_cast(factory.get(ADDRESS, 0), Ffm.ptr(passedValue), + Ffm.ptr(declaredType), casted, callErr); + if (state != Ffm.ERROR_NONE) { + Ffm.RawError error = Ffm.rawError(state, callErr); + String message = error.message; + String prefix = "Failed to cast value: "; + if (message.startsWith(prefix)) { + message = message.substring(prefix.length()); + } + setCallbackError(err, ERROR_INPUT_INVALID, + "Could not cast value " + valueToSqlString(passedValue) + + " to named parameter " + quoteIdentifier(declaredName) + " of type " + + typeToString(declaredType) + ": " + message); + return false; + } + bind.namedNames.add(declaredName); + bind.namedValues.add(Ffm.handle(casted.get(ADDRESS, 0))); + } finally { + if (passedType != null) { + FfmTypes.duckdb_destroy_logical_type(passedType); + } + if (passedValue != null) { + FfmV2.duckdb_v2_value_destroy(passedValue); + } + } + } + return true; + } + } + + private static final MemorySegment TABLE_BIND_STUB = + stub("tableBind", FunctionDescriptor.ofVoid(ADDRESS, ADDRESS, ADDRESS, ADDRESS), + MethodType.methodType(void.class, MemorySegment.class, MemorySegment.class, MemorySegment.class, + MemorySegment.class)); + + private static final MemorySegment TABLE_INIT_GLOBAL_STUB = + stub("tableInitGlobal", FunctionDescriptor.ofVoid(ADDRESS, ADDRESS, ADDRESS), + MethodType.methodType(void.class, MemorySegment.class, MemorySegment.class, MemorySegment.class)); + + private static final MemorySegment TABLE_INIT_LOCAL_STUB = + stub("tableInitLocal", FunctionDescriptor.ofVoid(ADDRESS, ADDRESS, ADDRESS), + MethodType.methodType(void.class, MemorySegment.class, MemorySegment.class, MemorySegment.class)); + + private static final MemorySegment TABLE_EXEC_STUB = + stub("tableExec", FunctionDescriptor.ofVoid(ADDRESS, ADDRESS, ADDRESS), + MethodType.methodType(void.class, MemorySegment.class, MemorySegment.class, MemorySegment.class)); + + private static TableUser user(MemorySegment userData) { + Object res = object(userData); + return res instanceof TableUser ? (TableUser) res : null; + } + + @SuppressWarnings("unused") + private static void tableBind(MemorySegment info, MemorySegment result, MemorySegment context, MemorySegment err) { + BindInfo bind = new BindInfo(); + try (Arena a = Arena.ofConfined()) { + MemorySegment userPtr = Ffm.outPtr(a); + if (Capi.duckdb_v2_function_bind_get_user_data(info, userPtr, Ffm.NULL) != Ffm.ERROR_NONE) { + setCallbackError(err, ERROR_QUERY_BINDER, "Table function callback not found"); + return; + } + TableUser user = user(userPtr.get(ADDRESS, 0)); + if (user == null || user.callback == null) { + setCallbackError(err, ERROR_QUERY_BINDER, "Table function callback not found"); + return; + } + bind.info = info; + bind.result = result; + bind.context = context; + bind.user = user; + try { + if (!resolveNamedParameters(bind, err)) { + return; + } + ByteBuffer infoBuf = token(a, bind); + try { + user.callback.executeBind(infoBuf); + } finally { + untoken(infoBuf); + } + if (bind.hasError) { + setCallbackError(err, ERROR_QUERY_BINDER, bind.error); + return; + } + MemorySegment callErr = Ffm.outPtr(a); + int state = + Capi.duckdb_v2_function_bind_set_bind_data(info, opaque(a, new State(bind.bindData)), callErr); + if (state != Ffm.ERROR_NONE) { + setError(err, Ffm.rawError(state, callErr)); + } + } finally { + for (ByteBuffer value : bind.namedValues) { + try { + FfmV2.duckdb_v2_value_destroy(value); + } catch (SQLException e) { + // nothing else can be done + } + } + } + } catch (Throwable t) { + setCallbackError(err, ERROR_QUERY_BINDER, "Java callback system error"); + } + } + + @SuppressWarnings("unused") + private static void tableInitGlobal(MemorySegment info, MemorySegment context, MemorySegment err) { + try (Arena a = Arena.ofConfined()) { + MemorySegment userPtr = Ffm.outPtr(a); + Capi.duckdb_v2_table_function_init_global_get_user_data(info, userPtr, Ffm.NULL); + TableUser user = user(userPtr.get(ADDRESS, 0)); + if (user == null || user.callback == null) { + setCallbackError(err, ERROR_INPUT_INVALID, "Table function callback not found"); + return; + } + InitInfo init = new InitInfo(); + init.global = info; + ByteBuffer infoBuf = token(a, init); + try { + user.callback.executeGlobalInit(infoBuf); + } finally { + untoken(infoBuf); + } + if (init.hasError) { + setCallbackError(err, ERROR_INPUT_INVALID, init.error); + return; + } + MemorySegment callErr = Ffm.outPtr(a); + int state = Capi.duckdb_v2_table_function_init_global_set_global_state( + info, opaque(a, new State(init.initData)), callErr); + if (state != Ffm.ERROR_NONE) { + setError(err, Ffm.rawError(state, callErr)); + } + } catch (Throwable t) { + setCallbackError(err, ERROR_INPUT_INVALID, "Java callback system error"); + } + } + + @SuppressWarnings("unused") + private static void tableInitLocal(MemorySegment info, MemorySegment context, MemorySegment err) { + try (Arena a = Arena.ofConfined()) { + MemorySegment userPtr = Ffm.outPtr(a); + Capi.duckdb_v2_table_function_init_local_get_user_data(info, userPtr, Ffm.NULL); + TableUser user = user(userPtr.get(ADDRESS, 0)); + if (user == null || user.callback == null) { + setCallbackError(err, ERROR_INPUT_INVALID, "Table function callback not found"); + return; + } + InitInfo init = new InitInfo(); + init.local = info; + ByteBuffer infoBuf = token(a, init); + try { + user.callback.executeLocalInit(infoBuf); + } finally { + untoken(infoBuf); + } + if (init.hasError) { + setCallbackError(err, ERROR_INPUT_INVALID, init.error); + return; + } + MemorySegment callErr = Ffm.outPtr(a); + int state = Capi.duckdb_v2_table_function_init_local_set_local_state( + info, opaque(a, new State(init.initData)), callErr); + if (state != Ffm.ERROR_NONE) { + setError(err, Ffm.rawError(state, callErr)); + } + } catch (Throwable t) { + setCallbackError(err, ERROR_INPUT_INVALID, "Java callback system error"); + } + } + + @SuppressWarnings("unused") + private static void tableExec(MemorySegment info, MemorySegment context, MemorySegment err) { + try (Arena a = Arena.ofConfined()) { + MemorySegment userPtr = Ffm.outPtr(a); + Capi.duckdb_v2_table_function_exec_get_user_data(info, userPtr, Ffm.NULL); + TableUser user = user(userPtr.get(ADDRESS, 0)); + if (user == null || user.callback == null) { + setCallbackError(err, ERROR_INPUT_INVALID, "Table function callback not found"); + return; + } + MemorySegment output = Ffm.outPtr(a); + MemorySegment callErr = Ffm.outPtr(a); + int state = Capi.duckdb_v2_table_function_exec_get_output_chunk(info, output, callErr); + if (state != Ffm.ERROR_NONE) { + setError(err, Ffm.rawError(state, callErr)); + return; + } + FunctionInfo function = new FunctionInfo(); + function.info = info; + function.hasLocalInit = user.hasLocalInit; + ByteBuffer infoBuf = token(a, function); + try { + user.callback.executeFunction(infoBuf, Ffm.handle(output.get(ADDRESS, 0))); + } finally { + untoken(infoBuf); + } + if (function.hasError) { + setCallbackError(err, ERROR_INPUT_INVALID, function.error); + } + } catch (Throwable t) { + setCallbackError(err, ERROR_INPUT_INVALID, "Java callback system error"); + } + } + + static ByteBuffer duckdb_create_table_function() throws SQLException { + MemorySegment segment = Arena.ofAuto().allocate(8, 8); + TOKENS.put(segment.address(), new TableSpec()); + return segment.asByteBuffer(); + } + + static void duckdb_destroy_table_function(ByteBuffer tableFunction) throws SQLException { + TableSpec spec = get(tableFunction, TableSpec.class, "table function"); + TOKENS.remove(MemorySegment.ofBuffer(tableFunction).address()); + spec.types.destroy(); + } + + static void duckdb_table_function_set_name(ByteBuffer tableFunction, byte[] name) throws SQLException { + TableSpec spec = get(tableFunction, TableSpec.class, "table function"); + String str = name == null ? "" : new String(name, StandardCharsets.UTF_8); + if (str.isEmpty()) { + throw new SQLException("Specified function name must be not empty"); + } + spec.name = str; + } + + static void duckdb_table_function_add_parameter(ByteBuffer tableFunction, ByteBuffer logicalType) + throws SQLException { + TableSpec spec = get(tableFunction, TableSpec.class, "table function"); + spec.parameters.add(spec.types.copy(logicalType)); + } + + static void duckdb_table_function_add_named_parameter(ByteBuffer tableFunction, byte[] name, ByteBuffer logicalType) + throws SQLException { + TableSpec spec = get(tableFunction, TableSpec.class, "table function"); + String str = name == null ? "" : new String(name, StandardCharsets.UTF_8); + if (str.isEmpty()) { + throw new SQLException("Specified parameter name must be not empty"); + } + Ffm.ptrNonNull(logicalType, "logical type"); + for (String existing : spec.namedNames) { + if (namesEqual(existing, str)) { + return; + } + } + spec.namedNames.add(str); + spec.namedTypes.add(spec.types.copy(logicalType)); + } + + static void duckdb_table_function_set_extra_info(ByteBuffer tableFunction, Object callback) throws SQLException { + if (callback == null) { + throw new SQLException("Specified callback must be not null"); + } + get(tableFunction, TableSpec.class, "table function").callback = callback; + } + + static void duckdb_table_function_set_bind(ByteBuffer tableFunction) throws SQLException { + get(tableFunction, TableSpec.class, "table function").hasBind = true; + } + + static void duckdb_table_function_set_init(ByteBuffer tableFunction) throws SQLException { + get(tableFunction, TableSpec.class, "table function").hasInit = true; + } + + static void duckdb_table_function_set_local_init(ByteBuffer tableFunction) throws SQLException { + get(tableFunction, TableSpec.class, "table function").hasLocalInit = true; + } + + static void duckdb_table_function_set_function(ByteBuffer tableFunction) throws SQLException { + get(tableFunction, TableSpec.class, "table function").hasFunction = true; + } + + static void duckdb_table_function_supports_projection_pushdown(ByteBuffer tableFunction, boolean pushdown) + throws SQLException { + get(tableFunction, TableSpec.class, "table function").projectionPushdown = pushdown; + } + + static int duckdb_register_table_function(ByteBuffer connection, ByteBuffer tableFunction) throws SQLException { + MemorySegment conn = Ffm.ptrNonNull(connection, "connection"); + TableSpec spec = get(tableFunction, TableSpec.class, "table function"); + if (spec.name.isEmpty() || !spec.hasBind || !spec.hasInit || !spec.hasFunction || + !(spec.callback instanceof DuckDBTableFunctionWrapper)) { + return 1; + } + for (ByteBuffer parameter : spec.parameters) { + if (!isValid(parameter)) { + return 1; + } + } + for (ByteBuffer type : spec.namedTypes) { + if (!isValid(type)) { + return 1; + } + } + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + if (!ok(Capi.duckdb_v2_connection_get_factory(conn, out, Ffm.NULL))) { + return 1; + } + MemorySegment factory = out.get(ADDRESS, 0); + if (!ok(Capi.duckdb_v2_table_function_create(factory, out, Ffm.NULL))) { + return 1; + } + MemorySegment function = out.get(ADDRESS, 0); + try { + byte[] name = spec.name.getBytes(StandardCharsets.UTF_8); + if (!ok(Capi.duckdb_v2_table_function_set_name(function, Ffm.bytes(a, name), name.length, Ffm.NULL)) || + !ok(Capi.duckdb_v2_table_function_get_signature(function, out, Ffm.NULL))) { + return 1; + } + MemorySegment signature = out.get(ADDRESS, 0); + for (int i = 0; i < spec.parameters.size(); i++) { + byte[] paramName = ("col" + i).getBytes(StandardCharsets.UTF_8); + if (!ok(Capi.duckdb_v2_function_signature_add_parameter( + signature, Ffm.bytes(a, paramName), paramName.length, Ffm.ptr(spec.parameters.get(i)), + Ffm.NULL, KIND_POSITIONAL_ONLY, Ffm.NULL))) { + return 1; + } + } + if (!spec.namedNames.isEmpty()) { + // the named parameters are checked and cast in the bind callback + MemorySegment any = Ffm.outPtr(a); + if (!ok(Capi.duckdb_v2_factory_create_type_from_id(factory, TYPE_ID_ANY, Ffm.NULL, Ffm.NULL, + Ffm.NULL, 0, any, Ffm.NULL))) { + return 1; + } + int state = Capi.duckdb_v2_function_signature_add_parameter( + signature, Ffm.bytes(a, "options".getBytes()), 7, any.get(ADDRESS, 0), Ffm.NULL, + KIND_NAMED_VARIADIC, Ffm.NULL); + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, any.get(ADDRESS, 0)); + Capi.duckdb_v2_logical_type_destroy(holder); + if (!ok(state)) { + return 1; + } + } + if (!ok(Capi.duckdb_v2_table_function_set_bind_callback(function, TABLE_BIND_STUB, Ffm.NULL)) || + !ok(Capi.duckdb_v2_table_function_set_init_global_callback(function, TABLE_INIT_GLOBAL_STUB, + Ffm.NULL)) || + (spec.hasLocalInit && !ok(Capi.duckdb_v2_table_function_set_init_local_callback( + function, TABLE_INIT_LOCAL_STUB, Ffm.NULL))) || + !ok(Capi.duckdb_v2_table_function_set_exec_callback(function, TABLE_EXEC_STUB, Ffm.NULL)) || + !ok(Capi.duckdb_v2_table_function_set_projection_pushdown(function, spec.projectionPushdown, + Ffm.NULL))) { + return 1; + } + // the user data owns the callback and the copies of the types of the named parameters + TableUser user = new TableUser(); + user.name = spec.name; + user.callback = (DuckDBTableFunctionWrapper) spec.callback; + user.hasLocalInit = spec.hasLocalInit; + for (int i = 0; i < spec.namedNames.size(); i++) { + user.namedNames.add(spec.namedNames.get(i)); + user.namedTypes.add(FfmV2.duckdb_v2_logical_type_copy(spec.namedTypes.get(i))); + } + long id = register(user); + MemorySegment opaque = a.allocate(24, 8); + opaque.set(ADDRESS, 0, MemorySegment.ofAddress(id)); + opaque.set(ADDRESS, 8, DESTROY_STUB); + opaque.set(ADDRESS, 16, Ffm.NULL); + if (!ok(Capi.duckdb_v2_table_function_set_user_data(function, opaque, Ffm.NULL))) { + OBJECTS.remove(id); + return 1; + } + if (!ok(Capi.duckdb_v2_connection_register_table_function(conn, function, Ffm.NULL))) { + return 1; + } + return 0; + } finally { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, function); + Capi.duckdb_v2_table_function_destroy(holder); + } + } + } + + // --------------------------------------------------------------------------------------------------------- + // The bind info, the init info and the function info of the table functions + // --------------------------------------------------------------------------------------------------------- + + static void duckdb_bind_add_result_column(ByteBuffer bindInfo, byte[] name, ByteBuffer logicalType) + throws SQLException { + BindInfo bind = get(bindInfo, BindInfo.class, "table function bind info"); + String str = name == null ? "" : new String(name, StandardCharsets.UTF_8); + if (str.isEmpty()) { + throw new SQLException("Specified result column name must be not empty"); + } + MemorySegment type = FfmTypes.typePtr(logicalType); + int typeId = FfmTypes.typeId(type); + if (typeId == FfmTypes.T_INVALID || typeId == FfmTypes.T_ANY) { + throw new SQLException("Invalid result column type"); + } + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_table_function_bind_add_result_column(bind.result, Ffm.bytes(a, name), name.length, + type, err), + err); + } + } + + static long duckdb_bind_get_parameter_count(ByteBuffer bindInfo) throws SQLException { + return get(bindInfo, BindInfo.class, "table function bind info").positionalCount; + } + + static ByteBuffer duckdb_bind_get_parameter(ByteBuffer bindInfo, long index) throws SQLException { + BindInfo bind = get(bindInfo, BindInfo.class, "table function bind info"); + if (index < 0 || index >= bind.positionalCount) { + return null; + } + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_function_bind_get_arg_value(bind.info, index, out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_bind_get_named_parameter(ByteBuffer bindInfo, byte[] name) throws SQLException { + BindInfo bind = get(bindInfo, BindInfo.class, "table function bind info"); + String str = name == null ? "" : new String(name, StandardCharsets.UTF_8); + for (int i = 0; i < bind.namedNames.size(); i++) { + if (!namesEqual(bind.namedNames.get(i), str)) { + continue; + } + ByteBuffer value = bind.namedValues.get(i); + ByteBuffer type = FfmV2.duckdb_v2_value_get_logical_type(value); + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_cast(Ffm.ptr(FfmTypes.defaultFactory()), Ffm.ptr(value), Ffm.ptr(type), + out, err), + err); + return Ffm.handle(out.get(ADDRESS, 0)); + } finally { + FfmTypes.duckdb_destroy_logical_type(type); + } + } + return null; + } + + static void duckdb_bind_set_bind_data(ByteBuffer bindInfo, Object bindData) throws SQLException { + if (bindData == null) { + throw new SQLException("Specified bind data must be not null"); + } + get(bindInfo, BindInfo.class, "table function bind info").bindData = bindData; + } + + static void duckdb_bind_set_cardinality(ByteBuffer bindInfo, long cardinality, boolean isExact) + throws SQLException { + BindInfo bind = get(bindInfo, BindInfo.class, "table function bind info"); + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_table_function_bind_set_cardinality(bind.result, cardinality, isExact, err), err); + } + } + + static void duckdb_bind_set_error(ByteBuffer bindInfo, byte[] error) throws SQLException { + BindInfo bind = get(bindInfo, BindInfo.class, "table function bind info"); + bind.hasError = true; + bind.error = error == null ? "" : new String(error, StandardCharsets.UTF_8); + } + + private static Object stateObject(MemorySegment data) { + Object res = object(data); + return res instanceof State ? ((State) res).object : null; + } + + static Object duckdb_init_get_bind_data(ByteBuffer initInfo) throws SQLException { + InitInfo init = get(initInfo, InitInfo.class, "table function init info"); + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + int state = init.global.address() != 0 + ? Capi.duckdb_v2_table_function_init_global_get_bind_data(init.global, out, err) + : Capi.duckdb_v2_table_function_init_local_get_bind_data(init.local, out, err); + Ffm.check(state, err); + return stateObject(out.get(ADDRESS, 0)); + } + } + + static void duckdb_init_set_init_data(ByteBuffer initInfo, Object initData) throws SQLException { + if (initData == null) { + throw new SQLException("Specified init data must be not null"); + } + get(initInfo, InitInfo.class, "table function init info").initData = initData; + } + + static long duckdb_init_get_column_count(ByteBuffer initInfo) throws SQLException { + InitInfo init = get(initInfo, InitInfo.class, "table function init info"); + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outLong(a); + MemorySegment err = Ffm.outPtr(a); + int state = init.global.address() != 0 + ? Capi.duckdb_v2_table_function_init_global_get_column_count(init.global, out, err) + : Capi.duckdb_v2_table_function_init_local_get_column_count(init.local, out, err); + Ffm.check(state, err); + return out.get(JAVA_LONG, 0); + } + } + + static long duckdb_init_get_column_index(ByteBuffer initInfo, long columnIndex) throws SQLException { + InitInfo init = get(initInfo, InitInfo.class, "table function init info"); + if (columnIndex < 0) { + return 0; + } + try (Arena a = Arena.ofConfined()) { + MemorySegment count = Ffm.outLong(a); + MemorySegment idx = Ffm.outLong(a); + if (init.global.address() != 0) { + if (Capi.duckdb_v2_table_function_init_global_get_column_count(init.global, count, Ffm.NULL) == + Ffm.ERROR_NONE && + columnIndex < count.get(JAVA_LONG, 0)) { + Capi.duckdb_v2_table_function_init_global_get_column_index(init.global, columnIndex, idx, Ffm.NULL); + } + } else if (Capi.duckdb_v2_table_function_init_local_get_column_count(init.local, count, Ffm.NULL) == + Ffm.ERROR_NONE && + columnIndex < count.get(JAVA_LONG, 0)) { + Capi.duckdb_v2_table_function_init_local_get_column_index(init.local, columnIndex, idx, Ffm.NULL); + } + return idx.get(JAVA_LONG, 0); + } + } + + static void duckdb_init_set_max_threads(ByteBuffer initInfo, long maxThreads) throws SQLException { + InitInfo init = get(initInfo, InitInfo.class, "table function init info"); + if (init.global.address() == 0) { + return; + } + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_table_function_init_global_set_max_threads(init.global, maxThreads, err), err); + } + } + + static void duckdb_init_set_error(ByteBuffer initInfo, byte[] error) throws SQLException { + InitInfo init = get(initInfo, InitInfo.class, "table function init info"); + init.hasError = true; + init.error = error == null ? "" : new String(error, StandardCharsets.UTF_8); + } + + static Object duckdb_function_get_bind_data(ByteBuffer functionInfo) throws SQLException { + FunctionInfo function = get(functionInfo, FunctionInfo.class, "function info"); + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_table_function_exec_get_bind_data(function.info, out, err), err); + return stateObject(out.get(ADDRESS, 0)); + } + } + + static Object duckdb_function_get_init_data(ByteBuffer functionInfo) throws SQLException { + FunctionInfo function = get(functionInfo, FunctionInfo.class, "function info"); + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_table_function_exec_get_global_state(function.info, out, err), err); + return stateObject(out.get(ADDRESS, 0)); + } + } + + static Object duckdb_function_get_local_init_data(ByteBuffer functionInfo) throws SQLException { + FunctionInfo function = get(functionInfo, FunctionInfo.class, "function info"); + if (!function.hasLocalInit) { + return null; + } + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_table_function_exec_get_local_state(function.info, out, err), err); + return stateObject(out.get(ADDRESS, 0)); + } + } + + static void duckdb_function_set_error(ByteBuffer functionInfo, byte[] error) throws SQLException { + FunctionInfo function = get(functionInfo, FunctionInfo.class, "function info"); + function.hasError = true; + function.error = error == null ? "" : new String(error, StandardCharsets.UTF_8); + } +} diff --git a/src/main/java22/org/duckdb/FfmTypes.java b/src/main/java22/org/duckdb/FfmTypes.java new file mode 100644 index 000000000..6b80a6e24 --- /dev/null +++ b/src/main/java22/org/duckdb/FfmTypes.java @@ -0,0 +1,717 @@ +package org.duckdb; + +import static java.lang.foreign.ValueLayout.ADDRESS; +import static java.lang.foreign.ValueLayout.JAVA_INT; +import static java.lang.foreign.ValueLayout.JAVA_LONG; + +import java.lang.foreign.Arena; +import java.lang.foreign.MemorySegment; +import java.nio.ByteBuffer; +import java.sql.SQLException; + +/** The bindings of the logical types. The type IDs that are passed to Java are the ones of the C API v1. */ +final class FfmTypes { + private FfmTypes() { + } + + // type IDs of the C API v1 + static final int T_INVALID = 0; + static final int T_BOOLEAN = 1; + static final int T_TINYINT = 2; + static final int T_SMALLINT = 3; + static final int T_INTEGER = 4; + static final int T_BIGINT = 5; + static final int T_UTINYINT = 6; + static final int T_USMALLINT = 7; + static final int T_UINTEGER = 8; + static final int T_UBIGINT = 9; + static final int T_FLOAT = 10; + static final int T_DOUBLE = 11; + static final int T_TIMESTAMP = 12; + static final int T_DATE = 13; + static final int T_TIME = 14; + static final int T_INTERVAL = 15; + static final int T_HUGEINT = 16; + static final int T_VARCHAR = 17; + static final int T_BLOB = 18; + static final int T_DECIMAL = 19; + static final int T_TIMESTAMP_S = 20; + static final int T_TIMESTAMP_MS = 21; + static final int T_TIMESTAMP_NS = 22; + static final int T_ENUM = 23; + static final int T_LIST = 24; + static final int T_STRUCT = 25; + static final int T_MAP = 26; + static final int T_UUID = 27; + static final int T_UNION = 28; + static final int T_BIT = 29; + static final int T_TIME_TZ = 30; + static final int T_TIMESTAMP_TZ = 31; + static final int T_UHUGEINT = 32; + static final int T_ARRAY = 33; + static final int T_ANY = 34; + static final int T_BIGNUM = 35; + static final int T_SQLNULL = 36; + static final int T_TIME_NS = 39; + static final int T_GEOMETRY = 40; + static final int T_VARIANT = 41; + static final int T_TIMESTAMP_TZ_NS = 42; + static final int T_GEOGRAPHY = 43; + + // type IDs of the C API v2 + private static final int V_SQLNULL = 1; + private static final int V_ANY = 3; + private static final int V_BOOLEAN = 10; + private static final int V_TINYINT = 11; + private static final int V_SMALLINT = 12; + private static final int V_INTEGER = 13; + private static final int V_BIGINT = 14; + private static final int V_DATE = 15; + private static final int V_TIME = 16; + private static final int V_TIMESTAMP_SEC = 17; + private static final int V_TIMESTAMP_MS = 18; + private static final int V_TIMESTAMP = 19; + private static final int V_TIMESTAMP_NS = 20; + private static final int V_DECIMAL = 21; + private static final int V_FLOAT = 22; + private static final int V_DOUBLE = 23; + private static final int V_VARCHAR = 25; + private static final int V_BLOB = 26; + private static final int V_INTERVAL = 27; + private static final int V_UTINYINT = 28; + private static final int V_USMALLINT = 29; + private static final int V_UINTEGER = 30; + private static final int V_UBIGINT = 31; + private static final int V_TIMESTAMP_TZ = 32; + private static final int V_TIMESTAMP_TZ_NS = 33; + private static final int V_TIME_TZ = 34; + private static final int V_TIME_NS = 35; + private static final int V_BIT = 36; + private static final int V_BIGNUM = 39; + private static final int V_UHUGEINT = 49; + private static final int V_HUGEINT = 50; + private static final int V_UUID = 54; + private static final int V_GEOMETRY = 60; + private static final int V_GEOGRAPHY = 61; + private static final int V_STRUCT = 100; + private static final int V_LIST = 101; + private static final int V_MAP = 102; + private static final int V_ENUM = 104; + private static final int V_UNION = 107; + private static final int V_ARRAY = 108; + private static final int V_VARIANT = 109; + private static final int V_TUPLE = 110; + + /** The placeholder of the INVALID type, that cannot be created with the C API v2. It is never passed to it. */ + static final ByteBuffer INVALID = Ffm.handle(Arena.global().allocate(8).address()); + + private static ByteBuffer defaultFactory; + + /** + * The factory of an instance that has no databases, it is used to create types, values and data chunks that are + * not related to a connection. It knows only the built-in types and casts. + */ + static synchronized ByteBuffer defaultFactory() throws SQLException { + if (defaultFactory == null) { + ByteBuffer environment = FfmV2.duckdb_v2_environment_create(); + ByteBuffer instance = + FfmV2.duckdb_v2_instance_create_with_options(environment, new byte[0][], new byte[0][]); + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_instance_get_factory(Ffm.ptr(instance), out, err), err); + defaultFactory = Ffm.handle(out.get(ADDRESS, 0)); + } + } + return defaultFactory; + } + + /** The pointer of the type, the placeholder of the INVALID type is rejected. */ + static MemorySegment typePtr(ByteBuffer type) throws SQLException { + MemorySegment res = Ffm.ptrNonNull(type, "logical type"); + if (res.address() == MemorySegment.ofBuffer(INVALID).address()) { + throw new SQLException("The INVALID logical type cannot be used"); + } + return res; + } + + static boolean isInvalid(ByteBuffer type) { + return MemorySegment.ofBuffer(type).address() == MemorySegment.ofBuffer(INVALID).address(); + } + + /** The ID (of the C API v1) of the type, the placeholder of the INVALID type is INVALID. */ + static int typeId(MemorySegment type) { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outInt(a); + if (Capi.duckdb_v2_logical_type_get_id(type, out, Ffm.NULL) != Ffm.ERROR_NONE) { + return T_INVALID; + } + return toCapi(out.get(JAVA_INT, 0)); + } + } + + static int toCapi(int id) { + switch (id) { + case V_SQLNULL: + return T_SQLNULL; + case V_ANY: + return T_ANY; + case V_BOOLEAN: + return T_BOOLEAN; + case V_TINYINT: + return T_TINYINT; + case V_SMALLINT: + return T_SMALLINT; + case V_INTEGER: + return T_INTEGER; + case V_BIGINT: + return T_BIGINT; + case V_DATE: + return T_DATE; + case V_TIME: + return T_TIME; + case V_TIMESTAMP_SEC: + return T_TIMESTAMP_S; + case V_TIMESTAMP_MS: + return T_TIMESTAMP_MS; + case V_TIMESTAMP: + return T_TIMESTAMP; + case V_TIMESTAMP_NS: + return T_TIMESTAMP_NS; + case V_DECIMAL: + return T_DECIMAL; + case V_FLOAT: + return T_FLOAT; + case V_DOUBLE: + return T_DOUBLE; + case V_VARCHAR: + return T_VARCHAR; + case V_BLOB: + return T_BLOB; + case V_INTERVAL: + return T_INTERVAL; + case V_UTINYINT: + return T_UTINYINT; + case V_USMALLINT: + return T_USMALLINT; + case V_UINTEGER: + return T_UINTEGER; + case V_UBIGINT: + return T_UBIGINT; + case V_TIMESTAMP_TZ: + return T_TIMESTAMP_TZ; + case V_TIMESTAMP_TZ_NS: + return T_TIMESTAMP_TZ_NS; + case V_TIME_TZ: + return T_TIME_TZ; + case V_TIME_NS: + return T_TIME_NS; + case V_BIT: + return T_BIT; + case V_BIGNUM: + return T_BIGNUM; + case V_UHUGEINT: + return T_UHUGEINT; + case V_HUGEINT: + return T_HUGEINT; + case V_UUID: + return T_UUID; + case V_GEOMETRY: + return T_GEOMETRY; + case V_GEOGRAPHY: + return T_GEOGRAPHY; + case V_STRUCT: + case V_TUPLE: + return T_STRUCT; + case V_LIST: + return T_LIST; + case V_MAP: + return T_MAP; + case V_ENUM: + return T_ENUM; + case V_UNION: + return T_UNION; + case V_ARRAY: + return T_ARRAY; + case V_VARIANT: + return T_VARIANT; + default: + return T_INVALID; + } + } + + /** The ID of the C API v2 of the type ID of the C API v1, -1 if the type cannot be created. */ + static int fromCapi(int id) { + switch (id) { + case T_BOOLEAN: + return V_BOOLEAN; + case T_TINYINT: + return V_TINYINT; + case T_SMALLINT: + return V_SMALLINT; + case T_INTEGER: + return V_INTEGER; + case T_BIGINT: + return V_BIGINT; + case T_UTINYINT: + return V_UTINYINT; + case T_USMALLINT: + return V_USMALLINT; + case T_UINTEGER: + return V_UINTEGER; + case T_UBIGINT: + return V_UBIGINT; + case T_HUGEINT: + return V_HUGEINT; + case T_UHUGEINT: + return V_UHUGEINT; + case T_FLOAT: + return V_FLOAT; + case T_DOUBLE: + return V_DOUBLE; + case T_TIMESTAMP: + return V_TIMESTAMP; + case T_TIMESTAMP_TZ: + return V_TIMESTAMP_TZ; + case T_TIMESTAMP_TZ_NS: + return V_TIMESTAMP_TZ_NS; + case T_TIMESTAMP_S: + return V_TIMESTAMP_SEC; + case T_TIMESTAMP_MS: + return V_TIMESTAMP_MS; + case T_TIMESTAMP_NS: + return V_TIMESTAMP_NS; + case T_DATE: + return V_DATE; + case T_TIME: + return V_TIME; + case T_TIME_TZ: + return V_TIME_TZ; + case T_TIME_NS: + return V_TIME_NS; + case T_VARCHAR: + return V_VARCHAR; + case T_BLOB: + return V_BLOB; + case T_BIT: + return V_BIT; + case T_BIGNUM: + return V_BIGNUM; + case T_INTERVAL: + return V_INTERVAL; + case T_DECIMAL: + return V_DECIMAL; + case T_ENUM: + return V_ENUM; + case T_LIST: + return V_LIST; + case T_STRUCT: + return V_STRUCT; + case T_MAP: + return V_MAP; + case T_UNION: + return V_UNION; + case T_UUID: + return V_UUID; + case T_ARRAY: + return V_ARRAY; + case T_ANY: + return V_ANY; + case T_SQLNULL: + return V_SQLNULL; + case T_GEOMETRY: + return V_GEOMETRY; + case T_GEOGRAPHY: + return V_GEOGRAPHY; + case T_VARIANT: + return V_VARIANT; + default: + return -1; + } + } + + private static void destroyValue(MemorySegment value) { + if (value.address() == 0) { + return; + } + try (Arena a = Arena.ofConfined()) { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, value); + Capi.duckdb_v2_value_destroy(holder); + } + } + + /** The parameter of the type, the caller destroys the value. Returns NULL if there is no such parameter. */ + private static MemorySegment typeParam(MemorySegment type, long index) { + try (Arena a = Arena.ofConfined()) { + MemorySegment name = Ffm.outPtr(a); + MemorySegment nameLen = Ffm.outLong(a); + MemorySegment value = Ffm.outPtr(a); + if (Capi.duckdb_v2_logical_type_get_param(type, index, name, nameLen, value, Ffm.NULL) != Ffm.ERROR_NONE) { + return Ffm.NULL; + } + return value.get(ADDRESS, 0); + } + } + + private static byte[] typeParamName(MemorySegment type, long index) { + try (Arena a = Arena.ofConfined()) { + MemorySegment name = Ffm.outPtr(a); + MemorySegment nameLen = Ffm.outLong(a); + MemorySegment value = Ffm.outPtr(a); + if (Capi.duckdb_v2_logical_type_get_param(type, index, name, nameLen, value, Ffm.NULL) != Ffm.ERROR_NONE) { + return null; + } + destroyValue(value.get(ADDRESS, 0)); + return Ffm.toBytes(name.get(ADDRESS, 0), nameLen.get(JAVA_LONG, 0)); + } + } + + private static long typeParamCount(MemorySegment type) { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outLong(a); + if (Capi.duckdb_v2_logical_type_get_param_count(type, out, Ffm.NULL) != Ffm.ERROR_NONE) { + return 0; + } + return out.get(JAVA_LONG, 0); + } + } + + private static long decimalParam(MemorySegment type, long index) { + MemorySegment value = typeParam(type, index); + if (value.address() == 0) { + return 0; + } + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outInt(a); + if (Capi.duckdb_v2_value_get_uint(value, out, Ffm.NULL) != Ffm.ERROR_NONE) { + return 0; + } + return Integer.toUnsignedLong(out.get(JAVA_INT, 0)); + } finally { + destroyValue(value); + } + } + + private static MemorySegment typeValue(MemorySegment factory, MemorySegment type) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_create_type(factory, type, out, err), err); + return out.get(ADDRESS, 0); + } + } + + /** Creates the type with the parameters, the values are destroyed. Returns null on failure. */ + private static ByteBuffer createType(MemorySegment factory, int v2Id, byte[][] names, MemorySegment[] values) { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + int count = values.length; + MemorySegment namePtrs = a.allocate(Math.max(1, count) * 8L, 8); + MemorySegment nameLens = a.allocate(Math.max(1, count) * 8L, 8); + MemorySegment valuePtrs = a.allocate(Math.max(1, count) * 8L, 8); + for (int i = 0; i < count; i++) { + byte[] name = names != null && i < names.length ? names[i] : null; + namePtrs.setAtIndex(ADDRESS, i, Ffm.bytes(a, name)); + nameLens.setAtIndex(JAVA_LONG, i, Ffm.len(name)); + valuePtrs.setAtIndex(ADDRESS, i, values[i]); + } + int state = Capi.duckdb_v2_factory_create_type_from_id( + factory, v2Id, count == 0 ? Ffm.NULL : namePtrs, count == 0 ? Ffm.NULL : nameLens, + count == 0 ? Ffm.NULL : valuePtrs, count, out, Ffm.NULL); + if (state != Ffm.ERROR_NONE) { + return null; + } + return Ffm.handle(out.get(ADDRESS, 0)); + } finally { + for (MemorySegment value : values) { + destroyValue(value); + } + } + } + + // --------------------------------------------------------------------------------------------------------- + // The bindings + // --------------------------------------------------------------------------------------------------------- + + static ByteBuffer duckdb_create_logical_type(int type) throws SQLException { + int id = fromCapi(type); + if (id < 0) { + return INVALID; + } + switch (id) { + case V_DECIMAL: + case V_ENUM: + case V_LIST: + case V_STRUCT: + case V_MAP: + case V_ARRAY: + case V_UNION: + return INVALID; + default: + break; + } + MemorySegment factory = Ffm.ptr(defaultFactory()); + String name = null; + if (id == V_VARIANT) { + name = "VARIANT"; + } else if (id == V_GEOMETRY) { + name = "GEOMETRY"; + } else if (id == V_GEOGRAPHY) { + name = "GEOGRAPHY"; + } + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + int state; + if (name != null) { + byte[] text = name.getBytes(java.nio.charset.StandardCharsets.UTF_8); + state = Capi.duckdb_v2_factory_create_type_from_text(factory, Ffm.bytes(a, text), text.length, out, + Ffm.NULL); + } else { + state = Capi.duckdb_v2_factory_create_type_from_id(factory, id, Ffm.NULL, Ffm.NULL, Ffm.NULL, 0, out, + Ffm.NULL); + } + if (state != Ffm.ERROR_NONE) { + return INVALID; + } + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_create_decimal_type(int width, int scale) throws SQLException { + if (width < 1 || width > 38) { + throw new SQLException("Invalid decimal width: expected 1..38"); + } + if (scale < 0 || scale > width) { + throw new SQLException("Invalid decimal scale: expected 0..width"); + } + MemorySegment factory = Ffm.ptr(defaultFactory()); + MemorySegment[] values = new MemorySegment[2]; + try (Arena a = Arena.ofConfined()) { + for (int i = 0; i < 2; i++) { + MemorySegment out = Ffm.outPtr(a); + Capi.duckdb_v2_value_create_utinyint(factory, (byte) (i == 0 ? width : scale), out, Ffm.NULL); + values[i] = out.get(ADDRESS, 0); + } + } + return createType(factory, V_DECIMAL, null, values); + } + + static int duckdb_get_type_id(ByteBuffer type) throws SQLException { + MemorySegment ptr = Ffm.ptrNonNull(type, "logical type"); + if (isInvalid(type)) { + return T_INVALID; + } + return typeId(ptr); + } + + static int duckdb_decimal_width(ByteBuffer type) throws SQLException { + MemorySegment ptr = typePtr(type); + if (typeId(ptr) != T_DECIMAL) { + return 0; + } + long width = decimalParam(ptr, 0); + return width > 255 ? 0 : (int) width; + } + + static int duckdb_decimal_scale(ByteBuffer type) throws SQLException { + MemorySegment ptr = typePtr(type); + if (typeId(ptr) != T_DECIMAL) { + return 0; + } + if (decimalParam(ptr, 0) > 255) { + return 0; + } + long scale = decimalParam(ptr, 1); + return scale > 255 ? 0 : (int) scale; + } + + static int duckdb_decimal_internal_type(ByteBuffer type) throws SQLException { + MemorySegment ptr = typePtr(type); + if (typeId(ptr) != T_DECIMAL) { + return T_INVALID; + } + long width = decimalParam(ptr, 0); + if (width == 0) { + return T_INVALID; + } else if (width <= 4) { + return T_SMALLINT; + } else if (width <= 9) { + return T_INTEGER; + } else if (width <= 18) { + return T_BIGINT; + } else if (width <= 38) { + return T_HUGEINT; + } + return T_BIGNUM; + } + + static ByteBuffer duckdb_create_list_type(ByteBuffer type) throws SQLException { + Ffm.ptrNonNull(type, "logical type"); + if (isInvalid(type)) { + return null; + } + MemorySegment factory = Ffm.ptr(defaultFactory()); + return createType(factory, V_LIST, null, new MemorySegment[] {typeValue(factory, typePtr(type))}); + } + + static ByteBuffer duckdb_create_array_type(ByteBuffer type, long arraySize) throws SQLException { + Ffm.ptrNonNull(type, "logical type"); + if (arraySize < 0) { + throw new SQLException("Invalid array size"); + } + if (isInvalid(type)) { + return null; + } + MemorySegment factory = Ffm.ptr(defaultFactory()); + MemorySegment typeValue = typeValue(factory, typePtr(type)); + MemorySegment size; + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + Capi.duckdb_v2_value_create_ubigint(factory, arraySize, out, Ffm.NULL); + size = out.get(ADDRESS, 0); + } + return createType(factory, V_ARRAY, null, new MemorySegment[] {typeValue, size}); + } + + static ByteBuffer duckdb_create_struct_type(ByteBuffer[] memberTypes, byte[][] memberNames) throws SQLException { + if (memberTypes == null) { + throw new SQLException("Invalid member types array"); + } + if (memberNames == null) { + throw new SQLException("Invalid member names array"); + } + if (memberTypes.length != memberNames.length) { + throw new SQLException("Invalid member names array size"); + } + for (ByteBuffer type : memberTypes) { + if (type == null) { + throw new SQLException("Invalid null type specified"); + } + } + for (byte[] name : memberNames) { + if (name == null) { + throw new SQLException("Invalid null name specified"); + } + } + MemorySegment factory = Ffm.ptr(defaultFactory()); + boolean unnamed = true; + MemorySegment[] values = new MemorySegment[memberTypes.length]; + for (int i = 0; i < memberTypes.length; i++) { + if (isInvalid(memberTypes[i])) { + for (int j = 0; j < i; j++) { + destroyValue(values[j]); + } + return null; + } + if (memberNames[i].length > 0) { + unnamed = false; + } + values[i] = typeValue(factory, typePtr(memberTypes[i])); + } + int id = unnamed && memberTypes.length > 0 ? V_TUPLE : V_STRUCT; + return createType(factory, id, memberNames, values); + } + + private static long structChildCount(MemorySegment type) { + switch (typeId(type)) { + case T_STRUCT: + return typeParamCount(type); + case T_UNION: + return typeParamCount(type) + 1; + default: + return 0; + } + } + + static long duckdb_struct_type_child_count(ByteBuffer type) throws SQLException { + return structChildCount(typePtr(type)); + } + + static byte[] duckdb_struct_type_child_name(ByteBuffer type, long index) throws SQLException { + MemorySegment ptr = typePtr(type); + if (index < 0 || index >= structChildCount(ptr)) { + throw new SQLException("Invalid struct field index specified"); + } + if (typeId(ptr) == T_UNION) { + // the hidden "tag" field of a UNION has an empty name + return index == 0 ? new byte[0] : typeParamName(ptr, index - 1); + } + return typeParamName(ptr, index); + } + + static long duckdb_array_type_array_size(ByteBuffer type) throws SQLException { + MemorySegment ptr = typePtr(type); + if (typeId(ptr) != T_ARRAY) { + return 0; + } + MemorySegment value = typeParam(ptr, 1); + if (value.address() == 0) { + return 0; + } + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outLong(a); + if (Capi.duckdb_v2_value_get_ubigint(value, out, Ffm.NULL) != Ffm.ERROR_NONE) { + return 0; + } + return out.get(JAVA_LONG, 0); + } finally { + destroyValue(value); + } + } + + static void duckdb_destroy_logical_type(ByteBuffer type) throws SQLException { + Ffm.ptrNonNull(type, "logical type"); + if (isInvalid(type)) { + return; + } + try (Arena a = Arena.ofConfined()) { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, Ffm.ptr(type)); + Capi.duckdb_v2_logical_type_destroy(holder); + } + } + + static int duckdb_enum_internal_type(ByteBuffer type) throws SQLException { + MemorySegment ptr = typePtr(type); + if (typeId(ptr) != T_ENUM) { + return T_INVALID; + } + long size = typeParamCount(ptr); + if (size <= 255) { + return T_UTINYINT; + } else if (size <= 65535) { + return T_USMALLINT; + } + return T_UINTEGER; + } + + static long duckdb_enum_dictionary_size(ByteBuffer type) throws SQLException { + MemorySegment ptr = typePtr(type); + return typeId(ptr) == T_ENUM ? typeParamCount(ptr) : 0; + } + + static byte[] duckdb_enum_dictionary_value(ByteBuffer type, long index) throws SQLException { + MemorySegment ptr = typePtr(type); + if (typeId(ptr) != T_ENUM) { + return null; + } + if (index < 0 || index >= typeParamCount(ptr)) { + throw new SQLException("Invalid enum field index specified"); + } + MemorySegment value = typeParam(ptr, index); + if (value.address() == 0) { + return null; + } + try (Arena a = Arena.ofConfined()) { + MemorySegment str = Ffm.outPtr(a); + MemorySegment len = Ffm.outLong(a); + if (Capi.duckdb_v2_value_get_varchar(value, str, len, Ffm.NULL) != Ffm.ERROR_NONE) { + return null; + } + return Ffm.toBytes(str.get(ADDRESS, 0), len.get(JAVA_LONG, 0)); + } finally { + destroyValue(value); + } + } +} diff --git a/src/main/java22/org/duckdb/FfmV2.java b/src/main/java22/org/duckdb/FfmV2.java new file mode 100644 index 000000000..f41dfec88 --- /dev/null +++ b/src/main/java22/org/duckdb/FfmV2.java @@ -0,0 +1,1233 @@ +package org.duckdb; + +import static java.lang.foreign.ValueLayout.ADDRESS; +import static java.lang.foreign.ValueLayout.JAVA_BOOLEAN; +import static java.lang.foreign.ValueLayout.JAVA_BYTE; +import static java.lang.foreign.ValueLayout.JAVA_DOUBLE; +import static java.lang.foreign.ValueLayout.JAVA_INT; +import static java.lang.foreign.ValueLayout.JAVA_LONG; + +import java.lang.foreign.Arena; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.MemorySegment; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; + +/** The bindings that map one to one to the calls of the C API v2. */ +final class FfmV2 { + private FfmV2() { + } + + private static MemorySegment p(ByteBuffer handle, String what) throws SQLException { + return Ffm.ptrNonNull(handle, what); + } + + /** The pointers of the handles, as an array in the native memory. */ + private static MemorySegment ptrs(Arena arena, ByteBuffer[] handles) throws SQLException { + int count = handles == null ? 0 : handles.length; + MemorySegment res = arena.allocate(Math.max(1, count) * 8L, 8); + for (int i = 0; i < count; i++) { + res.setAtIndex(ADDRESS, i, p(handles[i], "handle")); + } + return res; + } + + // --------------------------------------------------------------------------------------------------------- + // Connections + // --------------------------------------------------------------------------------------------------------- + + static void duckdb_v2_connection_interrupt(ByteBuffer conn) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_connection_interrupt(p(conn, "connection"), err), err); + } + } + + static QueryProgress duckdb_v2_connection_progress_get(ByteBuffer conn) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + MemorySegment percentage = a.allocate(JAVA_DOUBLE); + percentage.set(JAVA_DOUBLE, 0, -1); + MemorySegment rows = Ffm.outLong(a); + MemorySegment total = Ffm.outLong(a); + Ffm.check(Capi.duckdb_v2_connection_progress_get(p(conn, "connection"), percentage, rows, total, err), err); + return new QueryProgress(percentage.get(JAVA_DOUBLE, 0), rows.get(JAVA_LONG, 0), total.get(JAVA_LONG, 0)); + } + } + + static ByteBuffer duckdb_v2_connection_create(ByteBuffer instance) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_connection_create(p(instance, "instance"), out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static void duckdb_v2_connection_destroy(ByteBuffer conn) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, p(conn, "connection")); + Capi.duckdb_v2_connection_destroy(holder); + } + } + + static ByteBuffer duckdb_v2_connection_get_factory(ByteBuffer conn) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_connection_get_factory(p(conn, "connection"), out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_connection_get_config(ByteBuffer conn) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_connection_get_config(p(conn, "connection"), out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + // --------------------------------------------------------------------------------------------------------- + // Parsing and statements + // --------------------------------------------------------------------------------------------------------- + + static ByteBuffer duckdb_v2_parse_sql(ByteBuffer conn, byte[] sql) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_parse_sql(p(conn, "connection"), Ffm.bytes(a, sql), Ffm.len(sql), false, out, err), + err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_statement_iterator_next(ByteBuffer iterator) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_statement_iterator_next(p(iterator, "statement iterator"), out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static void duckdb_v2_statement_iterator_destroy(ByteBuffer iterator) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, p(iterator, "statement iterator")); + Capi.duckdb_v2_statement_iterator_destroy(holder); + } + } + + static void duckdb_v2_sql_statement_destroy(ByteBuffer statement) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, p(statement, "statement")); + Capi.duckdb_v2_sql_statement_destroy(holder); + } + } + + static int duckdb_v2_sql_statement_get_type(ByteBuffer statement) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outInt(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_sql_statement_get_type(p(statement, "statement"), out, err), err); + return out.get(JAVA_INT, 0); + } + } + + static long duckdb_v2_sql_statement_get_parameter_count(ByteBuffer statement) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outLong(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_sql_statement_get_parameter_count(p(statement, "statement"), out, err), err); + return out.get(JAVA_LONG, 0); + } + } + + static ByteBuffer duckdb_v2_prepared_statement_create(ByteBuffer conn, ByteBuffer statement, + boolean requireCacheable) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_prepared_statement_create(p(conn, "connection"), p(statement, "statement"), + requireCacheable, out, err), + err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static void duckdb_v2_prepared_statement_destroy(ByteBuffer prepared) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, p(prepared, "prepared statement")); + Capi.duckdb_v2_prepared_statement_destroy(holder); + } + } + + static ByteBuffer duckdb_v2_prepared_statement_execute(ByteBuffer prepared, ByteBuffer[] values) + throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + int count = values == null ? 0 : values.length; + Ffm.check(Capi.duckdb_v2_prepared_statement_execute(p(prepared, "prepared statement"), Ffm.NULL, Ffm.NULL, + ptrs(a, values), count, out, err), + err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_statement_execute(ByteBuffer conn, ByteBuffer statement, ByteBuffer[] values) + throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + int count = values == null ? 0 : values.length; + Ffm.check(Capi.duckdb_v2_statement_execute(p(conn, "connection"), p(statement, "statement"), Ffm.NULL, + Ffm.NULL, ptrs(a, values), count, out, err), + err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer[] duckdb_v2_statement_bind(ByteBuffer conn, ByteBuffer statement) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment output = Ffm.outPtr(a); + MemorySegment parameters = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_statement_bind(p(conn, "connection"), p(statement, "statement"), output, + parameters, err), + err); + return new ByteBuffer[] {Ffm.handle(output.get(ADDRESS, 0)), Ffm.handle(parameters.get(ADDRESS, 0))}; + } + } + + // --------------------------------------------------------------------------------------------------------- + // Schemas and results + // --------------------------------------------------------------------------------------------------------- + + static void duckdb_v2_schema_destroy(ByteBuffer schema) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, p(schema, "schema")); + Capi.duckdb_v2_schema_destroy(holder); + } + } + + static long duckdb_v2_schema_get_count(ByteBuffer schema) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outLong(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_schema_get_count(p(schema, "schema"), out, err), err); + return out.get(JAVA_LONG, 0); + } + } + + private static MemorySegment[] schemaField(Arena a, ByteBuffer schema, long index) throws SQLException { + MemorySegment name = Ffm.outPtr(a); + MemorySegment nameLen = Ffm.outLong(a); + MemorySegment type = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_schema_get_field(p(schema, "schema"), index, name, nameLen, type, err), err); + return new MemorySegment[] {name, nameLen, type}; + } + + static byte[] duckdb_v2_schema_get_field_name(ByteBuffer schema, long index) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment[] f = schemaField(a, schema, index); + return Ffm.toBytes(f[0].get(ADDRESS, 0), f[1].get(JAVA_LONG, 0)); + } + } + + // the returned type is borrowed from the schema + static ByteBuffer duckdb_v2_schema_get_field_type(ByteBuffer schema, long index) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment[] f = schemaField(a, schema, index); + return Ffm.handle(f[2].get(ADDRESS, 0)); + } + } + + static byte[][] duckdb_v2_schema_get_field_names(ByteBuffer schema) throws SQLException { + long count = duckdb_v2_schema_get_count(schema); + byte[][] res = new byte[(int) count][]; + try (Arena a = Arena.ofConfined()) { + for (int i = 0; i < count; i++) { + MemorySegment[] f = schemaField(a, schema, i); + res[i] = Ffm.toBytes(f[0].get(ADDRESS, 0), f[1].get(JAVA_LONG, 0)); + } + } + return res; + } + + static int[] duckdb_v2_schema_get_field_type_ids(ByteBuffer schema) throws SQLException { + long count = duckdb_v2_schema_get_count(schema); + int[] res = new int[(int) count]; + try (Arena a = Arena.ofConfined()) { + for (int i = 0; i < count; i++) { + MemorySegment[] f = schemaField(a, schema, i); + res[i] = FfmTypes.typeId(f[2].get(ADDRESS, 0)); + } + } + return res; + } + + static void duckdb_v2_result_destroy(ByteBuffer result) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, p(result, "result")); + Capi.duckdb_v2_result_destroy(holder); + } + } + + static ByteBuffer duckdb_v2_result_get_schema(ByteBuffer result) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_result_get_schema(p(result, "result"), out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static int duckdb_v2_result_get_result_type(ByteBuffer result) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outInt(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_result_get_result_type(p(result, "result"), out, err), err); + return out.get(JAVA_INT, 0); + } + } + + static int duckdb_v2_result_get_statement_type(ByteBuffer result) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outInt(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_result_get_statement_type(p(result, "result"), out, err), err); + return out.get(JAVA_INT, 0); + } + } + + static void duckdb_v2_result_wait(ByteBuffer result) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_result_wait(p(result, "result"), err), err); + } + } + + static long duckdb_v2_result_drain(ByteBuffer result) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outLong(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_result_drain(p(result, "result"), out, err), err); + return out.get(JAVA_LONG, 0); + } + } + + static ByteBuffer duckdb_v2_result_step(ByteBuffer result, int[] statusOut) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment chunk = Ffm.outPtr(a); + MemorySegment status = Ffm.outInt(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_result_step(p(result, "result"), chunk, status, err), err); + statusOut[0] = status.get(JAVA_INT, 0); + return Ffm.handle(chunk.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_result_fetch_chunk(ByteBuffer result) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_result_fetch_chunk(p(result, "result"), out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + // --------------------------------------------------------------------------------------------------------- + // Values + // --------------------------------------------------------------------------------------------------------- + + static void duckdb_v2_value_destroy(ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, p(value, "value")); + Capi.duckdb_v2_value_destroy(holder); + } + } + + static ByteBuffer duckdb_v2_value_create_null(ByteBuffer factory, ByteBuffer type) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_create_null(p(factory, "factory"), FfmTypes.typePtr(type), out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_value_create_bool(ByteBuffer factory, boolean value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_create_bool(p(factory, "factory"), value, out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_value_create_tinyint(ByteBuffer factory, byte value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_create_tinyint(p(factory, "factory"), value, out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_value_create_smallint(ByteBuffer factory, short value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_create_smallint(p(factory, "factory"), value, out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_value_create_int(ByteBuffer factory, int value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_create_int(p(factory, "factory"), value, out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_value_create_bigint(ByteBuffer factory, long value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_create_bigint(p(factory, "factory"), value, out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_value_create_float(ByteBuffer factory, float value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_create_float(p(factory, "factory"), value, out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_value_create_double(ByteBuffer factory, double value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_create_double(p(factory, "factory"), value, out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_value_create_date(ByteBuffer factory, int days) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_create_date(p(factory, "factory"), days, out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_value_create_time(ByteBuffer factory, long micros) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_create_time(p(factory, "factory"), micros, out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_value_create_timestamp(ByteBuffer factory, long micros) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_create_timestamp(p(factory, "factory"), micros, out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_value_create_timestamp_ns(ByteBuffer factory, long nanos) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_create_timestamp_ns(p(factory, "factory"), nanos, out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_value_create_timestamp_tz(ByteBuffer factory, long micros) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_create_timestamp_tz(p(factory, "factory"), micros, out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + private static MemorySegment hugeint(Arena a, long lower, long upper) { + MemorySegment res = a.allocate(16, 8); + res.set(JAVA_LONG, 0, lower); + res.set(JAVA_LONG, 8, upper); + return res; + } + + static ByteBuffer duckdb_v2_value_create_hugeint(ByteBuffer factory, long lower, long upper) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_create_hugeint(p(factory, "factory"), hugeint(a, lower, upper), out, err), + err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_value_create_uuid(ByteBuffer factory, long lower, long upper) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_create_uuid(p(factory, "factory"), hugeint(a, lower, upper), out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_value_create_decimal(ByteBuffer factory, long lower, long upper, int width, int scale) + throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_create_decimal(p(factory, "factory"), hugeint(a, lower, upper), width, scale, + out, err), + err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_value_create_varchar(ByteBuffer factory, byte[] value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_create_varchar(p(factory, "factory"), Ffm.bytes(a, value), Ffm.len(value), + out, err), + err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_value_create_blob(ByteBuffer factory, byte[] value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check( + Capi.duckdb_v2_value_create_blob(p(factory, "factory"), Ffm.bytes(a, value), Ffm.len(value), out, err), + err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_value_create_list(ByteBuffer factory, ByteBuffer childType, ByteBuffer[] children) + throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_create_list(p(factory, "factory"), FfmTypes.typePtr(childType), + ptrs(a, children), children.length, out, err), + err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_value_create_struct(ByteBuffer factory, byte[][] names, ByteBuffer[] children) + throws SQLException { + if (names.length != children.length) { + throw new SQLException("Struct names and values count mismatch"); + } + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + MemorySegment namePtrs = a.allocate(Math.max(1, names.length) * 8L, 8); + MemorySegment nameLens = a.allocate(Math.max(1, names.length) * 8L, 8); + for (int i = 0; i < names.length; i++) { + namePtrs.setAtIndex(ADDRESS, i, Ffm.bytes(a, names[i])); + nameLens.setAtIndex(JAVA_LONG, i, Ffm.len(names[i])); + } + Ffm.check(Capi.duckdb_v2_value_create_struct(p(factory, "factory"), namePtrs, nameLens, ptrs(a, children), + children.length, out, err), + err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_value_create_map(ByteBuffer factory, ByteBuffer keyType, ByteBuffer valueType, + ByteBuffer[] keys, ByteBuffer[] values) throws SQLException { + if (keys.length != values.length) { + throw new SQLException("Map keys and values count mismatch"); + } + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_create_map(p(factory, "factory"), FfmTypes.typePtr(keyType), + FfmTypes.typePtr(valueType), ptrs(a, keys), ptrs(a, values), + keys.length, out, err), + err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_value_create_type(ByteBuffer factory, ByteBuffer type) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_create_type(p(factory, "factory"), FfmTypes.typePtr(type), out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static byte[] duckdb_v2_value_to_string(ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment len = Ffm.outLong(a); + MemorySegment err = Ffm.outPtr(a); + MemorySegment v = p(value, "value"); + Ffm.check(Capi.duckdb_v2_value_to_string(v, Ffm.NULL, 0, len, err), err); + long length = len.get(JAVA_LONG, 0); + MemorySegment text = a.allocate(length + 1); + Ffm.check(Capi.duckdb_v2_value_to_string(v, text, length + 1, len, err), err); + return Ffm.toBytes(text, len.get(JAVA_LONG, 0)); + } + } + + static ByteBuffer duckdb_v2_value_variant_to_value(ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_variant_to_value(p(value, "value"), out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_value_get_logical_type(ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_get_logical_type(p(value, "value"), out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_value_get_type(ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_get_type(p(value, "value"), out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + // --------------------------------------------------------------------------------------------------------- + // Types + // --------------------------------------------------------------------------------------------------------- + + static ByteBuffer duckdb_v2_factory_create_type_from_text(ByteBuffer factory, byte[] text) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_factory_create_type_from_text(p(factory, "factory"), Ffm.bytes(a, text), + Ffm.len(text), out, err), + err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static long duckdb_v2_logical_type_get_param_count(ByteBuffer type) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outLong(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_logical_type_get_param_count(FfmTypes.typePtr(type), out, err), err); + return out.get(JAVA_LONG, 0); + } + } + + static ByteBuffer duckdb_v2_logical_type_get_param_value(ByteBuffer type, long index) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment name = Ffm.outPtr(a); + MemorySegment nameLen = Ffm.outLong(a); + MemorySegment value = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_logical_type_get_param(FfmTypes.typePtr(type), index, name, nameLen, value, err), + err); + return Ffm.handle(value.get(ADDRESS, 0)); + } + } + + static byte[] duckdb_v2_logical_type_get_param_name(ByteBuffer type, long index) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment name = Ffm.outPtr(a); + MemorySegment nameLen = Ffm.outLong(a); + MemorySegment value = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_logical_type_get_param(FfmTypes.typePtr(type), index, name, nameLen, value, err), + err); + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, value.get(ADDRESS, 0)); + Capi.duckdb_v2_value_destroy(holder); + long len = nameLen.get(JAVA_LONG, 0); + if (name.get(ADDRESS, 0).address() == 0 || len == 0) { + return null; + } + return Ffm.toBytes(name.get(ADDRESS, 0), len); + } + } + + static ByteBuffer duckdb_v2_logical_type_copy(ByteBuffer type) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_logical_type_copy(FfmTypes.typePtr(type), out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + // --------------------------------------------------------------------------------------------------------- + // Vectors + // --------------------------------------------------------------------------------------------------------- + + static void duckdb_v2_vector_flatten(ByteBuffer vector) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_vector_flatten(p(vector, "vector"), err), err); + } + } + + static ByteBuffer duckdb_v2_vector_get_value(ByteBuffer vector, long row) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_vector_get_value(p(vector, "vector"), row, out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static void duckdb_v2_vector_set_value(ByteBuffer vector, long row, ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_vector_set_value(p(vector, "vector"), row, p(value, "value"), err), err); + } + } + + static void duckdb_v2_vector_set_size(ByteBuffer vector, long size) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_vector_set_size(p(vector, "vector"), size, err), err); + } + } + + static long duckdb_v2_vector_get_size(ByteBuffer vector) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outLong(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_vector_get_size(p(vector, "vector"), out, err), err); + return out.get(JAVA_LONG, 0); + } + } + + static void duckdb_v2_vector_cast(ByteBuffer factory, ByteBuffer source, ByteBuffer target) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment converted = a.allocate(JAVA_BOOLEAN); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_vector_cast(p(factory, "factory"), p(source, "vector"), p(target, "vector"), 0, + converted, Ffm.NULL, err), + err); + } + } + + /** + * The strings (BLOBs) of the rows of the vector data that do not fit into the 16 bytes of the entry: the length + * is followed by a prefix and the pointer to the bytes. + */ + static byte[] duckdb_v2_vector_get_long_strings(ByteBuffer data, int[] rows, int count, int[] offsetsOut) + throws SQLException { + MemorySegment base = MemorySegment.ofBuffer(data); + long total = 0; + for (int i = 0; i < count; i++) { + offsetsOut[i] = (int) total; + total += Integer.toUnsignedLong(base.get(JAVA_INT, (long) rows[i] * 16)); + if (total > Integer.MAX_VALUE) { + throw new SQLException("The strings of the vector are too large"); + } + } + offsetsOut[count] = (int) total; + byte[] res = new byte[(int) total]; + for (int i = 0; i < count; i++) { + long entry = (long) rows[i] * 16; + int len = base.get(JAVA_INT, entry); + MemorySegment bytes = MemorySegment.ofAddress(base.get(JAVA_LONG, entry + 8)).reinterpret(len); + MemorySegment.copy(bytes, JAVA_BYTE, 0, res, offsetsOut[i], len); + } + return res; + } + + // --------------------------------------------------------------------------------------------------------- + // Column data collections and appending + // --------------------------------------------------------------------------------------------------------- + + static ByteBuffer duckdb_v2_column_data_collection_create(ByteBuffer factory, ByteBuffer[] types) + throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + MemorySegment typePtrs = a.allocate(Math.max(1, types.length) * 8L, 8); + for (int i = 0; i < types.length; i++) { + typePtrs.setAtIndex(ADDRESS, i, FfmTypes.typePtr(types[i])); + } + Ffm.check( + Capi.duckdb_v2_column_data_collection_create(p(factory, "factory"), typePtrs, types.length, out, err), + err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static void duckdb_v2_column_data_collection_destroy(ByteBuffer collection) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, p(collection, "collection")); + Capi.duckdb_v2_column_data_collection_destroy(holder); + } + } + + static void duckdb_v2_column_data_collection_clear(ByteBuffer collection) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_column_data_collection_clear(p(collection, "collection"), err), err); + } + } + + static long duckdb_v2_column_data_collection_row_count(ByteBuffer collection) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outLong(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_column_data_collection_row_count(p(collection, "collection"), out, err), err); + return out.get(JAVA_LONG, 0); + } + } + + static ByteBuffer duckdb_v2_column_data_collection_append_state_create(ByteBuffer collection) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_column_data_collection_append_state_create(p(collection, "collection"), out, err), + err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static void duckdb_v2_column_data_collection_append_state_destroy(ByteBuffer state) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, p(state, "append state")); + Capi.duckdb_v2_column_data_collection_append_state_destroy(holder); + } + } + + static void duckdb_v2_column_data_collection_append(ByteBuffer collection, ByteBuffer state, ByteBuffer chunk) + throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_column_data_collection_append(p(collection, "collection"), + p(state, "append state"), p(chunk, "chunk"), err), + err); + } + } + + static void duckdb_v2_statement_add_collection(ByteBuffer statement, byte[] name, ByteBuffer collection, + byte[][] columnNames) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + MemorySegment namePtrs = a.allocate(Math.max(1, columnNames.length) * 8L, 8); + MemorySegment nameLens = a.allocate(Math.max(1, columnNames.length) * 8L, 8); + for (int i = 0; i < columnNames.length; i++) { + namePtrs.setAtIndex(ADDRESS, i, Ffm.bytes(a, columnNames[i])); + nameLens.setAtIndex(JAVA_LONG, i, Ffm.len(columnNames[i])); + } + Ffm.check(Capi.duckdb_v2_statement_add_collection(p(statement, "statement"), Ffm.bytes(a, name), + Ffm.len(name), p(collection, "collection"), namePtrs, + nameLens, columnNames.length, err), + err); + } + } + + // --------------------------------------------------------------------------------------------------------- + // Environments, instances and configuration + // --------------------------------------------------------------------------------------------------------- + + static ByteBuffer duckdb_v2_environment_create() throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_environment_create(out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static void duckdb_v2_environment_destroy(ByteBuffer environment) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, p(environment, "environment")); + Capi.duckdb_v2_environment_destroy(holder); + } + } + + private static MemorySegment byteArrays(Arena a, byte[][] arrays) { + MemorySegment res = a.allocate(Math.max(1, arrays.length) * 8L, 8); + for (int i = 0; i < arrays.length; i++) { + res.setAtIndex(ADDRESS, i, Ffm.bytes(a, arrays[i])); + } + return res; + } + + private static MemorySegment lengths(Arena a, byte[][] arrays) { + MemorySegment res = a.allocate(Math.max(1, arrays.length) * 8L, 8); + for (int i = 0; i < arrays.length; i++) { + res.setAtIndex(JAVA_LONG, i, Ffm.len(arrays[i])); + } + return res; + } + + static ByteBuffer duckdb_v2_instance_create_with_options(ByteBuffer environment, byte[][] names, byte[][] values) + throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_instance_create_with_options(p(environment, "environment"), byteArrays(a, names), + lengths(a, names), byteArrays(a, values), + lengths(a, values), names.length, out, err), + err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + /** The initializer of the instance that is being opened by the current thread. */ + private static final ThreadLocal INSTANCE_INIT = new ThreadLocal<>(); + + private static final MemorySegment INSTANCE_INIT_STUB = initStub(); + + private static MemorySegment initStub() { + try { + MethodHandle target = MethodHandles.lookup().findStatic( + FfmV2.class, "instanceInit", + MethodType.methodType(void.class, MemorySegment.class, MemorySegment.class, MemorySegment.class)); + return Ffm.LINKER.upcallStub(target, FunctionDescriptor.ofVoid(ADDRESS, ADDRESS, ADDRESS), Arena.global()); + } catch (ReflectiveOperationException e) { + throw new ExceptionInInitializerError(e); + } + } + + // The callback of the C API: the instance is borrowed, err is a slot of the error info that is set on failure + @SuppressWarnings("unused") + private static void instanceInit(MemorySegment instance, MemorySegment userData, MemorySegment err) { + DuckDBBindings.InstanceInit init = INSTANCE_INIT.get(); + try { + init.init(Ffm.handle(instance)); + } catch (Throwable t) { + // the message of the error is without the type, the type is DATABASE_CATALOG + FfmFunctions.setCallbackError(err, 6001, String.valueOf(t.getMessage())); + } + } + + static ByteBuffer duckdb_v2_instance_open_shared(ByteBuffer environment, byte[] path, byte[][] names, + byte[][] values, DuckDBBindings.InstanceInit init) + throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + INSTANCE_INIT.set(init); + try { + Ffm.check(Capi.duckdb_v2_instance_open_shared( + p(environment, "environment"), Ffm.bytes(a, path), Ffm.len(path), byteArrays(a, names), + lengths(a, names), byteArrays(a, values), lengths(a, values), names.length, + init == null ? Ffm.NULL : INSTANCE_INIT_STUB, Ffm.NULL, out, err), + err); + } finally { + INSTANCE_INIT.remove(); + } + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static void duckdb_v2_instance_attach(ByteBuffer instance, byte[] name, byte[] path, boolean makeDefault) + throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_instance_attach(p(instance, "instance"), + name == null ? Ffm.NULL : Ffm.bytes(a, name), Ffm.len(name), + Ffm.bytes(a, path), Ffm.len(path), Ffm.NULL, makeDefault, err), + err); + } + } + + static void duckdb_v2_instance_destroy(ByteBuffer instance) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, p(instance, "instance")); + Capi.duckdb_v2_instance_destroy(holder); + } + } + + static ByteBuffer duckdb_v2_instance_get_config(ByteBuffer instance) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_instance_get_config(p(instance, "instance"), out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static void duckdb_v2_config_set_option_text(ByteBuffer config, byte[] name, byte[] value, int scope) + throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_config_set_option_text(p(config, "config"), Ffm.bytes(a, name), Ffm.len(name), + Ffm.bytes(a, value), Ffm.len(value), scope, err), + err); + } + } + + static void duckdb_v2_config_set_option_value(ByteBuffer config, byte[] name, ByteBuffer value, int scope) + throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_config_set_option_value(p(config, "config"), Ffm.bytes(a, name), Ffm.len(name), + p(value, "value"), scope, err), + err); + } + } + + static long duckdb_v2_config_get_option_count(ByteBuffer config) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outLong(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_config_get_option_count(p(config, "config"), out, err), err); + return out.get(JAVA_LONG, 0); + } + } + + static ByteBuffer duckdb_v2_config_get_option_by_index(ByteBuffer config, long index) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_config_get_option_by_index(p(config, "config"), index, out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static byte[] duckdb_v2_option_get_name(ByteBuffer option) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment name = Ffm.outPtr(a); + MemorySegment len = Ffm.outLong(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_option_get_name(p(option, "option"), name, len, err), err); + return Ffm.toBytes(name.get(ADDRESS, 0), len.get(JAVA_LONG, 0)); + } + } + + static boolean duckdb_v2_option_supports_scope(ByteBuffer option, int scope) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = a.allocate(JAVA_BOOLEAN); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_option_supports_scope(p(option, "option"), scope, out, err), err); + return out.get(JAVA_BOOLEAN, 0); + } + } + + static void duckdb_v2_option_destroy(ByteBuffer option) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, p(option, "option")); + Capi.duckdb_v2_option_destroy(holder); + } + } + + static ByteBuffer duckdb_v2_config_get_option_value_scoped(ByteBuffer config, byte[] name, int[] scopeOut) + throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment scope = Ffm.outInt(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_config_get_option_value(p(config, "config"), Ffm.bytes(a, name), Ffm.len(name), + out, scope, err), + err); + if (scopeOut != null) { + scopeOut[0] = scope.get(JAVA_INT, 0); + } + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static ByteBuffer duckdb_v2_config_get_option_value(ByteBuffer config, byte[] name) throws SQLException { + return duckdb_v2_config_get_option_value_scoped(config, name, null); + } + + static int duckdb_v2_config_get_bool_option(ByteBuffer config, byte[] name) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment value = Ffm.outPtr(a); + MemorySegment scope = Ffm.outInt(a); + MemorySegment err = Ffm.outPtr(a); + int state = Capi.duckdb_v2_config_get_option_value(p(config, "config"), Ffm.bytes(a, name), Ffm.len(name), + value, scope, err); + if (state != Ffm.ERROR_NONE) { + Ffm.error(state, err); + return -1; + } + MemorySegment v = value.get(ADDRESS, 0); + try { + MemorySegment res = a.allocate(JAVA_BOOLEAN); + if (Capi.duckdb_v2_value_get_bool(v, res, Ffm.NULL) != Ffm.ERROR_NONE) { + return -1; + } + return res.get(JAVA_BOOLEAN, 0) ? 1 : 0; + } finally { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, v); + Capi.duckdb_v2_value_destroy(holder); + } + } + } + + // --------------------------------------------------------------------------------------------------------- + // Custom options + // --------------------------------------------------------------------------------------------------------- + + static ByteBuffer duckdb_v2_custom_option_create(ByteBuffer factory) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_custom_option_create(p(factory, "factory"), out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static void duckdb_v2_custom_option_destroy(ByteBuffer option) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, p(option, "custom option")); + Capi.duckdb_v2_custom_option_destroy(holder); + } + } + + static void duckdb_v2_custom_option_set_name(ByteBuffer option, byte[] name) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_custom_option_set_name(p(option, "custom option"), Ffm.bytes(a, name), + Ffm.len(name), err), + err); + } + } + + static void duckdb_v2_custom_option_set_type(ByteBuffer option, ByteBuffer type) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_custom_option_set_type(p(option, "custom option"), FfmTypes.typePtr(type), err), + err); + } + } + + static void duckdb_v2_custom_option_set_default_value(ByteBuffer option, ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + Ffm.check( + Capi.duckdb_v2_custom_option_set_default_value(p(option, "custom option"), p(value, "value"), err), + err); + } + } + + static void duckdb_v2_custom_option_set_description(ByteBuffer option, byte[] description) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_custom_option_set_description( + p(option, "custom option"), Ffm.bytes(a, description), Ffm.len(description), err), + err); + } + } + + static void duckdb_v2_custom_option_set_default_scope(ByteBuffer option, int scope) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_custom_option_set_default_scope(p(option, "custom option"), scope, err), err); + } + } + + static void duckdb_v2_custom_option_set_supports_scope(ByteBuffer option, int scope, boolean supported) + throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + Ffm.check( + Capi.duckdb_v2_custom_option_set_supports_scope(p(option, "custom option"), scope, supported, err), + err); + } + } + + static void duckdb_v2_connection_register_custom_option(ByteBuffer conn, ByteBuffer option) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_connection_register_custom_option(p(conn, "connection"), + p(option, "custom option"), err), + err); + } + } + + // --------------------------------------------------------------------------------------------------------- + // Profiling + // --------------------------------------------------------------------------------------------------------- + + private static final ThreadLocal TEXT_SINK = new ThreadLocal<>(); + + private static final MemorySegment TEXT_SINK_STUB = textSinkStub(); + + private static MemorySegment textSinkStub() { + try { + MethodHandle target = + MethodHandles.lookup().findStatic(FfmV2.class, "textSink", + MethodType.methodType(void.class, MemorySegment.class, long.class, + MemorySegment.class, MemorySegment.class)); + return Ffm.LINKER.upcallStub(target, FunctionDescriptor.ofVoid(ADDRESS, JAVA_LONG, ADDRESS, ADDRESS), + Arena.global()); + } catch (ReflectiveOperationException e) { + throw new ExceptionInInitializerError(e); + } + } + + @SuppressWarnings("unused") + private static void textSink(MemorySegment text, long length, MemorySegment userData, MemorySegment err) { + TEXT_SINK.get()[0] = Ffm.toBytes(text, length); + } + + static byte[] duckdb_v2_connection_get_profiling_information(ByteBuffer conn, byte[] format) throws SQLException { + byte[][] holder = new byte[1][]; + TEXT_SINK.set(holder); + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_connection_get_profiling_information( + p(conn, "connection"), Ffm.bytes(a, format), Ffm.len(format), TEXT_SINK_STUB, Ffm.NULL, err), + err); + } finally { + TEXT_SINK.remove(); + } + return holder[0] == null ? new byte[0] : holder[0]; + } + + static String text(byte[] bytes) { + return new String(bytes, StandardCharsets.UTF_8); + } +} diff --git a/src/main/java22/org/duckdb/FfmValues.java b/src/main/java22/org/duckdb/FfmValues.java new file mode 100644 index 000000000..d10923d8e --- /dev/null +++ b/src/main/java22/org/duckdb/FfmValues.java @@ -0,0 +1,300 @@ +package org.duckdb; + +import static java.lang.foreign.ValueLayout.ADDRESS; +import static java.lang.foreign.ValueLayout.JAVA_BOOLEAN; +import static java.lang.foreign.ValueLayout.JAVA_BYTE; +import static java.lang.foreign.ValueLayout.JAVA_DOUBLE; +import static java.lang.foreign.ValueLayout.JAVA_FLOAT; +import static java.lang.foreign.ValueLayout.JAVA_INT; +import static java.lang.foreign.ValueLayout.JAVA_LONG; +import static java.lang.foreign.ValueLayout.JAVA_SHORT; + +import java.lang.foreign.Arena; +import java.lang.foreign.MemorySegment; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.sql.SQLException; + +/** + * The bindings that read the values. A value that cannot be read as the requested type is read as a value that is + * specific to the type (the same as the C API v1 does), not as an error. + */ +final class FfmValues { + private FfmValues() { + } + + private static MemorySegment v(ByteBuffer value) throws SQLException { + return Ffm.ptrNonNull(value, "value"); + } + + static boolean duckdb_is_null_value(ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = a.allocate(JAVA_BOOLEAN); + Capi.duckdb_v2_value_is_null(v(value), out, Ffm.NULL); + return out.get(JAVA_BOOLEAN, 0); + } + } + + static int duckdb_get_value_type(ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_get_logical_type(v(value), out, err), err); + MemorySegment type = out.get(ADDRESS, 0); + try { + return FfmTypes.typeId(type); + } finally { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, type); + Capi.duckdb_v2_logical_type_destroy(holder); + } + } + } + + static void duckdb_destroy_value(ByteBuffer value) throws SQLException { + FfmV2.duckdb_v2_value_destroy(value); + } + + static boolean duckdb_get_bool(ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = a.allocate(JAVA_BOOLEAN); + return Capi.duckdb_v2_value_get_bool(v(value), out, Ffm.NULL) == Ffm.ERROR_NONE && out.get(JAVA_BOOLEAN, 0); + } + } + + static byte duckdb_get_int8(ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = a.allocate(JAVA_BYTE); + return Capi.duckdb_v2_value_get_tinyint(v(value), out, Ffm.NULL) == Ffm.ERROR_NONE ? out.get(JAVA_BYTE, 0) + : Byte.MIN_VALUE; + } + } + + static short duckdb_get_uint8(ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = a.allocate(JAVA_BYTE); + return Capi.duckdb_v2_value_get_utinyint(v(value), out, Ffm.NULL) == Ffm.ERROR_NONE + ? (short) Byte.toUnsignedInt(out.get(JAVA_BYTE, 0)) + : 0; + } + } + + static short duckdb_get_int16(ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = a.allocate(JAVA_SHORT); + return Capi.duckdb_v2_value_get_smallint(v(value), out, Ffm.NULL) == Ffm.ERROR_NONE ? out.get(JAVA_SHORT, 0) + : Short.MIN_VALUE; + } + } + + static int duckdb_get_uint16(ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = a.allocate(JAVA_SHORT); + return Capi.duckdb_v2_value_get_usmallint(v(value), out, Ffm.NULL) == Ffm.ERROR_NONE + ? Short.toUnsignedInt(out.get(JAVA_SHORT, 0)) + : 0; + } + } + + static int duckdb_get_int32(ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outInt(a); + return Capi.duckdb_v2_value_get_int(v(value), out, Ffm.NULL) == Ffm.ERROR_NONE ? out.get(JAVA_INT, 0) + : Integer.MIN_VALUE; + } + } + + static long duckdb_get_uint32(ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outInt(a); + return Capi.duckdb_v2_value_get_uint(v(value), out, Ffm.NULL) == Ffm.ERROR_NONE + ? Integer.toUnsignedLong(out.get(JAVA_INT, 0)) + : 0; + } + } + + static long duckdb_get_int64(ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outLong(a); + return Capi.duckdb_v2_value_get_bigint(v(value), out, Ffm.NULL) == Ffm.ERROR_NONE ? out.get(JAVA_LONG, 0) + : Long.MIN_VALUE; + } + } + + static long duckdb_get_uint64(ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outLong(a); + return Capi.duckdb_v2_value_get_ubigint(v(value), out, Ffm.NULL) == Ffm.ERROR_NONE ? out.get(JAVA_LONG, 0) + : 0; + } + } + + static BigInteger duckdb_get_hugeint(ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = a.allocate(16, 8); + if (Capi.duckdb_v2_value_get_hugeint(v(value), out, Ffm.NULL) != Ffm.ERROR_NONE) { + return DuckDBHugeInt.toBigInteger(0, Long.MIN_VALUE); + } + return DuckDBHugeInt.toBigInteger(out.get(JAVA_LONG, 0), out.get(JAVA_LONG, 8)); + } + } + + static BigInteger duckdb_get_uhugeint(ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = a.allocate(16, 8); + if (Capi.duckdb_v2_value_get_uhugeint(v(value), out, Ffm.NULL) != Ffm.ERROR_NONE) { + return DuckDBHugeInt.toBigInteger(0, 0); + } + return DuckDBHugeInt.toBigInteger(out.get(JAVA_LONG, 0), out.get(JAVA_LONG, 8)); + } + } + + static BigInteger duckdb_get_bignum(ByteBuffer value) throws SQLException { + return null; + } + + static BigDecimal duckdb_get_decimal(ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = a.allocate(16, 8); + MemorySegment width = Ffm.outInt(a); + MemorySegment scale = Ffm.outInt(a); + if (Capi.duckdb_v2_value_get_decimal(v(value), out, width, scale, Ffm.NULL) != Ffm.ERROR_NONE) { + return DuckDBHugeInt.toBigDecimal(0, 0, 0); + } + return DuckDBHugeInt.toBigDecimal(out.get(JAVA_LONG, 0), out.get(JAVA_LONG, 8), scale.get(JAVA_INT, 0)); + } + } + + static float duckdb_get_float(ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = a.allocate(JAVA_FLOAT); + return Capi.duckdb_v2_value_get_float(v(value), out, Ffm.NULL) == Ffm.ERROR_NONE ? out.get(JAVA_FLOAT, 0) + : Float.NaN; + } + } + + static double duckdb_get_double(ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = a.allocate(JAVA_DOUBLE); + return Capi.duckdb_v2_value_get_double(v(value), out, Ffm.NULL) == Ffm.ERROR_NONE ? out.get(JAVA_DOUBLE, 0) + : Double.NaN; + } + } + + static int duckdb_get_date(ByteBuffer value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outInt(a); + return Capi.duckdb_v2_value_get_date(v(value), out, Ffm.NULL) == Ffm.ERROR_NONE ? out.get(JAVA_INT, 0) : 0; + } + } + + // not implemented in the bindings of the C API v2 + static long duckdb_get_time(ByteBuffer value) throws SQLException { + return 0; + } + + static long duckdb_get_time_ns(ByteBuffer value) throws SQLException { + return 0; + } + + static long duckdb_get_time_tz(ByteBuffer value) throws SQLException { + return 0; + } + + static long duckdb_get_timestamp_tz(ByteBuffer value) throws SQLException { + return 0; + } + + private static long timestamp(ByteBuffer value, int kind) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outLong(a); + MemorySegment val = v(value); + int state; + switch (kind) { + case 0: + state = Capi.duckdb_v2_value_get_timestamp(val, out, Ffm.NULL); + break; + case 1: + state = Capi.duckdb_v2_value_get_timestamp_sec(val, out, Ffm.NULL); + break; + case 2: + state = Capi.duckdb_v2_value_get_timestamp_ms(val, out, Ffm.NULL); + break; + default: + state = Capi.duckdb_v2_value_get_timestamp_ns(val, out, Ffm.NULL); + break; + } + return state == Ffm.ERROR_NONE ? out.get(JAVA_LONG, 0) : 0; + } + } + + static long duckdb_get_timestamp(ByteBuffer value) throws SQLException { + return timestamp(value, 0); + } + + static long duckdb_get_timestamp_s(ByteBuffer value) throws SQLException { + return timestamp(value, 1); + } + + static long duckdb_get_timestamp_ms(ByteBuffer value) throws SQLException { + return timestamp(value, 2); + } + + static long duckdb_get_timestamp_ns(ByteBuffer value) throws SQLException { + return timestamp(value, 3); + } + + static byte[] duckdb_get_varchar(ByteBuffer value) throws SQLException { + MemorySegment val = v(value); + try (Arena a = Arena.ofConfined()) { + MemorySegment type = Ffm.outPtr(a); + int typeId = -1; + if (Capi.duckdb_v2_value_get_logical_type(val, type, Ffm.NULL) == Ffm.ERROR_NONE) { + MemorySegment id = Ffm.outInt(a); + if (Capi.duckdb_v2_logical_type_get_id(type.get(ADDRESS, 0), id, Ffm.NULL) == Ffm.ERROR_NONE) { + typeId = id.get(JAVA_INT, 0); + } + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, type.get(ADDRESS, 0)); + Capi.duckdb_v2_logical_type_destroy(holder); + } + MemorySegment str = val; + MemorySegment cast = Ffm.NULL; + MemorySegment err = Ffm.outPtr(a); + try { + if (typeId != 25) { // not VARCHAR, the value is cast to it + MemorySegment factory = Ffm.ptr(FfmTypes.defaultFactory()); + MemorySegment varchar = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_factory_create_type_from_id(factory, 25, Ffm.NULL, Ffm.NULL, Ffm.NULL, 0, + varchar, err), + err); + MemorySegment casted = Ffm.outPtr(a); + int state = Capi.duckdb_v2_value_cast(factory, val, varchar.get(ADDRESS, 0), casted, err); + MemorySegment typeHolder = a.allocate(ADDRESS); + typeHolder.set(ADDRESS, 0, varchar.get(ADDRESS, 0)); + Capi.duckdb_v2_logical_type_destroy(typeHolder); + Ffm.check(state, err); + cast = casted.get(ADDRESS, 0); + str = cast; + } + MemorySegment text = Ffm.outPtr(a); + MemorySegment len = Ffm.outLong(a); + Ffm.check(Capi.duckdb_v2_value_get_varchar(str, text, len, err), err); + byte[] bytes = Ffm.toBytes(text.get(ADDRESS, 0), len.get(JAVA_LONG, 0)); + // as a C string, the value ends with the first zero byte + int end = 0; + while (end < bytes.length && bytes[end] != 0) { + end++; + } + return end == bytes.length ? bytes : java.util.Arrays.copyOf(bytes, end); + } finally { + if (cast.address() != 0) { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, cast); + Capi.duckdb_v2_value_destroy(holder); + } + } + } + } +} diff --git a/src/main/java22/org/duckdb/FfmVectors.java b/src/main/java22/org/duckdb/FfmVectors.java new file mode 100644 index 000000000..6a080ea50 --- /dev/null +++ b/src/main/java22/org/duckdb/FfmVectors.java @@ -0,0 +1,567 @@ +package org.duckdb; + +import static java.lang.foreign.ValueLayout.ADDRESS; +import static java.lang.foreign.ValueLayout.JAVA_BYTE; +import static java.lang.foreign.ValueLayout.JAVA_INT; +import static java.lang.foreign.ValueLayout.JAVA_LONG; + +import java.lang.foreign.Arena; +import java.lang.foreign.MemorySegment; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.concurrent.ConcurrentHashMap; + +/** The bindings of the vectors, the validity masks, the data chunks and the results that are read by chunks. */ +final class FfmVectors { + private FfmVectors() { + } + + // DUCKDB_V2_VECTOR_TYPE + private static final int VECTOR_FLAT = 1; + private static final int VECTOR_CONSTANT = 2; + private static final int TYPE_ID_VARCHAR = 25; + private static final int BYTES_INLINE_LENGTH = 12; + + private static long vectorSize = -1; + + /** The capacity of the data chunks (the standard vector size). */ + static synchronized long duckdb_vector_size() throws SQLException { + if (vectorSize < 0) { + ByteBuffer type = FfmTypes.duckdb_create_logical_type(FfmTypes.T_BOOLEAN); + ByteBuffer chunk = duckdb_create_data_chunk(new ByteBuffer[] {type}); + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outLong(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_data_chunk_get_capacity(Ffm.ptr(chunk), out, err), err); + vectorSize = out.get(JAVA_LONG, 0); + } finally { + duckdb_destroy_data_chunk(chunk); + FfmTypes.duckdb_destroy_logical_type(type); + } + } + return vectorSize; + } + + // --------------------------------------------------------------------------------------------------------- + // Vectors + // --------------------------------------------------------------------------------------------------------- + + // The chunks of the standalone vectors, by the addresses of the vectors + private static final ConcurrentHashMap STANDALONE = new ConcurrentHashMap<>(); + + static ByteBuffer duckdb_create_vector(ByteBuffer type) throws SQLException { + Ffm.ptrNonNull(type, "logical type"); + if (FfmTypes.isInvalid(type)) { + return null; + } + ByteBuffer chunk = duckdb_create_data_chunk(new ByteBuffer[] {type}); + if (chunk == null) { + return null; + } + ByteBuffer vector = duckdb_data_chunk_get_vector(chunk, 0); + STANDALONE.put(MemorySegment.ofBuffer(vector).address(), chunk); + return vector; + } + + static void duckdb_destroy_vector(ByteBuffer vector) throws SQLException { + ByteBuffer chunk = STANDALONE.remove(Ffm.ptrNonNull(vector, "vector").address()); + if (chunk != null) { + duckdb_destroy_data_chunk(chunk); + } + } + + static ByteBuffer duckdb_vector_get_column_type(ByteBuffer vector) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_vector_get_logical_type(Ffm.ptrNonNull(vector, "vector"), out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + private static MemorySegment vectorData(MemorySegment vector) { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + if (Capi.duckdb_v2_vector_get_data_mutable(vector, out, Ffm.NULL) != Ffm.ERROR_NONE) { + return Ffm.NULL; + } + return out.get(ADDRESS, 0); + } + } + + static ByteBuffer duckdb_vector_get_data(ByteBuffer vector, long sizeBytes) throws SQLException { + MemorySegment data = vectorData(Ffm.ptrNonNull(vector, "vector")); + return data.address() == 0 ? null : Ffm.data(data, sizeBytes); + } + + static ByteBuffer duckdb_vector_get_data_zeroed(ByteBuffer vector, long sizeBytes) throws SQLException { + MemorySegment data = vectorData(Ffm.ptrNonNull(vector, "vector")); + if (data.address() == 0) { + return null; + } + MemorySegment.ofAddress(data.address()).reinterpret(sizeBytes).fill((byte) 0); + return Ffm.data(data, sizeBytes); + } + + // The validity mask of a flat or a constant vector, NULL if all the rows are valid or if it is another vector + private static MemorySegment vectorValidity(MemorySegment vector) { + try (Arena a = Arena.ofConfined()) { + MemorySegment type = Ffm.outInt(a); + if (Capi.duckdb_v2_vector_get_vector_type(vector, type, Ffm.NULL) != Ffm.ERROR_NONE) { + return Ffm.NULL; + } + int vectorType = type.get(JAVA_INT, 0); + if (vectorType != VECTOR_FLAT && vectorType != VECTOR_CONSTANT) { + return Ffm.NULL; + } + // the view: the data, the validity, the selection and the count + MemorySegment view = a.allocate(32, 8); + if (Capi.duckdb_v2_vector_get_view(vector, view, Ffm.NULL) != Ffm.ERROR_NONE) { + return Ffm.NULL; + } + return view.get(ADDRESS, 8); + } + } + + static ByteBuffer duckdb_vector_get_validity(ByteBuffer vector, long vectorSizeElems) throws SQLException { + MemorySegment mask = vectorValidity(Ffm.ptrNonNull(vector, "vector")); + if (mask.address() == 0) { + return null; + } + long rounded = vectorSizeElems; + if (rounded % 64 != 0) { + rounded += 64 - (rounded % 64); + } + return Ffm.data(mask, rounded * 8 / 64); + } + + private static MemorySegment writableValidity(MemorySegment vector) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_vector_flat_get_validity_mutable(vector, out, err), err); + return out.get(ADDRESS, 0); + } + } + + static void duckdb_vector_ensure_validity_writable(ByteBuffer vector) throws SQLException { + writableValidity(Ffm.ptrNonNull(vector, "vector")); + } + + private static void setRowInvalid(MemorySegment vector, long row) throws SQLException { + MemorySegment validity = + MemorySegment.ofAddress(writableValidity(vector).address()).reinterpret((row / 64 + 1) * 8); + long word = validity.getAtIndex(JAVA_LONG, row / 64); + validity.setAtIndex(JAVA_LONG, row / 64, word & ~(1L << (row % 64))); + } + + private static void setRowValid(MemorySegment validity, long row) { + long word = validity.getAtIndex(JAVA_LONG, row / 64); + validity.setAtIndex(JAVA_LONG, row / 64, word | (1L << (row % 64))); + } + + // Writes the entry of the string: the bytes are stored in the arena of the vector if they do not fit the entry + private static void assignString(MemorySegment vector, MemorySegment data, MemorySegment arena, long row, + byte[] bytes, int offset, int length) throws SQLException { + MemorySegment entry = MemorySegment.ofAddress(data.address() + row * 16).reinterpret(16); + entry.fill((byte) 0); + entry.set(JAVA_INT, 0, length); + if (length <= BYTES_INLINE_LENGTH) { + MemorySegment.copy(bytes, offset, entry, JAVA_BYTE, 4, length); + return; + } + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_arena_allocate(arena, length, out, err), err); + MemorySegment dst = MemorySegment.ofAddress(out.get(ADDRESS, 0).address()).reinterpret(length); + MemorySegment.copy(bytes, offset, dst, JAVA_BYTE, 0, length); + MemorySegment.copy(bytes, offset, entry, JAVA_BYTE, 4, 4); + entry.set(ADDRESS, 8, dst); + } + } + + private static MemorySegment vectorArena(MemorySegment vector) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_vector_get_arena(vector, out, err), err); + return out.get(ADDRESS, 0); + } + } + + private static boolean validUtf8(byte[] bytes, int offset, int length) { + try (Arena a = Arena.ofConfined()) { + MemorySegment text = a.allocate(Math.max(1, length)); + MemorySegment.copy(bytes, offset, text, JAVA_BYTE, 0, length); + return Capi.duckdb_v2_validate_utf8(text, length, Ffm.NULL) == Ffm.ERROR_NONE; + } + } + + static void duckdb_vector_assign_string_element_len(ByteBuffer vector, long index, byte[] str) throws SQLException { + MemorySegment vec = Ffm.ptrNonNull(vector, "vector"); + if (index < 0) { + throw new SQLException("Invalid index"); + } + if (str == null) { + throw new SQLException("Invalid string"); + } + try (Arena a = Arena.ofConfined()) { + MemorySegment type = Ffm.outPtr(a); + int typeId = -1; + if (Capi.duckdb_v2_vector_get_logical_type(vec, type, Ffm.NULL) == Ffm.ERROR_NONE) { + MemorySegment id = Ffm.outInt(a); + if (Capi.duckdb_v2_logical_type_get_id(type.get(ADDRESS, 0), id, Ffm.NULL) == Ffm.ERROR_NONE) { + typeId = id.get(JAVA_INT, 0); + } + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, type.get(ADDRESS, 0)); + Capi.duckdb_v2_logical_type_destroy(holder); + } + if (typeId == TYPE_ID_VARCHAR && !validUtf8(str, 0, str.length)) { + setRowInvalid(vec, index); + return; + } + } + assignString(vec, vectorData(vec), vectorArena(vec), index, str, 0, str.length); + } + + static void duckdb_vector_assign_string_elements(ByteBuffer vector, long index, byte[] data, long[] lengths, + int dataLength) throws SQLException { + MemorySegment vec = Ffm.ptrNonNull(vector, "vector"); + if (data == null || lengths == null || dataLength < 0 || dataLength > data.length) { + throw new SQLException("Invalid string batch length"); + } + long payload = 0; + for (long len : lengths) { + if (len < 0) { + continue; + } + if (len > dataLength - payload) { + throw new SQLException("Invalid string batch lengths"); + } + payload += len; + } + if (payload != dataLength) { + throw new SQLException("String batch length does not match payload"); + } + if (!validUtf8(data, 0, dataLength)) { + throw new SQLException("Invalid UTF-8 string batch"); + } + MemorySegment validity = writableValidity(vec); + if (validity.address() == 0) { + throw new SQLException("Invalid validity mask"); + } + MemorySegment mask = + MemorySegment.ofAddress(validity.address()).reinterpret((index + lengths.length) / 64 * 8 + 8); + MemorySegment dataPtr = vectorData(vec); + MemorySegment arena = vectorArena(vec); + int offset = 0; + for (int i = 0; i < lengths.length; i++) { + long row = index + i; + long len = lengths[i]; + if (len < 0) { + long word = mask.getAtIndex(JAVA_LONG, row / 64); + mask.setAtIndex(JAVA_LONG, row / 64, word & ~(1L << (row % 64))); + continue; + } + assignString(vec, dataPtr, arena, row, data, offset, (int) len); + setRowValid(mask, row); + offset += (int) len; + } + } + + /** The bytes of the string (BLOB) of the row of the vector data. */ + static byte[] duckdb_vector_get_string(ByteBuffer vectorData, long row) throws SQLException { + MemorySegment base = MemorySegment.ofBuffer(Ffm.ptrNonNullBuffer(vectorData, "vector data")); + long entry = row * 16; + int len = base.get(JAVA_INT, entry); + if (len <= BYTES_INLINE_LENGTH) { + byte[] res = new byte[len]; + MemorySegment.copy(base, JAVA_BYTE, entry + 4, res, 0, len); + return res; + } + MemorySegment bytes = MemorySegment.ofAddress(base.get(JAVA_LONG, entry + 8)).reinterpret(len); + return bytes.toArray(JAVA_BYTE); + } + + private static MemorySegment child(MemorySegment vector, long index) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_vector_get_child(vector, index, out, err), err); + return out.get(ADDRESS, 0); + } + } + + static ByteBuffer duckdb_list_vector_get_child(ByteBuffer vector) throws SQLException { + return Ffm.handle(child(Ffm.ptrNonNull(vector, "vector"), 0)); + } + + static long duckdb_list_vector_get_size(ByteBuffer vector) throws SQLException { + MemorySegment child = child(Ffm.ptrNonNull(vector, "vector"), 0); + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outLong(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_vector_get_size(child, out, err), err); + return out.get(JAVA_LONG, 0); + } + } + + static int duckdb_list_vector_set_size(ByteBuffer vector, long size) throws SQLException { + MemorySegment vec = Ffm.ptrNonNull(vector, "vector"); + try (Arena a = Arena.ofConfined()) { + MemorySegment c = child(vec, 0); + return Capi.duckdb_v2_vector_set_size(c, size, Ffm.NULL) == Ffm.ERROR_NONE ? 0 : 1; + } catch (SQLException e) { + return 1; + } + } + + static int duckdb_list_vector_reserve(ByteBuffer vector, long capacity) throws SQLException { + MemorySegment vec = Ffm.ptrNonNull(vector, "vector"); + try (Arena a = Arena.ofConfined()) { + MemorySegment c = child(vec, 0); + MemorySegment out = Ffm.outLong(a); + if (Capi.duckdb_v2_vector_get_size(c, out, Ffm.NULL) != Ffm.ERROR_NONE) { + return 1; + } + long size = out.get(JAVA_LONG, 0); + if (capacity > size) { + if (Capi.duckdb_v2_vector_set_size(c, capacity, Ffm.NULL) != Ffm.ERROR_NONE || + Capi.duckdb_v2_vector_set_size(c, size, Ffm.NULL) != Ffm.ERROR_NONE) { + return 1; + } + } + return 0; + } catch (SQLException e) { + return 1; + } + } + + static ByteBuffer duckdb_struct_vector_get_child(ByteBuffer vector, long index) throws SQLException { + return Ffm.handle(child(Ffm.ptrNonNull(vector, "vector"), index)); + } + + static ByteBuffer duckdb_array_vector_get_child(ByteBuffer vector) throws SQLException { + return Ffm.handle(child(Ffm.ptrNonNull(vector, "vector"), 0)); + } + + // --------------------------------------------------------------------------------------------------------- + // Validity masks + // --------------------------------------------------------------------------------------------------------- + + static boolean duckdb_validity_row_is_valid(ByteBuffer validity, long row) throws SQLException { + MemorySegment mask = MemorySegment.ofBuffer(Ffm.ptrNonNullBuffer(validity, "validity")); + return (mask.getAtIndex(JAVA_LONG, row / 64) & (1L << (row % 64))) != 0; + } + + static void duckdb_validity_set_row_validity(ByteBuffer validity, long row, boolean valid) throws SQLException { + MemorySegment mask = MemorySegment.ofBuffer(Ffm.ptrNonNullBuffer(validity, "validity")); + long word = mask.getAtIndex(JAVA_LONG, row / 64); + long bit = 1L << (row % 64); + mask.setAtIndex(JAVA_LONG, row / 64, valid ? (word | bit) : (word & ~bit)); + } + + // --------------------------------------------------------------------------------------------------------- + // Data chunks + // --------------------------------------------------------------------------------------------------------- + + /** The row count of the input chunk of a scalar function without arguments, see FfmFunctions. */ + static final ThreadLocal SCALAR_INPUT_ROW_COUNT = new ThreadLocal<>(); + + static ByteBuffer duckdb_create_data_chunk(ByteBuffer[] types) throws SQLException { + if (types == null) { + throw new SQLException("Invalid logical type array"); + } + try (Arena a = Arena.ofConfined()) { + MemorySegment typePtrs = a.allocate(Math.max(1, types.length) * 8L, 8); + for (int i = 0; i < types.length; i++) { + if (types[i] == null) { + throw new SQLException("Invalid logical type buffer"); + } + if (FfmTypes.isInvalid(types[i])) { + return null; + } + typePtrs.setAtIndex(ADDRESS, i, Ffm.ptr(types[i])); + } + MemorySegment out = Ffm.outPtr(a); + if (Capi.duckdb_v2_data_chunk_create(Ffm.ptr(FfmTypes.defaultFactory()), typePtrs, types.length, out, + Ffm.NULL) != Ffm.ERROR_NONE) { + return null; + } + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static void duckdb_destroy_data_chunk(ByteBuffer chunk) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, Ffm.ptrNonNull(chunk, "chunk")); + Capi.duckdb_v2_data_chunk_destroy(holder); + } + } + + static void duckdb_data_chunk_reset(ByteBuffer chunk) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_data_chunk_clear(Ffm.ptrNonNull(chunk, "chunk"), err), err); + } + } + + static long duckdb_data_chunk_get_column_count(ByteBuffer chunk) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outLong(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_data_chunk_get_vector_count(Ffm.ptrNonNull(chunk, "chunk"), out, err), err); + return out.get(JAVA_LONG, 0); + } + } + + static ByteBuffer duckdb_data_chunk_get_vector(ByteBuffer chunk, long colIdx) throws SQLException { + MemorySegment dc = Ffm.ptrNonNull(chunk, "chunk"); + try (Arena a = Arena.ofConfined()) { + MemorySegment count = Ffm.outLong(a); + if (Capi.duckdb_v2_data_chunk_get_vector_count(dc, count, Ffm.NULL) != Ffm.ERROR_NONE || colIdx < 0 || + colIdx >= count.get(JAVA_LONG, 0)) { + return null; + } + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_data_chunk_get_vector(dc, colIdx, out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static long duckdb_data_chunk_get_size(ByteBuffer chunk) throws SQLException { + MemorySegment dc = Ffm.ptrNonNull(chunk, "chunk"); + long[] scalar = SCALAR_INPUT_ROW_COUNT.get(); + if (scalar != null && scalar[0] == dc.address()) { + return scalar[1]; + } + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outLong(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_data_chunk_get_size(dc, out, err), err); + return out.get(JAVA_LONG, 0); + } + } + + static void duckdb_data_chunk_set_size(ByteBuffer chunk, long size) throws SQLException { + MemorySegment dc = Ffm.ptrNonNull(chunk, "chunk"); + try (Arena a = Arena.ofConfined()) { + MemorySegment count = Ffm.outLong(a); + if (Capi.duckdb_v2_data_chunk_get_vector_count(dc, count, Ffm.NULL) != Ffm.ERROR_NONE) { + return; + } + MemorySegment vec = Ffm.outPtr(a); + for (long i = 0; i < count.get(JAVA_LONG, 0); i++) { + if (Capi.duckdb_v2_data_chunk_get_vector(dc, i, vec, Ffm.NULL) != Ffm.ERROR_NONE) { + return; + } + Capi.duckdb_v2_vector_set_size(vec.get(ADDRESS, 0), size, Ffm.NULL); + } + } + long[] scalar = SCALAR_INPUT_ROW_COUNT.get(); + if (scalar != null && scalar[0] == dc.address()) { + scalar[1] = size; + } + } + + // --------------------------------------------------------------------------------------------------------- + // The results that are read by chunks + // --------------------------------------------------------------------------------------------------------- + + /** A result that is read by chunks, with the error of the last fetch (as of the C API v1 result). */ + private static final class ChunkedResult { + final ByteBuffer result; + final String[] names; + final int[] types; + String error; + + ChunkedResult(ByteBuffer result, String[] names, int[] types) { + this.result = result; + this.names = names; + this.types = types; + } + } + + // The results by the addresses of their tokens + private static final ConcurrentHashMap RESULTS = new ConcurrentHashMap<>(); + + /** Takes the ownership of the result, returns the reference of it. */ + static ByteBuffer createChunkedResult(ByteBuffer result) throws SQLException { + ByteBuffer schema = null; + try { + schema = FfmV2.duckdb_v2_result_get_schema(result); + byte[][] nameBytes = FfmV2.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], StandardCharsets.UTF_8); + } + int[] types = FfmV2.duckdb_v2_schema_get_field_type_ids(schema); + ByteBuffer token = Ffm.handle(Arena.global().allocate(8).address()); + RESULTS.put(MemorySegment.ofBuffer(token).address(), new ChunkedResult(result, names, types)); + return token; + } catch (SQLException | RuntimeException e) { + FfmV2.duckdb_v2_result_destroy(result); + throw e; + } finally { + if (schema != null) { + FfmV2.duckdb_v2_schema_destroy(schema); + } + } + } + + private static ChunkedResult result(ByteBuffer ref) throws SQLException { + ChunkedResult res = RESULTS.get(Ffm.ptrNonNull(ref, "result").address()); + if (res == null) { + throw new SQLException("Invalid result"); + } + return res; + } + + static void duckdb_destroy_result(ByteBuffer result) throws SQLException { + ChunkedResult res = RESULTS.remove(Ffm.ptrNonNull(result, "result").address()); + if (res != null) { + FfmV2.duckdb_v2_result_destroy(res.result); + } + } + + static ByteBuffer duckdb_fetch_chunk(ByteBuffer result) throws SQLException { + ChunkedResult res = result(result); + try { + return FfmV2.duckdb_v2_result_fetch_chunk(res.result); + } catch (SQLException e) { + // the error is set on the result so duckdb_result_error can retrieve it + res.error = e.getMessage(); + return null; + } + } + + static byte[] duckdb_column_name(ByteBuffer result, long col) throws SQLException { + ChunkedResult res = result(result); + if (col < 0 || col >= res.names.length) { + return null; + } + return res.names[(int) col].getBytes(StandardCharsets.UTF_8); + } + + static int duckdb_column_type(ByteBuffer result, long col) throws SQLException { + ChunkedResult res = result(result); + if (col < 0 || col >= res.types.length) { + return FfmTypes.T_INVALID; + } + return res.types[(int) col]; + } + + static long duckdb_column_count(ByteBuffer result) throws SQLException { + return result(result).names.length; + } + + static byte[] duckdb_result_error(ByteBuffer result) throws SQLException { + ChunkedResult res = result(result); + return res.error == null ? null : res.error.getBytes(StandardCharsets.UTF_8); + } +} 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); } } 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)); 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); diff --git a/src/test/java/org/duckdb/TestNoLib.java b/src/test/java/org/duckdb/TestNoLib.java index 2df9a5fca..5af1831ec 100644 --- a/src/test/java/org/duckdb/TestNoLib.java +++ b/src/test/java/org/duckdb/TestNoLib.java @@ -14,7 +14,7 @@ public class TestNoLib { private static Path javaExe() { String javaHomeProp = System.getProperty("java.home"); Path javaHome = Paths.get(javaHomeProp); - boolean isWindows = "windows".equals(DuckDBNative.osName()); + boolean isWindows = "windows".equals(DuckDBLibrary.osName()); return isWindows ? javaHome.resolve("bin/java.exe") : javaHome.resolve("bin/java"); } @@ -33,7 +33,7 @@ private static void runQuickTest(Path currentJarDir) throws Exception { } private static String platformLibName() throws Exception { - String os = DuckDBNative.osName(); + String os = DuckDBLibrary.osName(); switch (os) { case "windows": return "duckdb_java.dll"; @@ -46,7 +46,7 @@ private static String platformLibName() throws Exception { } } private static Path nativeLibPathInBuildTree(Path buildDir) throws SQLException { - String libName = DuckDBNative.nativeLibName(); + String libName = DuckDBLibrary.nativeLibName(); Path libPath = buildDir.resolve(libName); if (Files.exists(libPath)) { return libPath; @@ -63,7 +63,7 @@ private static Path nativeLibPathInBuildTree(Path buildDir) throws SQLException public static void test_nolib_next_to_jar() throws Exception { try (TempDirectory td = new TempDirectory()) { - Path dir = DuckDBNative.currentJarDir(); + Path dir = DuckDBLibrary.currentJarDir(); Path nativeLib = nativeLibPathInBuildTree(dir); Files.copy(dir.resolve("duckdb_jdbc_nolib.jar"), td.path().resolve("duckdb_jdbc_nolib.jar")); Files.copy(dir.resolve("duckdb_jdbc_tests.jar"), td.path().resolve("duckdb_jdbc_tests.jar")); @@ -77,7 +77,7 @@ public static void test_nolib_next_to_jar() throws Exception { public static void test_nolib_by_name() throws Exception { try (TempDirectory td = new TempDirectory()) { - Path dir = DuckDBNative.currentJarDir(); + Path dir = DuckDBLibrary.currentJarDir(); Path nativeLib = nativeLibPathInBuildTree(dir); Files.copy(dir.resolve("duckdb_jdbc_nolib.jar"), td.path().resolve("duckdb_jdbc_nolib.jar")); Files.copy(dir.resolve("duckdb_jdbc_tests.jar"), td.path().resolve("duckdb_jdbc_tests.jar"));