diff --git a/.github/composite-actions/find-visual-studio/action.yml b/.github/composite-actions/find-visual-studio/action.yml new file mode 100644 index 000000000..4156f3a3c --- /dev/null +++ b/.github/composite-actions/find-visual-studio/action.yml @@ -0,0 +1,41 @@ +name: 'Find Visual Studio' +description: >- + Finds the C++ tools of Visual Studio 2026 or, when it is not installed, of Visual Studio 2022 and sets + the VCVARS_PATH environment variable to the path of the script that sets up their environment. +inputs: + vcvars: + description: >- + Name of the environment script of the tools, for example vcvars64.bat (amd64 tools for amd64) + or vcvarsamd64_arm64.bat (amd64 tools for arm64) + required: true + +runs: + using: "composite" + steps: + - name: Find Visual Studio + shell: pwsh + env: + VCVARS_NAME: ${{ inputs.vcvars }} + run: | + $vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe' + if (-not (Test-Path $vswhere)) { + throw "vswhere is not found: $vswhere" + } + # Visual Studio 2026 (18.x) and Visual Studio 2022 (17.x) of any edition, the newest version is the first one + $installations = @(& $vswhere -products * -version '[17.0,19.0)' -sort -property installationPath) + Write-Output 'Visual Studio installations:' + $installations | ForEach-Object { Write-Output " $_" } + # the first installation that has the requested tools is used + $vcvars = $null + foreach ($installation in $installations) { + $candidate = Join-Path $installation (Join-Path 'VC\Auxiliary\Build' $env:VCVARS_NAME) + if (Test-Path $candidate) { + $vcvars = $candidate + break + } + } + if (-not $vcvars) { + throw "Visual Studio 2026 or 2022 with $($env:VCVARS_NAME) is not found" + } + Write-Output "VCVARS_PATH=$vcvars" + "VCVARS_PATH=$vcvars" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append diff --git a/.github/composite-actions/linux-build-docker/action.yml b/.github/composite-actions/linux-build-docker/action.yml index 4447e8213..dd90ee0d6 100644 --- a/.github/composite-actions/linux-build-docker/action.yml +++ b/.github/composite-actions/linux-build-docker/action.yml @@ -1,5 +1,7 @@ name: 'Linux Build Docker' -description: 'Linux build in Docker' +description: >- + Linux build in Docker. The JDKs of the JAVA_JNI_HOME and JAVA_FFM_HOME environment variables + (see setup-jdk-corretto) are mounted into the container. inputs: docker_image: description: 'Docker image name' @@ -12,23 +14,29 @@ runs: - name: Build shell: bash run: | + : "${JAVA_JNI_HOME:?JAVA_JNI_HOME is not set}" + : "${JAVA_FFM_HOME:?JAVA_FFM_HOME is not set}" python ./scripts/retry.py --timeout 1m -- \ docker pull ${{ inputs.docker_image }} docker run \ -v.:/duckdb \ + -v "${JAVA_JNI_HOME}:/jdk-jni" \ + -v "${JAVA_FFM_HOME}:/jdk-ffm" \ -e GEN=ninja \ -e CC='ccache gcc' \ -e CXX='ccache g++' \ -e CCACHE_DIR=/duckdb/ccache \ - -e JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk \ + -e JAVA_JNI_HOME=/jdk-jni \ + -e JAVA_FFM_HOME=/jdk-ffm \ ${{ inputs.docker_image }} \ bash -c " set -e cat /etc/os-release + /jdk-jni/bin/java -version + /jdk-ffm/bin/java -version python3 /duckdb/scripts/retry.py --timeout 2m -- \ dnf install -y \ ccache \ - java-1.8.0-openjdk-devel \ ninja-build make -C /duckdb release " diff --git a/.github/composite-actions/linux-build-musl-docker/action.yml b/.github/composite-actions/linux-build-musl-docker/action.yml index 0412b1f5e..bf294e3fe 100644 --- a/.github/composite-actions/linux-build-musl-docker/action.yml +++ b/.github/composite-actions/linux-build-musl-docker/action.yml @@ -1,5 +1,7 @@ name: 'Linux Build Musl Docker' -description: 'Linux build with musl libc in Docker' +description: >- + Linux build with musl libc in Docker. The JDKs of the JAVA_JNI_HOME and JAVA_FFM_HOME environment + variables (see setup-jdk-corretto, the JDKs for Alpine Linux) are mounted into the container. inputs: docker_image: description: 'Docker image name' @@ -12,15 +14,20 @@ runs: - name: Build shell: bash run: | + : "${JAVA_JNI_HOME:?JAVA_JNI_HOME is not set}" + : "${JAVA_FFM_HOME:?JAVA_FFM_HOME is not set}" python ./scripts/retry.py --timeout 1m -- \ docker pull ${{ inputs.docker_image }} docker run \ -v.:/duckdb \ + -v "${JAVA_JNI_HOME}:/jdk-jni" \ + -v "${JAVA_FFM_HOME}:/jdk-ffm" \ -e GEN=ninja \ -e CC='ccache gcc' \ -e CXX='ccache g++' \ -e CCACHE_DIR=/duckdb/ccache \ - -e JAVA_HOME=/usr/lib/jvm/java-8-openjdk \ + -e JAVA_JNI_HOME=/jdk-jni \ + -e JAVA_FFM_HOME=/jdk-ffm \ ${{ inputs.docker_image }} \ sh -c " set -e @@ -31,7 +38,8 @@ runs: cmake \ g++ \ make \ - openjdk8-jdk \ samurai + /jdk-jni/bin/java -version + /jdk-ffm/bin/java -version make -C /duckdb release - " \ No newline at end of file + " diff --git a/.github/composite-actions/linux-tests-docker/action.yml b/.github/composite-actions/linux-tests-docker/action.yml index 086872a90..8f500ee82 100644 --- a/.github/composite-actions/linux-tests-docker/action.yml +++ b/.github/composite-actions/linux-tests-docker/action.yml @@ -1,5 +1,7 @@ name: 'Linux Tests Docker' -description: 'Linux test run in Docker' +description: >- + Linux test run in Docker. The JDK of the JAVA_JNI_HOME environment variable (see setup-jdk-corretto) + is mounted into the container and runs the tests. inputs: docker_image: description: 'Docker image name' @@ -12,20 +14,21 @@ runs: - name: Tests Docker shell: bash run: | + : "${JAVA_JNI_HOME:?JAVA_JNI_HOME is not set}" python ./scripts/retry.py --timeout 1m -- \ docker pull ${{ inputs.docker_image }} - docker run \ - -v.:/duckdb \ - ${{ inputs.docker_image }} \ + docker run \ + -v.:/duckdb \ + -v "${JAVA_JNI_HOME}:/jdk-jni" \ + ${{ inputs.docker_image }} \ bash -c " set -e cat /etc/os-release - python3 /duckdb/scripts/retry.py --timeout 2m -- \ - dnf install -y \ - java-1.8.0-openjdk - /usr/lib/jvm/jre-1.8.0-openjdk/bin/java -version + export PATH=/jdk-jni/bin:\$PATH + which java + java -version cd /duckdb - /usr/lib/jvm/jre-1.8.0-openjdk/bin/java \ + java \ -cp ./build/release/duckdb_jdbc_tests.jar:./build/release/duckdb_jdbc.jar \ org.duckdb.TestDuckDBJDBC rm ./test1.db diff --git a/.github/composite-actions/linux-tests-host/action.yml b/.github/composite-actions/linux-tests-host/action.yml index 16a67439e..84d156b64 100644 --- a/.github/composite-actions/linux-tests-host/action.yml +++ b/.github/composite-actions/linux-tests-host/action.yml @@ -1,25 +1,52 @@ name: 'Linux Tests Host' -description: 'Linux test run in host OS' +description: >- + Linux test run in host OS. The JDK of the JAVA_LATEST_HOME environment variable (see setup-jdk-corretto) + runs the tests two times: with the JNI bindings and with the FFM bindings of the multi-release jar. runs: using: "composite" steps: - - name: Setup JDK - uses: actions/setup-java@v6 - with: - distribution: 'corretto' - java-version: '27' - - - name: Tests Host + - name: Tests Host (JNI) shell: bash run: | + : "${JAVA_LATEST_HOME:?JAVA_LATEST_HOME is not set}" cat /etc/os-release + export PATH="${JAVA_LATEST_HOME}/bin:${PATH}" + which java + java -version + # the FFM classes of the multi-release jar are not used + java -Djdk.util.jar.enableMultiRelease=false \ + -cp ./build/release/duckdb_jdbc_tests.jar:./build/release/duckdb_jdbc.jar \ + org.duckdb.TestDuckDBJDBC + + - name: Tests Host (FFM) + shell: bash + run: | + export PATH="${JAVA_LATEST_HOME}/bin:${PATH}" + which java java -version - java \ + java --enable-native-access=ALL-UNNAMED \ -cp ./build/release/duckdb_jdbc_tests.jar:./build/release/duckdb_jdbc.jar \ org.duckdb.TestDuckDBJDBC - - name: Arrow Tests Host + - name: Arrow Tests Host (JNI) shell: bash + env: + JDK_JAVA_OPTIONS: '-Djdk.util.jar.enableMultiRelease=false' run: | + export JAVA_HOME="${JAVA_LATEST_HOME}" + export PATH="${JAVA_LATEST_HOME}/bin:${PATH}" + which java + java -version + ./src/test/external/test_arrow.sh + + - name: Arrow Tests Host (FFM) + shell: bash + env: + JDK_JAVA_OPTIONS: '--enable-native-access=ALL-UNNAMED' + run: | + export JAVA_HOME="${JAVA_LATEST_HOME}" + export PATH="${JAVA_LATEST_HOME}/bin:${PATH}" + which java + java -version ./src/test/external/test_arrow.sh diff --git a/.github/composite-actions/linux-tests-musl-docker/action.yml b/.github/composite-actions/linux-tests-musl-docker/action.yml index cb0f00c96..74a65a9f5 100644 --- a/.github/composite-actions/linux-tests-musl-docker/action.yml +++ b/.github/composite-actions/linux-tests-musl-docker/action.yml @@ -1,5 +1,7 @@ name: 'Linux Tests Musl Docker' -description: 'Linux test run with musl libc in Docker' +description: >- + Linux test run with musl libc in Docker. The JDK of the JAVA_JNI_HOME environment variable + (see setup-jdk-corretto, the JDK for Alpine Linux) is mounted into the container and runs the tests. inputs: docker_image: description: 'Docker image name' @@ -12,12 +14,13 @@ runs: - name: Tests Musl Docker shell: bash run: | + : "${JAVA_JNI_HOME:?JAVA_JNI_HOME is not set}" python ./scripts/retry.py --timeout 1m -- \ docker pull ${{ inputs.docker_image }} docker run \ -v.:/duckdb \ + -v "${JAVA_JNI_HOME}:/jdk-jni" \ -e GEN=ninja \ - -e JAVA_HOME=/usr/lib/jvm/java-8-openjdk \ ${{ inputs.docker_image }} \ sh -c " set -e @@ -27,7 +30,9 @@ runs: cmake \ g++ \ make \ - openjdk8-jdk \ samurai + export PATH=/jdk-jni/bin:\$PATH + which java + java -version make -C /duckdb test || true " diff --git a/.github/composite-actions/setup-jdk-corretto/action.yml b/.github/composite-actions/setup-jdk-corretto/action.yml new file mode 100644 index 000000000..e9cf4fb00 --- /dev/null +++ b/.github/composite-actions/setup-jdk-corretto/action.yml @@ -0,0 +1,123 @@ +name: 'Setup JDK Corretto' +description: >- + Downloads Amazon Corretto JDK from its permanent URL, checks the SHA-256 checksum of the download and sets + the environment variable to the home directory of the JDK. PATH is not changed. +inputs: + version: + description: 'Major version of the JDK, for example 8 or 25' + required: true + env_name: + description: 'Name of the environment variable that is set to the home directory of the JDK' + required: false + default: 'JAVA_HOME' + arch: + description: >- + Architecture and OS of the JDK as they are named in the Corretto downloads, for example + x64-linux, aarch64-linux, x64-alpine, aarch64-alpine, x64-macos, aarch64-macos or x64-windows + required: true + +runs: + using: "composite" + steps: + - name: Setup JDK Corretto + shell: bash + env: + JDK_VERSION: ${{ inputs.version }} + JDK_ENV_NAME: ${{ inputs.env_name }} + JDK_ARCH: ${{ inputs.arch }} + run: | + set -euo pipefail + + if ! [[ "${JDK_VERSION}" =~ ^[0-9]+$ ]]; then + echo "Invalid JDK version: '${JDK_VERSION}'" >&2 + exit 1 + fi + if ! [[ "${JDK_ARCH}" =~ ^[a-z0-9]+-[a-z]+$ ]]; then + echo "Invalid JDK arch: '${JDK_ARCH}'" >&2 + exit 1 + fi + if ! [[ "${JDK_ENV_NAME}" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]]; then + echo "Invalid environment variable name: '${JDK_ENV_NAME}'" >&2 + exit 1 + fi + + # Windows downloads are ZIP archives, all the other ones are tarballs + if [[ "${JDK_ARCH}" == *-windows ]]; then + EXT=zip + else + EXT=tar.gz + fi + FILE="amazon-corretto-${JDK_VERSION}-${JDK_ARCH}-jdk.${EXT}" + URL="https://corretto.aws/downloads/latest/${FILE}" + CHECKSUM_URL="https://corretto.aws/downloads/latest_sha256/${FILE}" + + # RUNNER_TEMP is a Windows path on Windows + TEMP_DIR="${RUNNER_TEMP}" + if command -v cygpath > /dev/null; then + TEMP_DIR="$(cygpath -u "${RUNNER_TEMP}")" + fi + DIR="${TEMP_DIR}/setup-jdk-corretto/${JDK_VERSION}-${JDK_ARCH}" + rm -rf "${DIR}" + mkdir -p "${DIR}" + + # only HTTPS is allowed (redirects included), the certificates are verified + download() { + curl --fail --silent --show-error --location \ + --proto '=https' --proto-redir '=https' --tlsv1.2 \ + --retry 3 --retry-delay 5 \ + --output "$2" "$1" + } + + echo "Downloading ${URL}" + download "${URL}" "${DIR}/${FILE}" + download "${CHECKSUM_URL}" "${DIR}/${FILE}.sha256" + + # the checksum file has the hex digest only + EXPECTED="$(tr -d '[:space:]' < "${DIR}/${FILE}.sha256" | tr 'A-F' 'a-f')" + if ! [[ "${EXPECTED}" =~ ^[0-9a-f]{64}$ ]]; then + echo "Invalid checksum file: ${CHECKSUM_URL}" >&2 + exit 1 + fi + if command -v sha256sum > /dev/null; then + ACTUAL="$(sha256sum "${DIR}/${FILE}" | cut -d ' ' -f 1)" + else + ACTUAL="$(shasum -a 256 "${DIR}/${FILE}" | cut -d ' ' -f 1)" + fi + # sha256sum of Git Bash marks binary files with a leading backslash in some cases + ACTUAL="${ACTUAL#\\}" + if [[ "${ACTUAL}" != "${EXPECTED}" ]]; then + echo "Checksum mismatch for ${FILE}: expected ${EXPECTED}, actual ${ACTUAL}" >&2 + exit 1 + fi + echo "SHA-256 checksum is correct: ${ACTUAL}" + + mkdir "${DIR}/jdk" + if [[ "${EXT}" == zip ]]; then + unzip -q "${DIR}/${FILE}" -d "${DIR}/jdk" + else + tar -xzf "${DIR}/${FILE}" -C "${DIR}/jdk" + fi + rm "${DIR}/${FILE}" "${DIR}/${FILE}.sha256" + + # the home directory is the one that has bin/javac, it is Contents/Home on macOS + JAVAC="$(find "${DIR}/jdk" -maxdepth 6 -type f \( -name javac -o -name javac.exe \) -path '*/bin/*' -print -quit)" + if [[ -z "${JAVAC}" ]]; then + echo "JDK home directory is not found in ${FILE}" >&2 + exit 1 + fi + JDK_HOME="$(cd "$(dirname "${JAVAC}")/.." && pwd)" + + # the variable has a Windows path on Windows + JDK_HOME_ENV="${JDK_HOME}" + if [[ "${JDK_ARCH}" == *-windows ]] && command -v cygpath > /dev/null; then + JDK_HOME_ENV="$(cygpath -w "${JDK_HOME}")" + fi + echo "${JDK_ENV_NAME}=${JDK_HOME_ENV}" >> "${GITHUB_ENV}" + echo "${JDK_ENV_NAME}=${JDK_HOME_ENV}" + + # a JDK for musl libc cannot be run on a host with glibc, it is run in an Alpine container + if [[ "${JDK_ARCH}" == *-alpine ]] && ! (ldd --version 2>&1 | grep -qi musl); then + echo "JDK for Alpine Linux is not run on this host, 'java -version' is skipped" + else + "${JDK_HOME}/bin/java" -version 2>&1 + fi diff --git a/.github/workflows/Java.yml b/.github/workflows/Java.yml index 9c346ba66..7cd2111a9 100644 --- a/.github/workflows/Java.yml +++ b/.github/workflows/Java.yml @@ -72,6 +72,20 @@ jobs: path: ${{ github.workspace }}/ccache key: ${{ steps.cache_key.outputs.value }} + - name: Setup JDK 8 (JNI) + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '8' + env_name: JAVA_JNI_HOME + arch: x64-linux + + - name: Setup JDK 25 (FFM) + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '25' + env_name: JAVA_FFM_HOME + arch: x64-linux + - name: Build uses: ./.github/composite-actions/linux-build-docker with: @@ -91,8 +105,15 @@ jobs: run: | nm ./build/release/libduckdb_java.so_linux_amd64 | grep jemalloc || exit 1 + - name: Check FFM classes + run: | + unzip -l build/release/duckdb_jdbc.jar | grep -q 'META-INF/versions/25/org/duckdb/Ffm.class' + - name: Check Module Name run: | + export PATH="${JAVA_FFM_HOME}/bin:${PATH}" + which java + java -version java \ --module-path ./build/release/duckdb_jdbc.jar \ -d duckdb.jdbc @@ -103,6 +124,14 @@ jobs: with: docker_image: '${{ env.MANYLINUX_IMAGE }}' + - name: Setup JDK 27 (latest) + if: ${{ inputs.skip_tests != 'true' }} + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '27' + env_name: JAVA_LATEST_HOME + arch: x64-linux + - name: JDBC Tests if: ${{ inputs.skip_tests != 'true' }} uses: ./.github/composite-actions/linux-tests-host @@ -137,6 +166,22 @@ jobs: path: ${{ github.workspace }}/ccache key: ${{ steps.cache_key.outputs.value }} + - name: Setup JDK 8 (JNI) + if: ${{ inputs.skip_tests != 'true' }} + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '8' + env_name: JAVA_JNI_HOME + arch: x64-linux + + - name: Setup JDK 25 (FFM) + if: ${{ inputs.skip_tests != 'true' }} + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '25' + env_name: JAVA_FFM_HOME + arch: x64-linux + - name: Build if: ${{ inputs.skip_tests != 'true' }} uses: ./.github/composite-actions/linux-build-docker @@ -163,15 +208,17 @@ jobs: run: | docker run \ -v.:/duckdb \ - -e JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk \ + -v "${JAVA_JNI_HOME}:/jdk-jni" \ + -e JAVA_HOME=/jdk-jni \ -e DUCKDB_JAR=/duckdb/build/release/duckdb_jdbc.jar \ -e PLATFORM_TCK_DIR=/duckdb/platform-tck \ ${{ env.MANYLINUX_IMAGE }} \ bash -c " set -e cat /etc/os-release - dnf install -y \ - java-1.8.0-openjdk-devel + export PATH=/jdk-jni/bin:\$PATH + which java + java -version make -C /duckdb/jdbc_compatibility_test_suite_runner test " @@ -200,6 +247,22 @@ jobs: path: ${{ github.workspace }}/ccache key: ${{ steps.cache_key.outputs.value }} + - name: Setup JDK 8 (JNI) + if: ${{ inputs.skip_tests != 'true' }} + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '8' + env_name: JAVA_JNI_HOME + arch: x64-linux + + - name: Setup JDK 25 (FFM) + if: ${{ inputs.skip_tests != 'true' }} + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '25' + env_name: JAVA_FFM_HOME + arch: x64-linux + - name: Build if: ${{ inputs.skip_tests != 'true' }} uses: ./.github/composite-actions/linux-build-docker @@ -213,12 +276,24 @@ jobs: java-version: '25' distribution: 'graalvm-community' - - name: Native Image Hello World + - name: Native Image Hello World (FFM) if: ${{ inputs.skip_tests != 'true' }} run: | + which java + java -version java ${{ github.workspace }}/src/test/external/RunGraalNativeImage.java \ ${{ github.workspace }}/src/test/external/graal + - name: Native Image Hello World (JNI) + if: ${{ inputs.skip_tests != 'true' }} + run: | + which java + java -version + # the FFM classes of the multi-release jar are not used by the image builder + java ${{ github.workspace }}/src/test/external/RunGraalNativeImage.java \ + ${{ github.workspace }}/src/test/external/graal \ + -J-Djdk.util.jar.enableMultiRelease=false + java-linux-amd64-spark: name: Linux Spark (amd64) runs-on: ${{ github.repository_owner == 'duckdb' && 'namespace-profile-linux-x64' || 'ubuntu-latest' }} @@ -261,11 +336,26 @@ jobs: path: ${{ github.workspace }}/ccache key: ${{ steps.cache_key.outputs.value }} - - name: Setup JDK - uses: actions/setup-java@v6 + - name: Setup JDK 8 (JNI) + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '8' + env_name: JAVA_JNI_HOME + arch: x64-linux + + - name: Setup JDK 25 (FFM) + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '25' + env_name: JAVA_FFM_HOME + arch: x64-linux + + - name: Setup JDK 17 (Spark) + uses: ./.github/composite-actions/setup-jdk-corretto with: - distribution: corretto - java-version: '17' + version: '17' + env_name: JAVA_HOME + arch: x64-linux - name: Build if: ${{ inputs.skip_tests != 'true' }} @@ -310,6 +400,8 @@ jobs: mv mc.linux-amd64.RELEASE.2025-08-13T08-35-41Z mc chmod +x mc ./mc --version + export PATH="${JAVA_HOME}/bin:${PATH}" + which java java -version java ${{ github.workspace }}/src/test/external/SetupMinio.java @@ -320,6 +412,8 @@ jobs: cat ${{ env.SESSION_INIT_SQL_FILE }} python ../scripts/retry.py --timeout 1m -- \ wget -nv https://github.com/pgjdbc/pgjdbc/releases/download/REL42.7.7/postgresql-42.7.7.jar + export PATH="${JAVA_HOME}/bin:${PATH}" + which java java -version java -cp ${{ env.DUCKDB_JDBC_JAR }}:postgresql-42.7.7.jar ${{ github.workspace }}/src/test/external/SetupDuckLake.java @@ -331,6 +425,8 @@ jobs: wget -nv https://blobs.duckdb.org/ci/spark-3.5.3-bin-hadoop3.tgz tar xf spark-3.5.3-bin-hadoop3.tgz cat spark-test.sql + export PATH="${JAVA_HOME}/bin:${PATH}" + which java java -version java ${{ github.workspace }}/src/test/external/RunSpark.java spark-test.sql @@ -373,6 +469,15 @@ jobs: path: ${{ github.workspace }}/ccache key: ${{ steps.cache_key.outputs.value }} + # The JDK that is installed on the runner compiles the driver and runs the tests (JAVA_JNI_HOME is not set), + # the build needs JDK 25 for the FFM bindings in addition to it + - name: Setup JDK 25 (FFM) + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '25' + env_name: JAVA_FFM_HOME + arch: x64-linux + - name: Build (patched) if: ${{ inputs.skip_tests != 'true' }} run: | @@ -391,7 +496,11 @@ jobs: env: LD_PRELOAD: "/usr/lib/x86_64-linux-gnu/libasan.so.8 /usr/lib/x86_64-linux-gnu/libstdc++.so.6" run: | + which java + LD_PRELOAD= java -version + # the JNI bindings are tested: the FFM classes of the multi-release jar are not used java \ + -Djdk.util.jar.enableMultiRelease=false \ -cp ./build/sanitized/duckdb_jdbc_nolib.jar:./build/sanitized/duckdb_jdbc_tests.jar \ org.duckdb.TestDuckDBJDBC \ quick \ @@ -414,7 +523,11 @@ jobs: env: LD_PRELOAD: "/usr/lib/x86_64-linux-gnu/libasan.so.8 /usr/lib/x86_64-linux-gnu/libstdc++.so.6" run: | + which java + LD_PRELOAD= java -version + # the JNI bindings are tested: the FFM classes of the multi-release jar are not used java \ + -Djdk.util.jar.enableMultiRelease=false \ -cp ./build/sanitized/duckdb_jdbc_nolib.jar:./build/sanitized/duckdb_jdbc_tests.jar \ org.duckdb.TestDuckDBJDBC \ quick \ @@ -464,6 +577,20 @@ jobs: path: ${{ github.workspace }}/ccache key: ${{ steps.cache_key.outputs.value }} + - name: Setup JDK 8 (JNI) + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '8' + env_name: JAVA_JNI_HOME + arch: x64-linux + + - name: Setup JDK 25 (FFM) + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '25' + env_name: JAVA_FFM_HOME + arch: x64-linux + - name: Build uses: ./.github/composite-actions/linux-build-docker with: @@ -481,21 +608,25 @@ jobs: graphviz \ leiningen - - name: Setup JDK - uses: actions/setup-java@v6 + - name: Setup JDK 21 (Jepsen) + uses: ./.github/composite-actions/setup-jdk-corretto with: - distribution: corretto - java-version: '21' + version: '21' + env_name: JAVA_HOME + arch: x64-linux - name: Check JDK version run: | + export PATH="${JAVA_HOME}/bin:${PATH}" which java java -version echo $JAVA_HOME - $JAVA_HOME/bin/java -version - name: Install JAR run: | + export PATH="${JAVA_HOME}/bin:${PATH}" + which java + java -version mvn -B -ntp --version mvn -B -ntp install:install-file \ -Dfile=${{ github.workspace }}/build/release/duckdb_jdbc.jar \ @@ -508,6 +639,9 @@ jobs: working-directory: jepsen run: | patch -p1 < ${{ github.workspace }}/data/jepsen/jepsen.patch + export PATH="${JAVA_HOME}/bin:${PATH}" + which java + java -version lein --version python ../scripts/retry.py --retries 1 --timeout 5m -- \ lein run test \ @@ -560,6 +694,20 @@ jobs: path: ${{ github.workspace }}/ccache key: ${{ steps.cache_key.outputs.value }} + - name: Setup JDK 8 (JNI) + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '8' + env_name: JAVA_JNI_HOME + arch: aarch64-linux + + - name: Setup JDK 25 (FFM) + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '25' + env_name: JAVA_FFM_HOME + arch: aarch64-linux + - name: Build uses: ./.github/composite-actions/linux-build-docker with: @@ -585,6 +733,14 @@ jobs: with: docker_image: '${{ env.MANYLINUX_IMAGE }}' + - name: Setup JDK 27 (latest) + if: ${{ inputs.skip_tests != 'true' }} + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '27' + env_name: JAVA_LATEST_HOME + arch: aarch64-linux + - name: JDBC Tests if: ${{ inputs.skip_tests != 'true' }} uses: ./.github/composite-actions/linux-tests-host @@ -619,6 +775,20 @@ jobs: path: ${{ github.workspace }}/ccache key: ${{ steps.cache_key.outputs.value }} + - name: Setup JDK 8 (JNI) + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '8' + env_name: JAVA_JNI_HOME + arch: x64-alpine + + - name: Setup JDK 25 (FFM) + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '25' + env_name: JAVA_FFM_HOME + arch: x64-alpine + - name: Build uses: ./.github/composite-actions/linux-build-musl-docker with: @@ -674,6 +844,20 @@ jobs: path: ${{ github.workspace }}/ccache key: ${{ steps.cache_key.outputs.value }} + - name: Setup JDK 8 (JNI) + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '8' + env_name: JAVA_JNI_HOME + arch: aarch64-alpine + + - name: Setup JDK 25 (FFM) + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '25' + env_name: JAVA_FFM_HOME + arch: aarch64-alpine + - name: Build uses: ./.github/composite-actions/linux-build-musl-docker with: @@ -727,11 +911,24 @@ jobs: ccache \ -y --force --no-progress - - name: Setup JDK - uses: actions/setup-java@v6 + - name: Find Visual Studio + uses: ./.github/composite-actions/find-visual-studio with: - distribution: corretto - java-version: '8' + vcvars: vcvars64.bat + + - name: Setup JDK 8 (JNI) + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '8' + env_name: JAVA_JNI_HOME + arch: x64-windows + + - name: Setup JDK 25 (FFM) + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '25' + env_name: JAVA_FFM_HOME + arch: x64-windows - name: Cache Key id: cache_key @@ -750,7 +947,7 @@ jobs: - name: Build shell: cmd run: | - call "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\vcvars64.bat" + call "%VCVARS_PATH%" mkdir build cd build mkdir release @@ -767,7 +964,7 @@ jobs: - name: List Symbols shell: cmd run: | - call "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\vcvars64.bat" + call "%VCVARS_PATH%" dumpbin.exe /imports build\release\libduckdb_java.so_windows_amd64 dumpbin.exe /exports build\release\libduckdb_java.so_windows_amd64 @@ -775,6 +972,8 @@ jobs: if: ${{ inputs.skip_tests != 'true' }} shell: bash run: | + export PATH="$(cygpath -u "${JAVA_JNI_HOME}")/bin:${PATH}" + which java java -version make test @@ -806,11 +1005,31 @@ jobs: ccache \ -y --force --no-progress - - name: Setup JDK - uses: actions/setup-java@v6 + - name: Check Host Architecture + shell: bash + run: | + # the arm64 binaries are cross-compiled on an amd64 host, with the amd64 tools and with the amd64 JDK + echo "Runner architecture: ${{ runner.arch }}" + test "${{ runner.arch }}" = "X64" + + - name: Find Visual Studio + uses: ./.github/composite-actions/find-visual-studio with: - distribution: corretto - java-version: '8' + vcvars: vcvarsamd64_arm64.bat + + - name: Setup JDK 8 (JNI) + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '8' + env_name: JAVA_JNI_HOME + arch: x64-windows + + - name: Setup JDK 25 (FFM) + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '25' + env_name: JAVA_FFM_HOME + arch: x64-windows - name: Cache Key id: cache_key @@ -829,7 +1048,7 @@ jobs: - name: Build shell: cmd run: | - call "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\vcvarsamd64_arm64.bat" + call "%VCVARS_PATH%" mkdir build cd build mkdir release @@ -846,7 +1065,7 @@ jobs: - name: List Symbols shell: cmd run: | - call "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\vcvarsamd64_arm64.bat" + call "%VCVARS_PATH%" dumpbin.exe /imports build\release\libduckdb_java.so_windows_arm64 dumpbin.exe /exports build\release\libduckdb_java.so_windows_arm64 @@ -854,6 +1073,8 @@ jobs: if: ${{ false && inputs.skip_tests != 'true' }} shell: bash run: | + export PATH="$(cygpath -u "${JAVA_JNI_HOME}")/bin:${PATH}" + which java java -version make test @@ -897,11 +1118,19 @@ jobs: ccache \ ninja - - name: Setup JDK - uses: actions/setup-java@v6 + - name: Setup JDK 8 (JNI) + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '8' + env_name: JAVA_JNI_HOME + arch: aarch64-macos + + - name: Setup JDK 25 (FFM) + uses: ./.github/composite-actions/setup-jdk-corretto with: - distribution: corretto - java-version: '8' + version: '25' + env_name: JAVA_FFM_HOME + arch: aarch64-macos - name: Build shell: bash @@ -932,7 +1161,11 @@ jobs: - name: Java Tests if: ${{ inputs.skip_tests != 'true' }} shell: bash - run: make test + run: | + export PATH="${JAVA_JNI_HOME}/bin:${PATH}" + which java + java -version + make test - uses: actions/upload-artifact@v4 with: @@ -974,12 +1207,19 @@ jobs: ccache \ ninja - - name: Setup JDK - uses: actions/setup-java@v6 + - name: Setup JDK 8 (JNI) + uses: ./.github/composite-actions/setup-jdk-corretto with: - distribution: corretto - java-version: '8' - architecture: x64 + version: '8' + env_name: JAVA_JNI_HOME + arch: x64-macos + + - name: Setup JDK 25 (FFM) + uses: ./.github/composite-actions/setup-jdk-corretto + with: + version: '25' + env_name: JAVA_FFM_HOME + arch: x64-macos - name: Build shell: bash @@ -1011,7 +1251,11 @@ jobs: # disabled: no extensions available for macos_amd64 if: ${{ inputs.skip_tests != 'true' && false }} shell: bash - run: make test + run: | + export PATH="${JAVA_JNI_HOME}/bin:${PATH}" + which java + java -version + make test - uses: actions/upload-artifact@v4 with: diff --git a/.gitignore b/.gitignore index a5c788e89..04485b6b7 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ test1.db /AGENTS.md /CLAUDE.md +/.vscode diff --git a/CMakeLists.txt b/CMakeLists.txt index 9c4ad49ca..218583667 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,25 @@ # Java and JNI +# Two JDKs are used by the build, they can be the same one: +# - JAVA_JNI: JDK 8+, it compiles the driver, the JNI bindings and the tests, and it has the JNI headers of the native +# library. It is the JDK of the JAVA_JNI_HOME environment variable, otherwise the JDK that CMake detects (JAVA_HOME). +# - JAVA_FFM: JDK 25+, it compiles the FFM bindings. It is the JDK of the JAVA_FFM_HOME environment variable, +# otherwise JAVA_JNI. The configuration fails when it is older than JDK 25 or older than JAVA_JNI. +# The class files have the version of the JDK that compiles them: the driver runs on the JDK of JAVA_JNI and later +# ones, it uses the FFM bindings on the JDK of JAVA_FFM and later ones. + +set(JAVA_FFM_MIN_VERSION 25) + +if(NOT "$ENV{JAVA_JNI_HOME}" STREQUAL "") + # JAVA_HOME is the variable that the Java and JNI modules of CMake read + file(TO_CMAKE_PATH "$ENV{JAVA_JNI_HOME}" JAVA_HOME) + if(NOT IS_DIRECTORY "${JAVA_HOME}") + message(FATAL_ERROR "JAVA_JNI_HOME is not a directory: ${JAVA_HOME}") + endif() + # the compiler of the Java language of the project is detected with the environment variable + set(ENV{JAVA_HOME} "${JAVA_HOME}") +endif() + find_package(Java 1.8) set(JAVA_AWT_LIBRARY NotNeeded) @@ -16,11 +36,61 @@ set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") option(ENABLE_ADDRESS_SANITIZER "Enable address sanitizer." FALSE) if(NOT JNI_FOUND OR NOT Java_FOUND) - message(FATAL_ERROR "No compatible Java/JNI found") + message(FATAL_ERROR "JAVA_JNI is not found: set JAVA_JNI_HOME to JDK 8 or later") endif() -if(NOT(Java_VERSION_MAJOR STREQUAL "1" AND Java_VERSION_MINOR STREQUAL "8")) - message(WARNING "JDK ${Java_VERSION} is used to compile the Java part of the driver, resulting binaries will NOT be compatible with JDK 8.") +set(JAVAC_JNI ${Java_JAVAC_EXECUTABLE}) +set(JAR_JNI ${Java_JAR_EXECUTABLE}) +if(Java_VERSION_MAJOR STREQUAL "1") + set(JAVA_JNI_VERSION ${Java_VERSION_MINOR}) +else() + set(JAVA_JNI_VERSION ${Java_VERSION_MAJOR}) +endif() + +if(NOT JAVA_JNI_VERSION EQUAL 8) + message(WARNING "JDK ${Java_VERSION} is used as JAVA_JNI to compile the driver, resulting binaries will NOT be compatible with JDK 8.") +endif() + +# JAVA_FFM_HOME is kept in the cache, so the variable is not required when the build directory is configured again +if(NOT "$ENV{JAVA_FFM_HOME}" STREQUAL "") + file(TO_CMAKE_PATH "$ENV{JAVA_FFM_HOME}" JAVA_FFM_HOME_ENV) + set(JAVA_FFM_HOME "${JAVA_FFM_HOME_ENV}" CACHE PATH "JDK that compiles the FFM bindings" FORCE) +endif() +if(JAVA_FFM_HOME) + set(JAVA_FFM_EXE_SUFFIX "") + if(CMAKE_HOST_WIN32) + set(JAVA_FFM_EXE_SUFFIX ".exe") + endif() + set(JAVAC_FFM "${JAVA_FFM_HOME}/bin/javac${JAVA_FFM_EXE_SUFFIX}") + set(JAR_FFM "${JAVA_FFM_HOME}/bin/jar${JAVA_FFM_EXE_SUFFIX}") + if(NOT EXISTS "${JAVAC_FFM}") + message(FATAL_ERROR "JAVA_FFM_HOME has no Java compiler: ${JAVAC_FFM}") + endif() + # javac prints its version as "javac 25.0.1", JDK 8 prints "javac 1.8.0_472" to stderr + execute_process(COMMAND ${JAVAC_FFM} -version OUTPUT_VARIABLE JAVAC_FFM_VERSION ERROR_VARIABLE JAVAC_FFM_VERSION) + string(STRIP "${JAVAC_FFM_VERSION}" JAVAC_FFM_VERSION) + if(NOT JAVAC_FFM_VERSION MATCHES "javac ([0-9]+)") + message(FATAL_ERROR "Cannot detect the version of the JDK of JAVA_FFM_HOME: '${JAVAC_FFM_VERSION}' (${JAVAC_FFM})") + endif() + set(JAVA_FFM_VERSION ${CMAKE_MATCH_1}) + if(JAVA_FFM_VERSION LESS JAVA_FFM_MIN_VERSION) + message(FATAL_ERROR "JDK ${JAVA_FFM_MIN_VERSION} or later is required as JAVA_FFM to compile the FFM bindings, JAVA_FFM_HOME is '${JAVAC_FFM_VERSION}' (${JAVAC_FFM})") + endif() +else() + set(JAVAC_FFM ${JAVAC_JNI}) + set(JAR_FFM ${JAR_JNI}) + set(JAVA_FFM_VERSION ${JAVA_JNI_VERSION}) + if(JAVA_FFM_VERSION LESS JAVA_FFM_MIN_VERSION) + message(FATAL_ERROR "JDK ${JAVA_FFM_MIN_VERSION} or later is required as JAVA_FFM to compile the FFM bindings, JAVA_JNI is JDK ${Java_VERSION} (${JAVAC_JNI}): set JAVA_FFM_HOME to JDK ${JAVA_FFM_MIN_VERSION} or later") + endif() +endif() + +if(JAVA_FFM_VERSION LESS JAVA_JNI_VERSION) + message(FATAL_ERROR "JAVA_FFM must not be older than JAVA_JNI: JAVA_FFM is JDK ${JAVA_FFM_VERSION} (${JAVAC_FFM}), JAVA_JNI is JDK ${JAVA_JNI_VERSION} (${JAVAC_JNI})") +endif() + +if(JAVA_FFM_VERSION GREATER JAVA_FFM_MIN_VERSION) + message(WARNING "JDK ${JAVA_FFM_VERSION} is used as JAVA_FFM to compile the FFM bindings, resulting binaries will NOT use the FFM bindings on JDK older than ${JAVA_FFM_VERSION}.") endif() include(UseJava) @@ -631,15 +701,39 @@ endif() # Java compilation -file(GLOB_RECURSE JAVA_SRC_FILES src/main/java/org/duckdb/*.java) +# The driver, the JNI bindings and the tests are compiled with JAVA_JNI (add_jar uses the JDK that CMake has detected). +# The jar of the driver is an intermediate one (java_jni/duckdb_jdbc_jni.jar), the FFM bindings are added to its copies +# when the jars are packed. + +file(GLOB_RECURSE JAVA_JNI_SRC_FILES src/main/java/org/duckdb/*.java) file(GLOB_RECURSE JAVA_TEST_FILES src/test/java/org/duckdb/*.java) set(CMAKE_JAVA_COMPILE_FLAGS -encoding utf-8 -g -Xlint:all) +message(STATUS "Driver and JNI bindings are compiled with ${JAVAC_JNI} (JDK ${JAVA_JNI_VERSION})") -add_jar(duckdb_jdbc_nolib ${JAVA_SRC_FILES} META-INF/services/java.sql.Driver +add_jar(duckdb_jdbc_jni ${JAVA_JNI_SRC_FILES} META-INF/services/java.sql.Driver META-INF/native-image/org.duckdb/duckdb_jdbc/reachability-metadata.json MANIFEST META-INF/MANIFEST.MF + OUTPUT_DIR ${CMAKE_CURRENT_BINARY_DIR}/java_jni GENERATE_NATIVE_HEADERS duckdb-native) -add_jar(duckdb_jdbc_tests ${JAVA_TEST_FILES} INCLUDE_JARS duckdb_jdbc_nolib) +get_target_property(JAVA_JNI_JAR duckdb_jdbc_jni JAR_FILE) +add_jar(duckdb_jdbc_tests ${JAVA_TEST_FILES} INCLUDE_JARS duckdb_jdbc_jni) + +# Implementation of the bindings for the JDK of JAVA_FFM and later ones: the C API of the native library is called +# directly with the Foreign Function and Memory API, without JNI. The classes are compiled with JAVA_FFM and are packed +# into the multi-release jars as META-INF/versions/, older JDKs use JNI. + +file(GLOB_RECURSE JAVA_FFM_SRC_FILES src/main/java22/org/duckdb/*.java) +message(STATUS "FFM bindings are compiled with ${JAVAC_FFM} (JDK ${JAVA_FFM_VERSION})") + +add_custom_command( + OUTPUT java_ffm/classes.stamp + DEPENDS duckdb_jdbc_jni ${JAVA_JNI_JAR} ${JAVA_FFM_SRC_FILES} + COMMAND ${CMAKE_COMMAND} -E remove_directory java_ffm/classes + COMMAND ${CMAKE_COMMAND} -E make_directory java_ffm/classes + COMMAND ${JAVAC_FFM} -encoding utf-8 -g -Xlint:-restricted,-try -cp ${JAVA_JNI_JAR} -d java_ffm/classes + ${JAVA_FFM_SRC_FILES} + COMMAND ${CMAKE_COMMAND} -E touch java_ffm/classes.stamp) +add_custom_target(duckdb_jdbc_ffm DEPENDS java_ffm/classes.stamp) # main shared lib compilation @@ -764,13 +858,21 @@ set_target_properties(duckdb_java PROPERTIES PREFIX "lib") # JAR packing +# duckdb_jdbc_nolib.jar: the driver without the native library +# duckdb_jdbc.jar: the driver with the native library +# Both are multi-release jars, the FFM bindings are added to them as the classes of the version of JAVA_FFM. + add_custom_command( OUTPUT dummy_jdbc_target - DEPENDS duckdb_java duckdb_jdbc_nolib duckdb_jdbc_tests + DEPENDS duckdb_java duckdb_jdbc_jni duckdb_jdbc_tests duckdb_jdbc_ffm + COMMAND ${CMAKE_COMMAND} -E copy + ${JAVA_JNI_JAR} + duckdb_jdbc_nolib.jar + COMMAND ${JAR_FFM} uf duckdb_jdbc_nolib.jar --release ${JAVA_FFM_VERSION} -C java_ffm/classes . COMMAND ${CMAKE_COMMAND} -E copy duckdb_jdbc_nolib.jar duckdb_jdbc.jar - COMMAND ${Java_JAR_EXECUTABLE} uf duckdb_jdbc.jar -C + COMMAND ${JAR_JNI} uf duckdb_jdbc.jar -C $ $) add_custom_target(jdbc ALL DEPENDS dummy_jdbc_target) diff --git a/CMakeLists.txt.in b/CMakeLists.txt.in index fb0c3d761..8f7b96c6e 100644 --- a/CMakeLists.txt.in +++ b/CMakeLists.txt.in @@ -1,5 +1,25 @@ # Java and JNI +# Two JDKs are used by the build, they can be the same one: +# - JAVA_JNI: JDK 8+, it compiles the driver, the JNI bindings and the tests, and it has the JNI headers of the native +# library. It is the JDK of the JAVA_JNI_HOME environment variable, otherwise the JDK that CMake detects (JAVA_HOME). +# - JAVA_FFM: JDK 25+, it compiles the FFM bindings. It is the JDK of the JAVA_FFM_HOME environment variable, +# otherwise JAVA_JNI. The configuration fails when it is older than JDK 25 or older than JAVA_JNI. +# The class files have the version of the JDK that compiles them: the driver runs on the JDK of JAVA_JNI and later +# ones, it uses the FFM bindings on the JDK of JAVA_FFM and later ones. + +set(JAVA_FFM_MIN_VERSION 25) + +if(NOT "$ENV{JAVA_JNI_HOME}" STREQUAL "") + # JAVA_HOME is the variable that the Java and JNI modules of CMake read + file(TO_CMAKE_PATH "$ENV{JAVA_JNI_HOME}" JAVA_HOME) + if(NOT IS_DIRECTORY "${JAVA_HOME}") + message(FATAL_ERROR "JAVA_JNI_HOME is not a directory: ${JAVA_HOME}") + endif() + # the compiler of the Java language of the project is detected with the environment variable + set(ENV{JAVA_HOME} "${JAVA_HOME}") +endif() + find_package(Java 1.8) set(JAVA_AWT_LIBRARY NotNeeded) @@ -16,11 +36,61 @@ set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") option(ENABLE_ADDRESS_SANITIZER "Enable address sanitizer." FALSE) if(NOT JNI_FOUND OR NOT Java_FOUND) - message(FATAL_ERROR "No compatible Java/JNI found") + message(FATAL_ERROR "JAVA_JNI is not found: set JAVA_JNI_HOME to JDK 8 or later") endif() -if(NOT(Java_VERSION_MAJOR STREQUAL "1" AND Java_VERSION_MINOR STREQUAL "8")) - message(WARNING "JDK ${Java_VERSION} is used to compile the Java part of the driver, resulting binaries will NOT be compatible with JDK 8.") +set(JAVAC_JNI ${Java_JAVAC_EXECUTABLE}) +set(JAR_JNI ${Java_JAR_EXECUTABLE}) +if(Java_VERSION_MAJOR STREQUAL "1") + set(JAVA_JNI_VERSION ${Java_VERSION_MINOR}) +else() + set(JAVA_JNI_VERSION ${Java_VERSION_MAJOR}) +endif() + +if(NOT JAVA_JNI_VERSION EQUAL 8) + message(WARNING "JDK ${Java_VERSION} is used as JAVA_JNI to compile the driver, resulting binaries will NOT be compatible with JDK 8.") +endif() + +# JAVA_FFM_HOME is kept in the cache, so the variable is not required when the build directory is configured again +if(NOT "$ENV{JAVA_FFM_HOME}" STREQUAL "") + file(TO_CMAKE_PATH "$ENV{JAVA_FFM_HOME}" JAVA_FFM_HOME_ENV) + set(JAVA_FFM_HOME "${JAVA_FFM_HOME_ENV}" CACHE PATH "JDK that compiles the FFM bindings" FORCE) +endif() +if(JAVA_FFM_HOME) + set(JAVA_FFM_EXE_SUFFIX "") + if(CMAKE_HOST_WIN32) + set(JAVA_FFM_EXE_SUFFIX ".exe") + endif() + set(JAVAC_FFM "${JAVA_FFM_HOME}/bin/javac${JAVA_FFM_EXE_SUFFIX}") + set(JAR_FFM "${JAVA_FFM_HOME}/bin/jar${JAVA_FFM_EXE_SUFFIX}") + if(NOT EXISTS "${JAVAC_FFM}") + message(FATAL_ERROR "JAVA_FFM_HOME has no Java compiler: ${JAVAC_FFM}") + endif() + # javac prints its version as "javac 25.0.1", JDK 8 prints "javac 1.8.0_472" to stderr + execute_process(COMMAND ${JAVAC_FFM} -version OUTPUT_VARIABLE JAVAC_FFM_VERSION ERROR_VARIABLE JAVAC_FFM_VERSION) + string(STRIP "${JAVAC_FFM_VERSION}" JAVAC_FFM_VERSION) + if(NOT JAVAC_FFM_VERSION MATCHES "javac ([0-9]+)") + message(FATAL_ERROR "Cannot detect the version of the JDK of JAVA_FFM_HOME: '${JAVAC_FFM_VERSION}' (${JAVAC_FFM})") + endif() + set(JAVA_FFM_VERSION ${CMAKE_MATCH_1}) + if(JAVA_FFM_VERSION LESS JAVA_FFM_MIN_VERSION) + message(FATAL_ERROR "JDK ${JAVA_FFM_MIN_VERSION} or later is required as JAVA_FFM to compile the FFM bindings, JAVA_FFM_HOME is '${JAVAC_FFM_VERSION}' (${JAVAC_FFM})") + endif() +else() + set(JAVAC_FFM ${JAVAC_JNI}) + set(JAR_FFM ${JAR_JNI}) + set(JAVA_FFM_VERSION ${JAVA_JNI_VERSION}) + if(JAVA_FFM_VERSION LESS JAVA_FFM_MIN_VERSION) + message(FATAL_ERROR "JDK ${JAVA_FFM_MIN_VERSION} or later is required as JAVA_FFM to compile the FFM bindings, JAVA_JNI is JDK ${Java_VERSION} (${JAVAC_JNI}): set JAVA_FFM_HOME to JDK ${JAVA_FFM_MIN_VERSION} or later") + endif() +endif() + +if(JAVA_FFM_VERSION LESS JAVA_JNI_VERSION) + message(FATAL_ERROR "JAVA_FFM must not be older than JAVA_JNI: JAVA_FFM is JDK ${JAVA_FFM_VERSION} (${JAVAC_FFM}), JAVA_JNI is JDK ${JAVA_JNI_VERSION} (${JAVAC_JNI})") +endif() + +if(JAVA_FFM_VERSION GREATER JAVA_FFM_MIN_VERSION) + message(WARNING "JDK ${JAVA_FFM_VERSION} is used as JAVA_FFM to compile the FFM bindings, resulting binaries will NOT use the FFM bindings on JDK older than ${JAVA_FFM_VERSION}.") endif() include(UseJava) @@ -107,15 +177,39 @@ endif() # Java compilation -file(GLOB_RECURSE JAVA_SRC_FILES src/main/java/org/duckdb/*.java) +# The driver, the JNI bindings and the tests are compiled with JAVA_JNI (add_jar uses the JDK that CMake has detected). +# The jar of the driver is an intermediate one (java_jni/duckdb_jdbc_jni.jar), the FFM bindings are added to its copies +# when the jars are packed. + +file(GLOB_RECURSE JAVA_JNI_SRC_FILES src/main/java/org/duckdb/*.java) file(GLOB_RECURSE JAVA_TEST_FILES src/test/java/org/duckdb/*.java) set(CMAKE_JAVA_COMPILE_FLAGS -encoding utf-8 -g -Xlint:all) +message(STATUS "Driver and JNI bindings are compiled with ${JAVAC_JNI} (JDK ${JAVA_JNI_VERSION})") -add_jar(duckdb_jdbc_nolib ${JAVA_SRC_FILES} META-INF/services/java.sql.Driver +add_jar(duckdb_jdbc_jni ${JAVA_JNI_SRC_FILES} META-INF/services/java.sql.Driver META-INF/native-image/org.duckdb/duckdb_jdbc/reachability-metadata.json MANIFEST META-INF/MANIFEST.MF + OUTPUT_DIR ${CMAKE_CURRENT_BINARY_DIR}/java_jni GENERATE_NATIVE_HEADERS duckdb-native) -add_jar(duckdb_jdbc_tests ${JAVA_TEST_FILES} INCLUDE_JARS duckdb_jdbc_nolib) +get_target_property(JAVA_JNI_JAR duckdb_jdbc_jni JAR_FILE) +add_jar(duckdb_jdbc_tests ${JAVA_TEST_FILES} INCLUDE_JARS duckdb_jdbc_jni) + +# Implementation of the bindings for the JDK of JAVA_FFM and later ones: the C API of the native library is called +# directly with the Foreign Function and Memory API, without JNI. The classes are compiled with JAVA_FFM and are packed +# into the multi-release jars as META-INF/versions/, older JDKs use JNI. + +file(GLOB_RECURSE JAVA_FFM_SRC_FILES src/main/java22/org/duckdb/*.java) +message(STATUS "FFM bindings are compiled with ${JAVAC_FFM} (JDK ${JAVA_FFM_VERSION})") + +add_custom_command( + OUTPUT java_ffm/classes.stamp + DEPENDS duckdb_jdbc_jni ${JAVA_JNI_JAR} ${JAVA_FFM_SRC_FILES} + COMMAND ${CMAKE_COMMAND} -E remove_directory java_ffm/classes + COMMAND ${CMAKE_COMMAND} -E make_directory java_ffm/classes + COMMAND ${JAVAC_FFM} -encoding utf-8 -g -Xlint:-restricted,-try -cp ${JAVA_JNI_JAR} -d java_ffm/classes + ${JAVA_FFM_SRC_FILES} + COMMAND ${CMAKE_COMMAND} -E touch java_ffm/classes.stamp) +add_custom_target(duckdb_jdbc_ffm DEPENDS java_ffm/classes.stamp) # main shared lib compilation @@ -240,13 +334,21 @@ set_target_properties(duckdb_java PROPERTIES PREFIX "lib") # JAR packing +# duckdb_jdbc_nolib.jar: the driver without the native library +# duckdb_jdbc.jar: the driver with the native library +# Both are multi-release jars, the FFM bindings are added to them as the classes of the version of JAVA_FFM. + add_custom_command( OUTPUT dummy_jdbc_target - DEPENDS duckdb_java duckdb_jdbc_nolib duckdb_jdbc_tests + DEPENDS duckdb_java duckdb_jdbc_jni duckdb_jdbc_tests duckdb_jdbc_ffm + COMMAND ${CMAKE_COMMAND} -E copy + ${JAVA_JNI_JAR} + duckdb_jdbc_nolib.jar + COMMAND ${JAR_FFM} uf duckdb_jdbc_nolib.jar --release ${JAVA_FFM_VERSION} -C java_ffm/classes . COMMAND ${CMAKE_COMMAND} -E copy duckdb_jdbc_nolib.jar duckdb_jdbc.jar - COMMAND ${Java_JAR_EXECUTABLE} uf duckdb_jdbc.jar -C + COMMAND ${JAR_JNI} uf duckdb_jdbc.jar -C $ $) 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/META-INF/native-image/org.duckdb/duckdb_jdbc/reachability-metadata.json b/META-INF/native-image/org.duckdb/duckdb_jdbc/reachability-metadata.json index 6d08d4ade..120a63810 100644 --- a/META-INF/native-image/org.duckdb/duckdb_jdbc/reachability-metadata.json +++ b/META-INF/native-image/org.duckdb/duckdb_jdbc/reachability-metadata.json @@ -602,6 +602,857 @@ { "type": "java.lang.RuntimeException", "jniAccessible": true + }, + { + "type": "org.duckdb.FfmArrow", + "methods": [ + { + "name": "exportGetLastError", + "parameterTypes": [ + "java.lang.foreign.MemorySegment" + ] + }, + { + "name": "exportGetNext", + "parameterTypes": [ + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment" + ] + }, + { + "name": "exportGetSchema", + "parameterTypes": [ + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment" + ] + }, + { + "name": "exportRelease", + "parameterTypes": [ + "java.lang.foreign.MemorySegment" + ] + }, + { + "name": "resultScanBind", + "parameterTypes": [ + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment" + ] + }, + { + "name": "resultScanExec", + "parameterTypes": [ + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment" + ] + }, + { + "name": "resultScanInitGlobal", + "parameterTypes": [ + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment" + ] + }, + { + "name": "scanBind", + "parameterTypes": [ + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment" + ] + }, + { + "name": "scanExec", + "parameterTypes": [ + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment" + ] + }, + { + "name": "scanInitGlobal", + "parameterTypes": [ + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment" + ] + } + ] + }, + { + "type": "org.duckdb.FfmFunctions", + "methods": [ + { + "name": "destroyObject", + "parameterTypes": [ + "java.lang.foreign.MemorySegment" + ] + }, + { + "name": "scalarExec", + "parameterTypes": [ + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment" + ] + }, + { + "name": "scalarInit", + "parameterTypes": [ + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment" + ] + }, + { + "name": "tableBind", + "parameterTypes": [ + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment" + ] + }, + { + "name": "tableExec", + "parameterTypes": [ + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment" + ] + }, + { + "name": "tableInitGlobal", + "parameterTypes": [ + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment" + ] + }, + { + "name": "tableInitLocal", + "parameterTypes": [ + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment" + ] + } + ] + }, + { + "type": "org.duckdb.FfmV2", + "methods": [ + { + "name": "cacheCreate", + "parameterTypes": [ + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment" + ] + }, + { + "name": "instanceInit", + "parameterTypes": [ + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment" + ] + }, + { + "name": "textSink", + "parameterTypes": [ + "java.lang.foreign.MemorySegment", + "long", + "java.lang.foreign.MemorySegment", + "java.lang.foreign.MemorySegment" + ] + } + ] } - ] + ], + "foreign": { + "downcalls": [ + { + "returnType": "void*", + "parameterTypes": [ + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*" + ] + }, + { + "returnType": "void", + "parameterTypes": [ + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "jint" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "jlong" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "jboolean", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "jint", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "jlong", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "jlong", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "jboolean", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "jbyte", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "jdouble", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "jfloat", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "jint", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "jint", + "jboolean", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "jint", + "jint", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "jlong", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "jlong", + "jboolean", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "jshort", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "void*", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "jboolean", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "jboolean", + "jboolean", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "jlong", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "jlong", + "void*", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "void*", + "void*", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "void*", + "jlong", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "jint", + "jint", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "jlong", + "void*", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "jlong", + "void*", + "jint", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "jlong", + "jboolean", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "jlong", + "void*", + "void*", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "void*", + "void*", + "jlong", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "void*", + "jint", + "void*", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "jlong", + "void*", + "void*", + "jint", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "jlong", + "void*", + "jlong", + "jint", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "jlong", + "void*", + "jlong", + "void*", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "jlong", + "jboolean", + "void*", + "jlong", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "void*", + "void*", + "void*", + "jlong", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "jlong", + "void*", + "void*", + "void*", + "jlong", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "jlong", + "void*", + "jlong", + "void*", + "jboolean", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "jint", + "void*", + "void*", + "void*", + "jlong", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "void*", + "void*", + "void*", + "jlong", + "jlong", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "jlong", + "void*", + "jlong", + "void*", + "void*", + "void*", + "void*" + ] + }, + { + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*", + "jlong", + "void*", + "void*", + "void*", + "void*", + "jlong", + "void*", + "void*", + "void*", + "void*" + ] + } + ], + "directUpcalls": [ + { + "class": "org.duckdb.FfmArrow", + "method": "exportGetLastError", + "returnType": "void*", + "parameterTypes": [ + "void*" + ] + }, + { + "class": "org.duckdb.FfmArrow", + "method": "exportGetNext", + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*" + ] + }, + { + "class": "org.duckdb.FfmArrow", + "method": "exportGetSchema", + "returnType": "jint", + "parameterTypes": [ + "void*", + "void*" + ] + }, + { + "class": "org.duckdb.FfmArrow", + "method": "exportRelease", + "returnType": "void", + "parameterTypes": [ + "void*" + ] + }, + { + "class": "org.duckdb.FfmArrow", + "method": "resultScanBind", + "returnType": "void", + "parameterTypes": [ + "void*", + "void*", + "void*", + "void*" + ] + }, + { + "class": "org.duckdb.FfmArrow", + "method": "resultScanExec", + "returnType": "void", + "parameterTypes": [ + "void*", + "void*", + "void*" + ] + }, + { + "class": "org.duckdb.FfmArrow", + "method": "resultScanInitGlobal", + "returnType": "void", + "parameterTypes": [ + "void*", + "void*", + "void*" + ] + }, + { + "class": "org.duckdb.FfmArrow", + "method": "scanBind", + "returnType": "void", + "parameterTypes": [ + "void*", + "void*", + "void*", + "void*" + ] + }, + { + "class": "org.duckdb.FfmArrow", + "method": "scanExec", + "returnType": "void", + "parameterTypes": [ + "void*", + "void*", + "void*" + ] + }, + { + "class": "org.duckdb.FfmArrow", + "method": "scanInitGlobal", + "returnType": "void", + "parameterTypes": [ + "void*", + "void*", + "void*" + ] + }, + { + "class": "org.duckdb.FfmFunctions", + "method": "destroyObject", + "returnType": "void", + "parameterTypes": [ + "void*" + ] + }, + { + "class": "org.duckdb.FfmFunctions", + "method": "scalarExec", + "returnType": "void", + "parameterTypes": [ + "void*", + "void*", + "void*" + ] + }, + { + "class": "org.duckdb.FfmFunctions", + "method": "scalarInit", + "returnType": "void", + "parameterTypes": [ + "void*", + "void*", + "void*" + ] + }, + { + "class": "org.duckdb.FfmFunctions", + "method": "tableBind", + "returnType": "void", + "parameterTypes": [ + "void*", + "void*", + "void*", + "void*" + ] + }, + { + "class": "org.duckdb.FfmFunctions", + "method": "tableExec", + "returnType": "void", + "parameterTypes": [ + "void*", + "void*", + "void*" + ] + }, + { + "class": "org.duckdb.FfmFunctions", + "method": "tableInitGlobal", + "returnType": "void", + "parameterTypes": [ + "void*", + "void*", + "void*" + ] + }, + { + "class": "org.duckdb.FfmFunctions", + "method": "tableInitLocal", + "returnType": "void", + "parameterTypes": [ + "void*", + "void*", + "void*" + ] + }, + { + "class": "org.duckdb.FfmV2", + "method": "cacheCreate", + "returnType": "void", + "parameterTypes": [ + "void*", + "void*", + "void*", + "void*" + ] + }, + { + "class": "org.duckdb.FfmV2", + "method": "instanceInit", + "returnType": "void", + "parameterTypes": [ + "void*", + "void*", + "void*" + ] + }, + { + "class": "org.duckdb.FfmV2", + "method": "textSink", + "returnType": "void", + "parameterTypes": [ + "void*", + "jlong", + "void*", + "void*" + ] + } + ] + } } \ No newline at end of file diff --git a/README.md b/README.md index 442947117..3fb4446ff 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,13 @@ -It's required to have a JDK installed to build. -Make sure the `JAVA_HOME` environment variable is set. +Two JDKs are used by the build, they can be the same one: + +- `JAVA_JNI` (JDK 8 or later) compiles the driver, the JNI bindings and the tests. It is the JDK in the + `JAVA_JNI_HOME` environment variable, otherwise the JDK that CMake detects (`JAVA_HOME`). +- `JAVA_FFM` (JDK 25 or later) compiles the FFM bindings. It is the JDK in the `JAVA_FFM_HOME` environment variable, + otherwise `JAVA_JNI`. The build fails to configure when it is older than JDK 25 or older than `JAVA_JNI`. + +The class files have the version of the JDK that compiles them: the driver runs on the JDK of `JAVA_JNI` and later +ones, and it uses the FFM bindings on the JDK of `JAVA_FFM` and later ones. Release builds use JDK 8 and JDK 25, CMake +warns about other versions. ### Development @@ -31,3 +39,27 @@ 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 25+ (Foreign Function and Memory API) + +Both `duckdb_jdbc.jar` and `duckdb_jdbc_nolib.jar` are multi-release jars. On Java 25 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. `-Djdk.util.jar.enableMultiRelease=false` makes Java 25 and later use the JNI bindings too. + +The classes of the FFM bindings are in `src/main/java22`. They are compiled with `JAVA_FFM` (see above) and are packed +as `META-INF/versions/`, that is `META-INF/versions/25` in release builds. The rest of the driver +is compiled with `JAVA_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`. + +GraalVM Native Image: an image that is built with GraalVM for JDK 25 or later uses the FFM bindings. Their foreign +calls are registered in the Native Image metadata of the driver +(`META-INF/native-image/org.duckdb/duckdb_jdbc/reachability-metadata.json`), `scripts/gen_ffm_native.py` generates +these registrations too. To build an image with the JNI bindings pass `-J-Djdk.util.jar.enableMultiRelease=false` to +`native-image`. diff --git a/scripts/gen_ffm_bindings.py b/scripts/gen_ffm_bindings.py new file mode 100644 index 000000000..7d9fae351 --- /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|' + r'register_result|release_result)', '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_.*|bignum_.*)', '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..962452f82 --- /dev/null +++ b/scripts/gen_ffm_native.py @@ -0,0 +1,232 @@ +#!/usr/bin/env python3 +"""Generates the files of the FFM implementation of the bindings (java.lang.foreign, JDK 22+) that depend on the +functions that it calls: + +- src/main/java22/org/duckdb/Capi.java: the downcall handles of the C API v2 functions. A function is generated if it + is called as `Capi.(` or is referenced as `Capi::` in the Java sources of src/main/java22. +- the registrations of the foreign calls in the GraalVM Native Image metadata of the driver + (META-INF/native-image/org.duckdb/duckdb_jdbc/reachability-metadata.json): the downcalls (the functions of Capi.java + and the calls of the function pointers), the upcalls (the callbacks that are passed to the native library) and the + reflective access to the methods of the callbacks. The registrations of the JNI bindings in that file are not + changed. + +Usage: python3 scripts/gen_ffm_native.py +""" +import glob +import json +import re +import sys + +HEADER = 'src/duckdb/src/include/duckdb_v2.h' +JAVA_FFM_DIR = 'src/main/java22/org/duckdb' +OUT = JAVA_FFM_DIR + '/Capi.java' +METADATA = 'META-INF/native-image/org.duckdb/duckdb_jdbc/reachability-metadata.json' + +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(JAVA_FFM_DIR + '/*.java'): + if f == OUT: + continue + text = open(f).read() + used |= set(re.findall(r'\bCapi\.(duckdb_v2_[a-z0-9_]+)\(', text)) + # method references + used |= set(re.findall(r'\bCapi::(duckdb_v2_[a-z0-9_]+)\b', text)) + +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) + + +# --------------------------------------------------------------------------------------------------------------------- +# GraalVM Native Image metadata: the foreign calls must be registered when the image is built +# --------------------------------------------------------------------------------------------------------------------- + +# the names of the memory layouts in the metadata and the Java types of the callback parameters +GRAAL_TYPES = { + 'ADDRESS': ('void*', 'java.lang.foreign.MemorySegment'), + 'JAVA_BOOLEAN': ('jboolean', 'boolean'), + 'JAVA_BYTE': ('jbyte', 'byte'), + 'JAVA_SHORT': ('jshort', 'short'), + 'JAVA_INT': ('jint', 'int'), + 'JAVA_LONG': ('jlong', 'long'), + 'JAVA_FLOAT': ('jfloat', 'float'), + 'JAVA_DOUBLE': ('jdouble', 'double'), +} + + +def descriptor(kind, layouts): + """The layouts of FunctionDescriptor.of(...) or FunctionDescriptor.ofVoid(...): (return layout, parameters).""" + names = [l.strip() for l in layouts.split(',') if l.strip()] + unknown = [l for l in names if l not in GRAAL_TYPES] + if unknown: + print('Unknown layouts:', unknown) + sys.exit(1) + if kind == 'ofVoid': + return None, names + return names[0], names[1:] + + +def graal_call(ret, params): + return {'returnType': GRAAL_TYPES[ret][0] if ret else 'void', 'parameterTypes': [GRAAL_TYPES[p][0] for p in params]} + + +FD = r'FunctionDescriptor\.(of|ofVoid)\(([^()]*)\)' +downcalls = set() +upcalls = [] +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): + continue + downcalls.add((rl, tuple(l for _, l in jtypes))) +for f in sorted(glob.glob(JAVA_FFM_DIR + '/*.java')): + if f == OUT: + continue + text = open(f).read() + cls = re.search(r'^(?:final |public )*class (\w+)', text, re.M).group(1) + # the calls of the function pointers + for m in re.finditer(r'downcallHandle\(\s*' + FD + r'\)', text): + ret, params = descriptor(m.group(1), m.group(2)) + downcalls.add((ret, tuple(params))) + # the callbacks: the stubs that are created with the helper of the class, and the ones that are created in place + found = [] + for m in re.finditer(r'\bstub\(\s*"(\w+)",\s*' + FD, text): + found.append((m.group(1),) + descriptor(m.group(2), m.group(3))) + in_place = list(re.finditer(r'findStatic\(\s*\w+\.class,\s*"(\w+)",.*?upcallStub\(\s*target,\s*' + FD, text, re.S)) + for m in in_place: + found.append((m.group(1),) + descriptor(m.group(2), m.group(3))) + # every upcall stub of the class must be found: the helper has one upcallStub call, the other ones are in place + helper = 1 if re.search(r'\bMemorySegment stub\(String name', text) else 0 + if len(re.findall(r'upcallStub\(', text)) != helper + len(in_place): + print('Not all the upcall stubs are found in', f) + sys.exit(1) + for method, ret, params in found: + upcalls.append(('org.duckdb.' + cls, method, ret, params)) + +metadata = json.loads(open(METADATA).read()) +# the reflective access to the callbacks, they are looked up with MethodHandles.Lookup#findStatic +reflection = [e for e in metadata['reflection'] if not e['type'].startswith('org.duckdb.Ffm')] +for cls in sorted(set(u[0] for u in upcalls)): + methods = [{'name': method, 'parameterTypes': [GRAAL_TYPES[p][1] for p in params]} + for c, method, ret, params in sorted(upcalls) if c == cls] + reflection.append({'type': cls, 'methods': methods}) +metadata['reflection'] = reflection +metadata['foreign'] = { + 'downcalls': [graal_call(ret, params) for ret, params in sorted(downcalls, key=lambda d: (len(d[1]), str(d)))], + 'directUpcalls': [dict({'class': cls, 'method': method}, **graal_call(ret, params)) + for cls, method, ret, params in sorted(upcalls)], +} +open(METADATA, 'w').write(json.dumps(metadata, indent=2)) +print('registered', len(downcalls), 'downcall descriptors and', len(upcalls), 'upcalls in the native image metadata') 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/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 aeddffb80..0c15db2ee 100644 --- a/src/main/java/org/duckdb/DuckDBNative.java +++ b/src/main/java/org/duckdb/DuckDBNative.java @@ -20,118 +20,10 @@ 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); - } - } - - private static void loadNativeLibrary() throws Exception { - String libName = nativeLibName(); - URL libRes = DuckDBNative.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_\\-.]", ""); - } + DuckDBLibrary.load(); } - 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 = 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(); - } - - 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 - */ - // The statements, queries and results are implemented in Java on top of the C API v2 entry points of // DuckDBBindings, see DuckDBCore diff --git a/src/main/java22/org/duckdb/Capi.java b/src/main/java22/org/duckdb/Capi.java new file mode 100644 index 000000000..0d4117556 --- /dev/null +++ b/src/main/java22/org/duckdb/Capi.java @@ -0,0 +1,3220 @@ +// 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_bignum_decode { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_bignum_decode", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, + JAVA_LONG, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_bignum_decode(MemorySegment a0, long a1, MemorySegment a2, long a3, MemorySegment a4, + MemorySegment a5, MemorySegment a6) { + try { + return (int) H_duckdb_v2_bignum_decode.MH.invokeExact(a0, a1, a2, a3, a4, a5, a6); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_bignum_encode { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_bignum_encode", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, JAVA_BOOLEAN, + ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_bignum_encode(MemorySegment a0, long a1, boolean a2, MemorySegment a3, long a4, + MemorySegment a5, MemorySegment a6) { + try { + return (int) H_duckdb_v2_bignum_encode.MH.invokeExact(a0, a1, a2, a3, a4, a5, a6); + } 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_column_description_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_column_description_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_column_description_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_column_description_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_column_description_get_name { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_column_description_get_name", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_column_description_get_name(MemorySegment a0, MemorySegment a1, MemorySegment a2, + MemorySegment a3) { + try { + return (int) H_duckdb_v2_column_description_get_name.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_column_description_get_type { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_column_description_get_type", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_column_description_get_type(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_column_description_get_type.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_column_description_has_default { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_column_description_has_default", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_column_description_has_default(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_column_description_has_default.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_column_description_has_generated { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_column_description_has_generated", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_column_description_has_generated(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_column_description_has_generated.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_describe_table { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_connection_describe_table", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_connection_describe_table(MemorySegment a0, MemorySegment a1, MemorySegment a2, + MemorySegment a3) { + try { + return (int) H_duckdb_v2_connection_describe_table.MH.invokeExact(a0, a1, a2, a3); + } 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_data_source_create { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_data_source_create", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_source_create(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_data_source_create.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_source_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_data_source_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_data_source_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_data_source_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_source_exec_get_bind_data { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_data_source_exec_get_bind_data", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_source_exec_get_bind_data(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_data_source_exec_get_bind_data.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_source_exec_get_global_state { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_data_source_exec_get_global_state", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_source_exec_get_global_state(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_data_source_exec_get_global_state.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_source_exec_get_local_state { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_data_source_exec_get_local_state", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_source_exec_get_local_state(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_data_source_exec_get_local_state.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_source_exec_get_output_chunk { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_data_source_exec_get_output_chunk", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_source_exec_get_output_chunk(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_data_source_exec_get_output_chunk.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_source_exec_get_user_data { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_data_source_exec_get_user_data", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_source_exec_get_user_data(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_data_source_exec_get_user_data.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_source_init_global_get_bind_data { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_data_source_init_global_get_bind_data", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_source_init_global_get_bind_data(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_data_source_init_global_get_bind_data.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_source_init_global_get_column_count { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_data_source_init_global_get_column_count", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_source_init_global_get_column_count(MemorySegment a0, MemorySegment a1, + MemorySegment a2) { + try { + return (int) H_duckdb_v2_data_source_init_global_get_column_count.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_source_init_global_get_column_index { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_data_source_init_global_get_column_index", + FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_source_init_global_get_column_index(MemorySegment a0, long a1, MemorySegment a2, + MemorySegment a3) { + try { + return (int) H_duckdb_v2_data_source_init_global_get_column_index.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_source_init_global_get_user_data { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_data_source_init_global_get_user_data", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_source_init_global_get_user_data(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_data_source_init_global_get_user_data.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_source_init_global_set_global_state { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_data_source_init_global_set_global_state", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_source_init_global_set_global_state(MemorySegment a0, MemorySegment a1, + MemorySegment a2) { + try { + return (int) H_duckdb_v2_data_source_init_global_set_global_state.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_source_init_global_set_max_threads { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_data_source_init_global_set_max_threads", + FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS)); + } + + static int duckdb_v2_data_source_init_global_set_max_threads(MemorySegment a0, long a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_data_source_init_global_set_max_threads.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_source_init_local_get_bind_data { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_data_source_init_local_get_bind_data", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_source_init_local_get_bind_data(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_data_source_init_local_get_bind_data.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_source_init_local_get_column_count { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_data_source_init_local_get_column_count", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_source_init_local_get_column_count(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_data_source_init_local_get_column_count.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_source_init_local_get_column_index { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_data_source_init_local_get_column_index", + FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_source_init_local_get_column_index(MemorySegment a0, long a1, MemorySegment a2, + MemorySegment a3) { + try { + return (int) H_duckdb_v2_data_source_init_local_get_column_index.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_source_init_local_get_user_data { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_data_source_init_local_get_user_data", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_source_init_local_get_user_data(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_data_source_init_local_get_user_data.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_source_init_local_set_local_state { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_data_source_init_local_set_local_state", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_source_init_local_set_local_state(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_data_source_init_local_set_local_state.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_source_set_exec_callback { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_data_source_set_exec_callback", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_source_set_exec_callback(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_data_source_set_exec_callback.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_source_set_init_global_callback { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_data_source_set_init_global_callback", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_source_set_init_global_callback(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_data_source_set_init_global_callback.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_data_source_set_init_local_callback { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_data_source_set_init_local_callback", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_data_source_set_init_local_callback(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_data_source_set_init_local_callback.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_get_object_cache { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_instance_get_object_cache", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_instance_get_object_cache(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_instance_get_object_cache.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_object_cache_entry_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_object_cache_entry_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_object_cache_entry_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_object_cache_entry_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_object_cache_entry_get_data { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_object_cache_entry_get_data", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_object_cache_entry_get_data(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_object_cache_entry_get_data.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_object_cache_get_or_create { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_object_cache_get_or_create", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, JAVA_LONG, ADDRESS, + ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_object_cache_get_or_create(MemorySegment a0, MemorySegment a1, long a2, MemorySegment a3, + long a4, MemorySegment a5, MemorySegment a6, MemorySegment a7, + MemorySegment a8) { + try { + return (int) H_duckdb_v2_object_cache_get_or_create.MH.invokeExact(a0, a1, a2, a3, a4, a5, a6, a7, a8); + } 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_qname_create { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_qname_create", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_qname_create(MemorySegment a0, MemorySegment a1, long a2, MemorySegment a3, MemorySegment a4) { + try { + return (int) H_duckdb_v2_qname_create.MH.invokeExact(a0, a1, a2, a3, a4); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_qname_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_qname_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_qname_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_qname_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_qname_get_part { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_qname_get_part", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_qname_get_part(MemorySegment a0, long a1, MemorySegment a2, MemorySegment a3, + MemorySegment a4) { + try { + return (int) H_duckdb_v2_qname_get_part.MH.invokeExact(a0, a1, a2, a3, a4); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_qname_get_part_count { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_qname_get_part_count", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_qname_get_part_count(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_qname_get_part_count.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_qname_render { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_qname_render", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_qname_render(MemorySegment a0, MemorySegment a1, long a2, MemorySegment a3, MemorySegment a4) { + try { + return (int) H_duckdb_v2_qname_render.MH.invokeExact(a0, a1, a2, a3, a4); + } 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_description_destroy { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_table_description_destroy", FunctionDescriptor.of(JAVA_INT, ADDRESS)); + } + + static int duckdb_v2_table_description_destroy(MemorySegment a0) { + try { + return (int) H_duckdb_v2_table_description_destroy.MH.invokeExact(a0); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_description_get_column { + static final MethodHandle MH = + Ffm.downcall("duckdb_v2_table_description_get_column", + FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_description_get_column(MemorySegment a0, long a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_table_description_get_column.MH.invokeExact(a0, a1, a2, a3); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_description_get_column_count { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_description_get_column_count", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_description_get_column_count(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_description_get_column_count.MH.invokeExact(a0, a1, a2); + } catch (Throwable t) { + throw rethrow(t); + } + } + + private static final class H_duckdb_v2_table_description_get_qname { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_description_get_qname", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_description_get_qname(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_description_get_qname.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_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_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_data_source { + static final MethodHandle MH = Ffm.downcall("duckdb_v2_table_function_set_data_source", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_table_function_set_data_source(MemorySegment a0, MemorySegment a1, MemorySegment a2) { + try { + return (int) H_duckdb_v2_table_function_set_data_source.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_uint { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_value_create_uint", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_INT, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_create_uint(MemorySegment a0, int a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_value_create_uint.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_blob { + static final MethodHandle MH = Ffm.downcall( + "duckdb_v2_value_get_blob", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS)); + } + + static int duckdb_v2_value_get_blob(MemorySegment a0, MemorySegment a1, MemorySegment a2, MemorySegment a3) { + try { + return (int) H_duckdb_v2_value_get_blob.MH.invokeExact(a0, a1, a2, a3); + } 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..3b7abd6f6 --- /dev/null +++ b/src/main/java22/org/duckdb/DuckDBBindings.java @@ -0,0 +1,1778 @@ +// 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); + } + } + + // BIGNUM storage bytes to the big-endian two's-complement bytes of a BigInteger + static byte[] duckdb_bignum_decode(byte[] storage) throws SQLException { + return FfmValues.duckdb_bignum_decode(storage); + } + + // the big-endian two's-complement bytes of a BigInteger to BIGNUM storage bytes + static byte[] duckdb_bignum_encode(byte[] twosComplement) throws SQLException { + return FfmValues.duckdb_bignum_encode(twosComplement); + } + + 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 value and the type are borrowed, the returned value is owned by the caller + static ByteBuffer duckdb_v2_value_cast(ByteBuffer factory, ByteBuffer value, ByteBuffer type) throws SQLException { + return FfmV2.duckdb_v2_value_cast(factory, value, type); + } + + // 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); + } + + // object cache + + // the returned object cache is borrowed from the instance + static ByteBuffer duckdb_v2_instance_get_object_cache(ByteBuffer instance) throws SQLException { + return FfmV2.duckdb_v2_instance_get_object_cache(instance); + } + + // returns the bytes of the entry, that is created with the given bytes (and is never evicted) if there is none + static byte[] duckdb_v2_object_cache_get_or_create(ByteBuffer cache, byte[] type, byte[] key, byte[] data) + throws SQLException { + return FfmV2.duckdb_v2_object_cache_get_or_create(cache, type, key, data); + } + + // qualified names and table descriptions + + // creates a qualified name from one to three parts, outermost first, it is owned by the caller + static ByteBuffer duckdb_v2_qname_create(byte[][] parts) throws SQLException { + return FfmV2.duckdb_v2_qname_create(parts); + } + + static void duckdb_v2_qname_destroy(ByteBuffer qname) throws SQLException { + FfmV2.duckdb_v2_qname_destroy(qname); + } + + static long duckdb_v2_qname_get_part_count(ByteBuffer qname) throws SQLException { + return FfmV2.duckdb_v2_qname_get_part_count(qname); + } + + static byte[] duckdb_v2_qname_get_part(ByteBuffer qname, long index) throws SQLException { + return FfmV2.duckdb_v2_qname_get_part(qname, index); + } + + // the name as SQL text, its parts are quoted where the identifiers require it + static byte[] duckdb_v2_qname_render(ByteBuffer qname) throws SQLException { + return FfmV2.duckdb_v2_qname_render(qname); + } + + // resolves the name of the table like SQL does, the returned description is owned by the caller + static ByteBuffer duckdb_v2_connection_describe_table(ByteBuffer conn, ByteBuffer qname) throws SQLException { + return FfmV2.duckdb_v2_connection_describe_table(conn, qname); + } + + static void duckdb_v2_table_description_destroy(ByteBuffer description) throws SQLException { + FfmV2.duckdb_v2_table_description_destroy(description); + } + + // the resolved name of the table, it is owned by the caller + static ByteBuffer duckdb_v2_table_description_get_qname(ByteBuffer description) throws SQLException { + return FfmV2.duckdb_v2_table_description_get_qname(description); + } + + // counts all the columns in the declared order, the generated columns included + static long duckdb_v2_table_description_get_column_count(ByteBuffer description) throws SQLException { + return FfmV2.duckdb_v2_table_description_get_column_count(description); + } + + // the returned column description is owned by the caller + static ByteBuffer duckdb_v2_table_description_get_column(ByteBuffer description, long index) throws SQLException { + return FfmV2.duckdb_v2_table_description_get_column(description, index); + } + + static void duckdb_v2_column_description_destroy(ByteBuffer column) throws SQLException { + FfmV2.duckdb_v2_column_description_destroy(column); + } + + static byte[] duckdb_v2_column_description_get_name(ByteBuffer column) throws SQLException { + return FfmV2.duckdb_v2_column_description_get_name(column); + } + + // the returned type is borrowed from the column description and must not be destroyed + static ByteBuffer duckdb_v2_column_description_get_type(ByteBuffer column) throws SQLException { + return FfmV2.duckdb_v2_column_description_get_type(column); + } + + static boolean duckdb_v2_column_description_has_default(ByteBuffer column) throws SQLException { + return FfmV2.duckdb_v2_column_description_has_default(column); + } + + static boolean duckdb_v2_column_description_has_generated(ByteBuffer column) throws SQLException { + return FfmV2.duckdb_v2_column_description_has_generated(column); + } + + // 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 + + // Registers the rows of a result that are not read yet as a source for the Arrow export: the chunks that are + // fetched already and the result (can be null) that the next chunks are fetched from. Returns the id of the + // source, that owns the chunks and the result. The schema is borrowed. + static long duckdb_v2_arrow_register_result(ByteBuffer schema, ByteBuffer[] chunks, ByteBuffer result) + throws SQLException { + return FfmArrow.duckdb_v2_arrow_register_result(schema, chunks, result); + } + + // releases the registered rows of a result, if they are not owned by an exported stream + static void duckdb_v2_arrow_release_result(long id) { + try { + FfmArrow.duckdb_v2_arrow_release_result(id); + } catch (java.sql.SQLException e) { + throw Ffm.sneaky(e); + } + } + + // Executes the statement (that scans the registered rows of a result) on the helper connection with the Arrow + // result format and returns the address of the ArrowArrayStream. The stream owns the helper connection, the + // statement and the rows (the stream is released by its consumer), conn is the connection that the stream is + // closed with. + static long duckdb_v2_arrow_export_stream(ByteBuffer conn, ByteBuffer helper, ByteBuffer statement, long source_id, + long batch_size) throws SQLException { + return FfmArrow.duckdb_v2_arrow_export_stream(conn, helper, statement, source_id, batch_size); + } + + // registers the table functions that scan the registered Arrow streams and the rows of the exported results + 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_bignum, also the storage of the decimals wider than 38 digits + DUCKDB_TYPE_VARINT(35, 16), + // 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..22439d881 --- /dev/null +++ b/src/main/java22/org/duckdb/FfmArrow.java @@ -0,0 +1,1076 @@ +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.ArrayDeque; +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 functions that scan a registered stream and the rows of + * an exported result are the upcalls of the functions of this class. + * + * The rows of a result that is exported are not collected: the chunks of the result are passed to the scan as they + * are, and a result that is streamed is read when the Arrow stream is read. + */ +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); + } + } + + private static void destroy(MemorySegment handle, java.util.function.Consumer destroy) { + try (Arena a = Arena.ofConfined()) { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, handle); + destroy.accept(holder); + } + } + + // --------------------------------------------------------------------------------------------------------- + // The rows of the exported results + // --------------------------------------------------------------------------------------------------------- + + /** + * The rows of a query result that are not read yet: the chunks that are fetched already, and the result that the + * next chunks are fetched from (when the result is streamed). The rows are read once, by the scan of the Arrow + * export. The source is shared by its registration, by the stream that is exported and by the scans, it is + * destroyed when the last of them releases it. + */ + private static final class ResultSource { + final List names = new ArrayList<>(); + // the copies of the types of the columns + final List types = new ArrayList<>(); + final ArrayDeque chunks = new ArrayDeque<>(); + MemorySegment result = Ffm.NULL; + boolean closed; + private int references = 1; + + /** Releases the rows that are not read. */ + synchronized void close() { + closed = true; + for (MemorySegment chunk : chunks) { + destroy(chunk, Capi::duckdb_v2_data_chunk_destroy); + } + chunks.clear(); + if (result.address() != 0) { + destroy(result, Capi::duckdb_v2_result_destroy); + result = Ffm.NULL; + } + } + + synchronized void retain() { + references++; + } + + synchronized void release() { + if (--references > 0) { + return; + } + close(); + for (MemorySegment type : types) { + destroy(type, Capi::duckdb_v2_logical_type_destroy); + } + types.clear(); + } + } + + private static final ConcurrentHashMap RESULT_SOURCES = new ConcurrentHashMap<>(); + + /** + * Registers the rows of a result as a source for the Arrow export, returns the id of the source. The source takes + * the ownership of the chunks and of the result (that can be null) when the call succeeds, the schema is borrowed. + */ + static long duckdb_v2_arrow_register_result(ByteBuffer schema, ByteBuffer[] chunks, ByteBuffer result) + throws SQLException { + MemorySegment schemaPtr = Ffm.ptrNonNull(schema, "schema"); + ResultSource source = new ResultSource(); + boolean ok = false; + try (Arena a = Arena.ofConfined()) { + MemorySegment count = Ffm.outLong(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_schema_get_count(schemaPtr, count, err), err); + MemorySegment name = Ffm.outPtr(a); + MemorySegment nameLen = Ffm.outLong(a); + MemorySegment type = Ffm.outPtr(a); + MemorySegment copy = Ffm.outPtr(a); + for (long i = 0; i < count.get(JAVA_LONG, 0); i++) { + Ffm.check(Capi.duckdb_v2_schema_get_field(schemaPtr, i, name, nameLen, type, err), err); + Ffm.check(Capi.duckdb_v2_logical_type_copy(type.get(ADDRESS, 0), copy, err), err); + source.names.add(Ffm.toBytes(name.get(ADDRESS, 0), nameLen.get(JAVA_LONG, 0))); + source.types.add(copy.get(ADDRESS, 0)); + } + List chunkPtrs = new ArrayList<>(); + if (chunks != null) { + for (ByteBuffer chunk : chunks) { + chunkPtrs.add(Ffm.ptrNonNull(chunk, "data chunk")); + } + } + // nothing can fail from here on, the ownership of the rows is taken + source.chunks.addAll(chunkPtrs); + if (result != null) { + source.result = MemorySegment.ofBuffer(result); + } + ok = true; + } finally { + if (!ok) { + source.release(); + } + } + long id = NEXT_ID.getAndIncrement(); + RESULT_SOURCES.put(id, source); + return id; + } + + /** Releases the registered rows of a result, if they are not owned by an exported stream. */ + static void duckdb_v2_arrow_release_result(long id) throws SQLException { + ResultSource source = RESULT_SOURCES.remove(id); + if (source != null) { + source.close(); + source.release(); + } + } + + // --------------------------------------------------------------------------------------------------------- + // 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; + // the rows of the result that the statement scans + ResultSource source; + 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 (source != null) { + // the result that is streamed belongs to the connection that is being closed + source.close(); + source.release(); + source = 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 scans the registered rows of a result) on the helper connection with the Arrow + * result format and returns the address of the stream of the result. The stream takes the ownership of the helper + * connection, of the statement and of the registered rows when the call succeeds, conn is the connection that the + * stream is closed with. + */ + static long duckdb_v2_arrow_export_stream(ByteBuffer conn, ByteBuffer helper, ByteBuffer statement, long sourceId, + long batchSize) throws SQLException { + MemorySegment connPtr = Ffm.ptrNonNull(conn, "connection"); + ResultSource source = RESULT_SOURCES.get(sourceId); + if (source == null) { + throw new SQLException("Invalid Arrow export arguments"); + } + 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; + } + // the rows are owned by the stream from here on + RESULT_SOURCES.remove(sourceId); + exported.statement = statement; + exported.source = source; + 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_data_source_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_data_source_init_global_set_max_threads(info, 1, Ffm.NULL); + state = + Capi.duckdb_v2_data_source_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_data_source_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_data_source_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())); + } + } + + // --------------------------------------------------------------------------------------------------------- + // Result scan: the rows of a query result are scanned by the table function that the statement of the Arrow + // export selects from + // --------------------------------------------------------------------------------------------------------- + + /** The bind data of the result scan, it shares the rows of the result. */ + private static final class ResultScanBind implements AutoCloseable { + final ResultSource source; + + ResultScanBind(ResultSource source) { + this.source = source; + } + + @Override + public void close() { + source.release(); + } + } + + private static final MemorySegment RESULT_SCAN_BIND_STUB = + stub("resultScanBind", FunctionDescriptor.ofVoid(ADDRESS, ADDRESS, ADDRESS, ADDRESS), + MethodType.methodType(void.class, MemorySegment.class, MemorySegment.class, MemorySegment.class, + MemorySegment.class)); + private static final MemorySegment RESULT_SCAN_INIT_STUB = + stub("resultScanInitGlobal", FunctionDescriptor.ofVoid(ADDRESS, ADDRESS, ADDRESS), + MethodType.methodType(void.class, MemorySegment.class, MemorySegment.class, MemorySegment.class)); + private static final MemorySegment RESULT_SCAN_EXEC_STUB = + stub("resultScanExec", FunctionDescriptor.ofVoid(ADDRESS, ADDRESS, ADDRESS), + MethodType.methodType(void.class, MemorySegment.class, MemorySegment.class, MemorySegment.class)); + + private static void setCallbackError(MemorySegment err, int state, MemorySegment callErr) { + Ffm.RawError error = Ffm.rawError(state, callErr); + FfmFunctions.setCallbackError(err, error.code, error.message); + } + + @SuppressWarnings("unused") + private static void resultScanBind(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); + Capi.duckdb_v2_value_destroy(value); + } + if (state != Ffm.ERROR_NONE) { + setCallbackError(err, state, callErr); + return; + } + ResultSource source = RESULT_SOURCES.get(id.get(JAVA_LONG, 0)); + if (source == null) { + FfmFunctions.setCallbackError(err, ERROR_INPUT_INVALID, "This result has been released"); + return; + } + for (int i = 0; i < source.names.size(); i++) { + byte[] name = source.names.get(i); + state = Capi.duckdb_v2_table_function_bind_add_result_column(result, Ffm.bytes(a, name), name.length, + source.types.get(i), callErr); + if (state != Ffm.ERROR_NONE) { + setCallbackError(err, state, callErr); + return; + } + } + source.retain(); + ResultScanBind bind = new ResultScanBind(source); + state = Capi.duckdb_v2_function_bind_set_bind_data(info, FfmFunctions.opaque(a, bind), callErr); + if (state != Ffm.ERROR_NONE) { + bind.close(); + setCallbackError(err, state, callErr); + } + } catch (Throwable t) { + FfmFunctions.setCallbackError(err, ERROR_INPUT_INVALID, String.valueOf(t.getMessage())); + } + } + + @SuppressWarnings("unused") + private static void resultScanInitGlobal(MemorySegment info, MemorySegment context, MemorySegment err) { + try { + // the chunks are read in the order of the result + Capi.duckdb_v2_data_source_init_global_set_max_threads(info, 1, Ffm.NULL); + } catch (Throwable t) { + FfmFunctions.setCallbackError(err, ERROR_INPUT_INVALID, String.valueOf(t.getMessage())); + } + } + + @SuppressWarnings("unused") + private static void resultScanExec(MemorySegment info, MemorySegment context, MemorySegment err) { + MemorySegment chunk = Ffm.NULL; + try (Arena a = Arena.ofConfined()) { + MemorySegment bindPtr = Ffm.outPtr(a); + MemorySegment callErr = Ffm.outPtr(a); + int state = Capi.duckdb_v2_data_source_exec_get_bind_data(info, bindPtr, callErr); + if (state != Ffm.ERROR_NONE) { + setCallbackError(err, state, callErr); + return; + } + Object bindData = FfmFunctions.objectOf(bindPtr.get(ADDRESS, 0)); + if (!(bindData instanceof ResultScanBind)) { + FfmFunctions.setCallbackError(err, ERROR_INPUT_INVALID, "Invalid bind data"); + return; + } + ResultSource source = ((ResultScanBind) bindData).source; + MemorySegment rows = Ffm.outLong(a); + long rowCount = 0; + synchronized (source) { + // the chunks without rows are skipped: an empty output chunk is the end of the scan + while (rowCount == 0) { + if (chunk.address() != 0) { + destroy(chunk, Capi::duckdb_v2_data_chunk_destroy); + chunk = Ffm.NULL; + } + if (source.closed) { + FfmFunctions.setCallbackError(err, ERROR_INPUT_INVALID, "This result has been released"); + return; + } + if (!source.chunks.isEmpty()) { + chunk = source.chunks.pollFirst(); + } else if (source.result.address() != 0) { + // the result is streamed, the query of the result is run here + MemorySegment fetched = Ffm.outPtr(a); + state = Capi.duckdb_v2_result_fetch_chunk(source.result, fetched, callErr); + if (state != Ffm.ERROR_NONE) { + setCallbackError(err, state, callErr); + return; + } + chunk = fetched.get(ADDRESS, 0); + } + if (chunk.address() == 0) { + return; + } + state = Capi.duckdb_v2_data_chunk_get_size(chunk, rows, callErr); + if (state != Ffm.ERROR_NONE) { + setCallbackError(err, state, callErr); + return; + } + rowCount = rows.get(JAVA_LONG, 0); + } + } + // the vectors of the output share the data of the chunk, that is not copied + MemorySegment output = Ffm.outPtr(a); + state = Capi.duckdb_v2_data_source_exec_get_output_chunk(info, output, callErr); + if (state != Ffm.ERROR_NONE) { + setCallbackError(err, state, callErr); + return; + } + MemorySegment columns = Ffm.outLong(a); + Capi.duckdb_v2_data_chunk_get_vector_count(chunk, columns, Ffm.NULL); + MemorySegment target = Ffm.outPtr(a); + MemorySegment vector = 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(chunk, i, vector, callErr); + } + if (state == Ffm.ERROR_NONE) { + state = Capi.duckdb_v2_vector_reference(target.get(ADDRESS, 0), vector.get(ADDRESS, 0), callErr); + } + if (state == Ffm.ERROR_NONE) { + state = Capi.duckdb_v2_vector_set_size(target.get(ADDRESS, 0), rowCount, callErr); + } + if (state != Ffm.ERROR_NONE) { + setCallbackError(err, state, callErr); + return; + } + } + } catch (Throwable t) { + FfmFunctions.setCallbackError(err, ERROR_INPUT_INVALID, String.valueOf(t.getMessage())); + } finally { + if (chunk.address() != 0) { + destroy(chunk, Capi::duckdb_v2_data_chunk_destroy); + } + } + } + + // Registers a table function with one BIGINT parameter, the scan callbacks are set on a data source: the table + // function keeps a copy of it + private static void registerScanFunction(MemorySegment connPtr, String functionName, MemorySegment bindStub, + MemorySegment initStub, MemorySegment execStub) 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(connPtr, out, err), err); + MemorySegment factory = out.get(ADDRESS, 0); + MemorySegment functionHolder = Ffm.outPtr(a); + MemorySegment dataSourceHolder = Ffm.outPtr(a); + MemorySegment bigint = Ffm.outPtr(a); + try { + Ffm.check(Capi.duckdb_v2_table_function_create(factory, functionHolder, err), err); + MemorySegment function = functionHolder.get(ADDRESS, 0); + byte[] name = functionName.getBytes(StandardCharsets.UTF_8); + Ffm.check(Capi.duckdb_v2_table_function_set_name(function, Ffm.bytes(a, name), name.length, err), err); + Ffm.check(Capi.duckdb_v2_factory_create_type_from_id(factory, TYPE_ID_BIGINT, Ffm.NULL, Ffm.NULL, + Ffm.NULL, 0, bigint, err), + err); + Ffm.check(Capi.duckdb_v2_table_function_get_signature(function, out, err), err); + byte[] param = "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); + Ffm.check(Capi.duckdb_v2_table_function_set_bind_callback(function, bindStub, err), err); + Ffm.check(Capi.duckdb_v2_data_source_create(factory, dataSourceHolder, err), err); + MemorySegment dataSource = dataSourceHolder.get(ADDRESS, 0); + Ffm.check(Capi.duckdb_v2_data_source_set_init_global_callback(dataSource, initStub, err), err); + Ffm.check(Capi.duckdb_v2_data_source_set_exec_callback(dataSource, execStub, err), err); + Ffm.check(Capi.duckdb_v2_table_function_set_data_source(function, dataSource, err), err); + Ffm.check(Capi.duckdb_v2_connection_register_table_function(connPtr, function, err), err); + } finally { + if (bigint.get(ADDRESS, 0).address() != 0) { + Capi.duckdb_v2_logical_type_destroy(bigint); + } + if (dataSourceHolder.get(ADDRESS, 0).address() != 0) { + Capi.duckdb_v2_data_source_destroy(dataSourceHolder); + } + if (functionHolder.get(ADDRESS, 0).address() != 0) { + Capi.duckdb_v2_table_function_destroy(functionHolder); + } + } + } + } + + /** Registers the table functions that scan the registered streams and the rows of the exported results. */ + static void duckdb_v2_arrow_register_scan_function(ByteBuffer conn) throws SQLException { + MemorySegment connPtr = Ffm.ptrNonNull(conn, "connection"); + registerScanFunction(connPtr, "__jdbc_arrow_stream_scan", SCAN_BIND_STUB, SCAN_INIT_STUB, SCAN_EXEC_STUB); + registerScanFunction(connPtr, "__jdbc_arrow_result_scan", RESULT_SCAN_BIND_STUB, RESULT_SCAN_INIT_STUB, + RESULT_SCAN_EXEC_STUB); + } + + /** 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..58db86bab --- /dev/null +++ b/src/main/java22/org/duckdb/FfmFunctions.java @@ -0,0 +1,1268 @@ +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; + } + + /** Fills the opaque user data that is passed by the pointer with the registered object. */ + static void fillOpaque(MemorySegment opaque, Object object) { + MemorySegment res = opaque.reinterpret(24); + res.set(ADDRESS, 0, MemorySegment.ofAddress(register(object))); + res.set(ADDRESS, 8, DESTROY_STUB); + res.set(ADDRESS, 16, Ffm.NULL); + } + + /** 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_data_source_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_data_source_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_data_source_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_data_source_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_data_source_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_data_source_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; + } + } + // the scan callbacks are set on a data source, the table function keeps a copy of it, + // data source callbacks get the user data of the table function as the data source has none + MemorySegment dataSource = Ffm.outPtr(a); + if (!ok(Capi.duckdb_v2_data_source_create(factory, dataSource, Ffm.NULL))) { + return 1; + } + try { + MemorySegment source = dataSource.get(ADDRESS, 0); + if (!ok(Capi.duckdb_v2_data_source_set_init_global_callback(source, TABLE_INIT_GLOBAL_STUB, + Ffm.NULL)) || + (spec.hasLocalInit && !ok(Capi.duckdb_v2_data_source_set_init_local_callback( + source, TABLE_INIT_LOCAL_STUB, Ffm.NULL))) || + !ok(Capi.duckdb_v2_data_source_set_exec_callback(source, TABLE_EXEC_STUB, Ffm.NULL)) || + !ok(Capi.duckdb_v2_table_function_set_bind_callback(function, TABLE_BIND_STUB, Ffm.NULL)) || + !ok(Capi.duckdb_v2_table_function_set_data_source(function, source, Ffm.NULL)) || + !ok(Capi.duckdb_v2_table_function_set_projection_pushdown(function, spec.projectionPushdown, + Ffm.NULL))) { + return 1; + } + } finally { + Capi.duckdb_v2_data_source_destroy(dataSource); + } + // 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_data_source_init_global_get_bind_data(init.global, out, err) + : Capi.duckdb_v2_data_source_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_data_source_init_global_get_column_count(init.global, out, err) + : Capi.duckdb_v2_data_source_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_data_source_init_global_get_column_count(init.global, count, Ffm.NULL) == + Ffm.ERROR_NONE && + columnIndex < count.get(JAVA_LONG, 0)) { + Capi.duckdb_v2_data_source_init_global_get_column_index(init.global, columnIndex, idx, Ffm.NULL); + } + } else if (Capi.duckdb_v2_data_source_init_local_get_column_count(init.local, count, Ffm.NULL) == + Ffm.ERROR_NONE && + columnIndex < count.get(JAVA_LONG, 0)) { + Capi.duckdb_v2_data_source_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_data_source_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_data_source_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_data_source_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_data_source_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..332e53390 --- /dev/null +++ b/src/main/java22/org/duckdb/FfmTypes.java @@ -0,0 +1,718 @@ +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); + } + } + + /** The width (index 0) or the scale (index 1) of a DECIMAL type, 0 if the parameter cannot be read. */ + 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) { + throw new SQLException("Invalid decimal width: expected at least 1"); + } + 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_uint(factory, 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; + } + return decimalParamToInt(decimalParam(ptr, 0)); + } + + /** The width and the scale of a DECIMAL are 32-bit unsigned, the values that do not fit an int are clamped. */ + private static int decimalParamToInt(long param) { + return param > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) param; + } + + static int duckdb_decimal_scale(ByteBuffer type) throws SQLException { + MemorySegment ptr = typePtr(type); + if (typeId(ptr) != T_DECIMAL) { + return 0; + } + return decimalParamToInt(decimalParam(ptr, 1)); + } + + 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..f959908c2 --- /dev/null +++ b/src/main/java22/org/duckdb/FfmV2.java @@ -0,0 +1,1479 @@ +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); + } + + // --------------------------------------------------------------------------------------------------------- + // Value casts + // --------------------------------------------------------------------------------------------------------- + + // The value and the type are borrowed for the call, the returned value is owned by the caller + static ByteBuffer duckdb_v2_value_cast(ByteBuffer factory, ByteBuffer value, 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_cast(p(factory, "factory"), p(value, "value"), FfmTypes.typePtr(type), out, err), + err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + // --------------------------------------------------------------------------------------------------------- + // Qualified names and table descriptions + // --------------------------------------------------------------------------------------------------------- + + private static void destroy(ByteBuffer handle, String what, java.util.function.Consumer destroy) + throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment holder = a.allocate(ADDRESS); + holder.set(ADDRESS, 0, p(handle, what)); + destroy.accept(holder); + } + } + + // The parts are ordered outermost first, the returned name is owned by the caller + static ByteBuffer duckdb_v2_qname_create(byte[][] parts) throws SQLException { + byte[][] values = parts == null ? new byte[0][] : parts; + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_qname_create(byteArrays(a, values), lengths(a, values), values.length, out, err), + err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static void duckdb_v2_qname_destroy(ByteBuffer qname) throws SQLException { + destroy(qname, "qualified name", Capi::duckdb_v2_qname_destroy); + } + + static long duckdb_v2_qname_get_part_count(ByteBuffer qname) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outLong(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_qname_get_part_count(p(qname, "qualified name"), out, err), err); + return out.get(JAVA_LONG, 0); + } + } + + static byte[] duckdb_v2_qname_get_part(ByteBuffer qname, long index) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment part = Ffm.outPtr(a); + MemorySegment partLen = Ffm.outLong(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_qname_get_part(p(qname, "qualified name"), index, part, partLen, err), err); + return Ffm.toBytes(part.get(ADDRESS, 0), partLen.get(JAVA_LONG, 0)); + } + } + + // The name as SQL text, its parts are quoted where the identifiers require it + static byte[] duckdb_v2_qname_render(ByteBuffer qname) throws SQLException { + MemorySegment name = p(qname, "qualified name"); + try (Arena a = Arena.ofConfined()) { + MemorySegment length = Ffm.outLong(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_qname_render(name, Ffm.NULL, 0, length, err), err); + long capacity = length.get(JAVA_LONG, 0) + 1; + MemorySegment text = a.allocate(capacity); + Ffm.check(Capi.duckdb_v2_qname_render(name, text, capacity, length, err), err); + return Ffm.toBytes(text, length.get(JAVA_LONG, 0)); + } + } + + // The name is resolved like the same name in SQL, the returned description is owned by the caller + static ByteBuffer duckdb_v2_connection_describe_table(ByteBuffer conn, ByteBuffer qname) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check( + Capi.duckdb_v2_connection_describe_table(p(conn, "connection"), p(qname, "qualified name"), out, err), + err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static void duckdb_v2_table_description_destroy(ByteBuffer description) throws SQLException { + destroy(description, "table description", Capi::duckdb_v2_table_description_destroy); + } + + // The resolved name of the table, the returned name is owned by the caller + static ByteBuffer duckdb_v2_table_description_get_qname(ByteBuffer description) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_table_description_get_qname(p(description, "table description"), out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + // All the columns are counted, the generated columns included + static long duckdb_v2_table_description_get_column_count(ByteBuffer description) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outLong(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_table_description_get_column_count(p(description, "table description"), out, err), + err); + return out.get(JAVA_LONG, 0); + } + } + + // The returned column description is owned by the caller + static ByteBuffer duckdb_v2_table_description_get_column(ByteBuffer description, long index) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_table_description_get_column(p(description, "table description"), index, out, err), + err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static void duckdb_v2_column_description_destroy(ByteBuffer column) throws SQLException { + destroy(column, "column description", Capi::duckdb_v2_column_description_destroy); + } + + static byte[] duckdb_v2_column_description_get_name(ByteBuffer column) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment name = Ffm.outPtr(a); + MemorySegment nameLen = Ffm.outLong(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_column_description_get_name(p(column, "column description"), name, nameLen, err), + err); + return Ffm.toBytes(name.get(ADDRESS, 0), nameLen.get(JAVA_LONG, 0)); + } + } + + // The returned type is borrowed from the column description and must not be destroyed + static ByteBuffer duckdb_v2_column_description_get_type(ByteBuffer column) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_column_description_get_type(p(column, "column description"), out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + static boolean duckdb_v2_column_description_has_default(ByteBuffer column) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = a.allocate(JAVA_BOOLEAN); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_column_description_has_default(p(column, "column description"), out, err), err); + return out.get(JAVA_BOOLEAN, 0); + } + } + + static boolean duckdb_v2_column_description_has_generated(ByteBuffer column) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = a.allocate(JAVA_BOOLEAN); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_column_description_has_generated(p(column, "column description"), out, err), err); + return out.get(JAVA_BOOLEAN, 0); + } + } + + // --------------------------------------------------------------------------------------------------------- + // Object cache + // --------------------------------------------------------------------------------------------------------- + + // The returned object cache is borrowed from the instance and must not be destroyed + static ByteBuffer duckdb_v2_instance_get_object_cache(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_object_cache(p(instance, "instance"), out, err), err); + return Ffm.handle(out.get(ADDRESS, 0)); + } + } + + /** The bytes of the entries that are being created, by the user data of the create callback. */ + private static final java.util.concurrent.ConcurrentHashMap CACHE_CREATE = + new java.util.concurrent.ConcurrentHashMap<>(); + private static final java.util.concurrent.atomic.AtomicLong CACHE_CREATE_ID = + new java.util.concurrent.atomic.AtomicLong(1); + + private static final MemorySegment CACHE_CREATE_STUB = cacheCreateStub(); + + private static MemorySegment cacheCreateStub() { + try { + MethodHandle target = MethodHandles.lookup().findStatic( + FfmV2.class, "cacheCreate", + MethodType.methodType(void.class, MemorySegment.class, MemorySegment.class, MemorySegment.class, + MemorySegment.class)); + return Ffm.LINKER.upcallStub(target, FunctionDescriptor.ofVoid(ADDRESS, ADDRESS, ADDRESS, ADDRESS), + Arena.global()); + } catch (ReflectiveOperationException e) { + throw new ExceptionInInitializerError(e); + } + } + + // The callback of the C API. The data of a new entry is a copy of the bytes, the entry is pinned: it is kept for + // as long as the instance lives. + @SuppressWarnings("unused") + private static void cacheCreate(MemorySegment userData, MemorySegment data, MemorySegment sizeBytes, + MemorySegment err) { + try { + byte[] bytes = CACHE_CREATE.get(userData.address()); + FfmFunctions.fillOpaque(data, bytes.clone()); + sizeBytes.reinterpret(8).set(JAVA_LONG, 0, 0); + } catch (Throwable t) { + // DUCKDB_V2_ERROR_INPUT_INVALID + FfmFunctions.setCallbackError(err, 2001, String.valueOf(t.getMessage())); + } + } + + // Returns the bytes of the entry. The entry is created with the given bytes if there is none, only one of the + // concurrent calls creates it. + static byte[] duckdb_v2_object_cache_get_or_create(ByteBuffer cache, byte[] type, byte[] key, byte[] data) + throws SQLException { + MemorySegment cachePtr = p(cache, "object cache"); + long id = CACHE_CREATE_ID.getAndIncrement(); + CACHE_CREATE.put(id, data == null ? new byte[0] : data); + try (Arena a = Arena.ofConfined()) { + MemorySegment entry = Ffm.outPtr(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_object_cache_get_or_create(cachePtr, Ffm.bytes(a, type), Ffm.len(type), + Ffm.bytes(a, key), Ffm.len(key), CACHE_CREATE_STUB, + MemorySegment.ofAddress(id), entry, err), + err); + try { + MemorySegment stored = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_object_cache_entry_get_data(entry.get(ADDRESS, 0), stored, err), err); + Object bytes = FfmFunctions.objectOf(stored.get(ADDRESS, 0)); + return bytes instanceof byte[] ? ((byte[]) bytes).clone() : null; + } finally { + Capi.duckdb_v2_object_cache_entry_destroy(entry); + } + } finally { + CACHE_CREATE.remove(id); + } + } +} diff --git a/src/main/java22/org/duckdb/FfmValues.java b/src/main/java22/org/duckdb/FfmValues.java new file mode 100644 index 000000000..f23c57a8d --- /dev/null +++ b/src/main/java22/org/duckdb/FfmValues.java @@ -0,0 +1,459 @@ +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)); + } + } + + // The widest DECIMAL that is stored as a fixed-size integer, wider decimals are stored as BIGNUM blobs + private static final long MAX_FIXED_SIZE_DECIMAL_WIDTH = 38; + + /** Negates a big-endian two's-complement integer in place: all the bits are inverted and one is added. */ + private static void negateTwosComplement(byte[] bytes) { + boolean carry = true; + for (int i = bytes.length - 1; i >= 0; i--) { + int inverted = ~bytes[i] & 0xff; + bytes[i] = (byte) (carry ? inverted + 1 : inverted); + carry = carry && inverted == 0xff; + } + } + + /** + * Decodes the storage bytes of a BIGNUM into the big-endian two's-complement bytes that a BigInteger is created + * from. The unscaled value of a DECIMAL that is wider than 38 digits is stored in the same form. The storage + * format belongs to the engine, it is only interpreted by duckdb_v2_bignum_decode. + */ + private static byte[] bignumStorageToJava(MemorySegment storage, long storageLen) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment magnitudeLen = Ffm.outLong(a); + MemorySegment negative = a.allocate(JAVA_BOOLEAN); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_bignum_decode(storage, storageLen, Ffm.NULL, 0, magnitudeLen, negative, err), err); + long len = magnitudeLen.get(JAVA_LONG, 0); + if (len > Integer.MAX_VALUE - 1) { + throw new SQLException("Invalid BIGNUM storage"); + } + // the magnitude is unsigned, the leading zero byte keeps its sign bit clear + byte[] out = new byte[(int) len + 1]; + MemorySegment magnitude = len == 0 ? Ffm.NULL : a.allocate(len); + Ffm.check(Capi.duckdb_v2_bignum_decode(storage, storageLen, magnitude, len, magnitudeLen, negative, err), + err); + if (len > 0) { + MemorySegment.copy(magnitude, JAVA_BYTE, 0, out, 1, (int) len); + } + if (negative.get(JAVA_BOOLEAN, 0)) { + negateTwosComplement(out); + } + return out; + } + } + + /** + * Encodes the big-endian two's-complement bytes of a BigInteger (see BigInteger#toByteArray) into the storage + * bytes of a BIGNUM with duckdb_v2_bignum_encode. + */ + private static byte[] bignumStorageFromJava(byte[] bytes) throws SQLException { + byte[] magnitude = bytes.clone(); + boolean negative = magnitude.length > 0 && (magnitude[0] & 0x80) != 0; + if (negative) { + // the magnitude of a negative value always fits the same number of bytes + negateTwosComplement(magnitude); + } + // the magnitude must not have leading zero bytes, zero is a single zero byte + int skip = 0; + while (skip + 1 < magnitude.length && magnitude[skip] == 0) { + skip++; + } + int magnitudeLen = magnitude.length - skip; + try (Arena a = Arena.ofConfined()) { + MemorySegment magnitudePtr = Ffm.NULL; + if (magnitude.length > 0) { + magnitudePtr = a.allocate(magnitudeLen); + MemorySegment.copy(magnitude, skip, magnitudePtr, JAVA_BYTE, 0, magnitudeLen); + } + MemorySegment storageLen = Ffm.outLong(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_bignum_encode(magnitudePtr, magnitudeLen, negative, Ffm.NULL, 0, storageLen, err), + err); + long len = storageLen.get(JAVA_LONG, 0); + MemorySegment storage = len == 0 ? Ffm.NULL : a.allocate(len); + Ffm.check(Capi.duckdb_v2_bignum_encode(magnitudePtr, magnitudeLen, negative, storage, len, storageLen, err), + err); + return Ffm.toBytes(storage, len); + } + } + + /** + * Reads a non-NULL value that is stored as a BIGNUM blob (a BIGNUM or a DECIMAL that is wider than 38 digits) as + * the big-endian two's-complement bytes of a BigInteger. + */ + private static byte[] bignumBytes(MemorySegment value) throws SQLException { + try (Arena a = Arena.ofConfined()) { + MemorySegment blob = Ffm.outPtr(a); + MemorySegment blobLen = Ffm.outLong(a); + MemorySegment err = Ffm.outPtr(a); + Ffm.check(Capi.duckdb_v2_value_get_blob(value, blob, blobLen, err), err); + return bignumStorageToJava(blob.get(ADDRESS, 0), blobLen.get(JAVA_LONG, 0)); + } + } + + private static boolean isNull(MemorySegment value) { + try (Arena a = Arena.ofConfined()) { + MemorySegment out = a.allocate(JAVA_BOOLEAN); + return Capi.duckdb_v2_value_is_null(value, out, Ffm.NULL) != Ffm.ERROR_NONE || out.get(JAVA_BOOLEAN, 0); + } + } + + static BigInteger duckdb_get_bignum(ByteBuffer value) throws SQLException { + MemorySegment val = v(value); + // null is returned for non-BIGNUM and NULL values + try (Arena a = Arena.ofConfined()) { + MemorySegment type = Ffm.outPtr(a); + if (Capi.duckdb_v2_value_get_logical_type(val, type, Ffm.NULL) != Ffm.ERROR_NONE) { + return null; + } + try { + if (FfmTypes.typeId(type.get(ADDRESS, 0)) != FfmTypes.T_BIGNUM) { + return null; + } + } finally { + Capi.duckdb_v2_logical_type_destroy(type); + } + } + if (isNull(val)) { + return null; + } + return DuckDBBignum.toBigInteger(bignumBytes(val)); + } + + static byte[] duckdb_bignum_decode(byte[] storage) throws SQLException { + if (storage == null) { + throw new SQLException("Invalid BIGNUM storage"); + } + try (Arena a = Arena.ofConfined()) { + return bignumStorageToJava(Ffm.bytes(a, storage), storage.length); + } + } + + static byte[] duckdb_bignum_encode(byte[] twosComplement) throws SQLException { + if (twosComplement == null) { + throw new SQLException("Invalid BIGNUM value"); + } + return bignumStorageFromJava(twosComplement); + } + + static BigDecimal duckdb_get_decimal(ByteBuffer value) throws SQLException { + MemorySegment val = v(value); + try (Arena a = Arena.ofConfined()) { + // A decimal that is wider than 38 digits is read exactly from its BIGNUM storage. value_get_decimal is + // not tried for it: that call fails, with an error that is created and formatted for every such value, + // when the unscaled value does not fit in 128 bits. + MemorySegment type = Ffm.outPtr(a); + boolean wide = false; + long wideScale = 0; + if (Capi.duckdb_v2_value_get_logical_type(val, type, Ffm.NULL) == Ffm.ERROR_NONE) { + try { + MemorySegment lt = type.get(ADDRESS, 0); + if (FfmTypes.typeId(lt) == FfmTypes.T_DECIMAL && + FfmTypes.decimalParam(lt, 0) > MAX_FIXED_SIZE_DECIMAL_WIDTH) { + wide = true; + wideScale = FfmTypes.decimalParam(lt, 1); + } + } finally { + Capi.duckdb_v2_logical_type_destroy(type); + } + } + if (wide) { + if (!isNull(val)) { + return DuckDBBignum.toBigDecimal(bignumBytes(val), (int) wideScale); + } + return DuckDBHugeInt.toBigDecimal(0, 0, 0); + } + // same as in C API v1, zero is returned for non-decimal and NULL values + MemorySegment out = a.allocate(16, 8); + MemorySegment width = Ffm.outInt(a); + MemorySegment scale = Ffm.outInt(a); + if (Capi.duckdb_v2_value_get_decimal(val, 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/RunGraalNativeImage.java b/src/test/external/RunGraalNativeImage.java index b60007149..0eb27c7a0 100644 --- a/src/test/external/RunGraalNativeImage.java +++ b/src/test/external/RunGraalNativeImage.java @@ -6,14 +6,18 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; public class RunGraalNativeImage { static final String DUCKDB_JDBC_JAR = fromEnv("DUCKDB_JDBC_JAR", "./build/release/duckdb_jdbc.jar"); public static void main(String[] args) throws Exception { - if (args.length != 1) { - throw new RuntimeException("Path to the Graal sample directory must be specified as the only argument"); + if (args.length < 1) { + throw new RuntimeException("Path to the Graal sample directory must be specified as the first argument," + + " it can be followed by additional options of native-image"); } Path srcDir = Paths.get(args[0]); Path jar = Paths.get(DUCKDB_JDBC_JAR).toAbsolutePath(); @@ -26,8 +30,13 @@ public static void main(String[] args) throws Exception { StandardCopyOption.REPLACE_EXISTING); run(workDir, "javac", "-cp", jar.toString(), "Hello.java"); - run(workDir, "native-image", "--no-fallback", "--enable-native-access=ALL-UNNAMED", "-cp", - jar + File.pathSeparator + ".", "-H:ConfigurationFileDirectories=config", "-o", "hello", "Hello"); + List nativeImage = new ArrayList<>( + Arrays.asList("native-image", "--no-fallback", "--enable-native-access=ALL-UNNAMED", "-cp", + jar + File.pathSeparator + ".", "-H:ConfigurationFileDirectories=config", "-o", "hello")); + // additional options, e.g. -J-Djdk.util.jar.enableMultiRelease=false to build the image with the JNI bindings + nativeImage.addAll(Arrays.asList(args).subList(1, args.length)); + nativeImage.add("Hello"); + run(workDir, nativeImage.toArray(new String[0])); Process ps = new ProcessBuilder(workDir.resolve("hello").toString()) .directory(workDir.toFile()) diff --git a/src/test/external/graal/Hello.java b/src/test/external/graal/Hello.java index c304dfc71..35cb5283d 100644 --- a/src/test/external/graal/Hello.java +++ b/src/test/external/graal/Hello.java @@ -1,5 +1,14 @@ import java.sql.*; import java.time.LocalDateTime; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Function; +import org.duckdb.DuckDBConnection; +import org.duckdb.DuckDBDataChunkWriter; +import org.duckdb.DuckDBFunctions; +import org.duckdb.DuckDBTableFunction; +import org.duckdb.DuckDBTableFunctionBindInfo; +import org.duckdb.DuckDBTableFunctionCallInfo; +import org.duckdb.DuckDBTableFunctionInitInfo; public class Hello { public static void main(String[] a) { @@ -12,6 +21,7 @@ public static void main(String[] a) { } } checkTimestampNs(); + checkFunctions(); } catch (Throwable t) { // The default uncaught exception handler can fail to print in a native image, // masking the real cause, so report it explicitly here. @@ -30,6 +40,59 @@ public static void main(String[] a) { } } + // The functions are called back from the native library + private static void checkFunctions() throws Exception { + try (DuckDBConnection c = DriverManager.getConnection("jdbc:duckdb:").unwrap(DuckDBConnection.class); + Statement s = c.createStatement()) { + DuckDBFunctions.scalarFunction() + .withName("java_plus_one") + .withParameter(Integer.class) + .withReturnType(Integer.class) + .withFunction((Function) x -> x + 1) + .register(c); + try (ResultSet r = s.executeQuery("SELECT sum(java_plus_one(range::INTEGER)) FROM range(3)")) { + if (!r.next() || r.getLong(1) != 6) { + throw new IllegalStateException("Scalar function result mismatch"); + } + } + DuckDBFunctions.tableFunction() + .withName("java_table") + .withParameter(int.class) + .withFunction(new DuckDBTableFunction() { + @Override + public Integer bind(DuckDBTableFunctionBindInfo info) throws Exception { + info.addResultColumn("col1", Integer.TYPE).addResultColumn("col2", String.class); + return info.getParameter(0).getInt(); + } + + @Override + public AtomicBoolean init(DuckDBTableFunctionInitInfo info) throws Exception { + info.setMaxThreads(1); + return new AtomicBoolean(false); + } + + @Override + public long apply(DuckDBTableFunctionCallInfo info, DuckDBDataChunkWriter output) throws Exception { + Integer bindData = info.getBindData(); + AtomicBoolean done = info.getInitData(); + if (done.get()) { + return 0; + } + output.vector(0).setInt(0, bindData); + output.vector(1).setString(0, "foo"); + done.set(true); + return 1; + } + }) + .register(c); + try (ResultSet r = s.executeQuery("SELECT col1, col2 FROM java_table(41)")) { + if (!r.next() || r.getInt(1) != 41 || !"foo".equals(r.getString(2)) || r.next()) { + throw new IllegalStateException("Table function result mismatch"); + } + } + } + } + private static void checkTimestampNs() throws Exception { LocalDateTime expected = LocalDateTime.of(2026, 2, 20, 12, 0, 0, 123456789); long expectedNanos = 1771588800123456789L; 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"));