diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index cb752808..817f0b1c 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -24,6 +24,9 @@ /deny.toml @databricks/eng-oss-sql-driver /about.toml @databricks/eng-oss-sql-driver +# Native ADBC driver, including its public Rust and C ABI surfaces. +/adbc/ @databricks/eng-oss-sql-driver + # PyO3 sub-crate manifests — pip / Python dep changes flow through here. /pyo3/Cargo.toml @databricks/eng-oss-sql-driver /pyo3/pyproject.toml @databricks/eng-oss-sql-driver diff --git a/.github/workflows/cargo-publish.yml b/.github/workflows/cargo-publish.yml index 54d7c040..27a05c49 100644 --- a/.github/workflows/cargo-publish.yml +++ b/.github/workflows/cargo-publish.yml @@ -115,8 +115,8 @@ jobs: fi # `--registry jfrog` matches the `[registries.jfrog]` block # that setup-jfrog writes into ~/.cargo/config.toml. The - # workspace's other members (pyo3/) have their own publish - # workflows / are not part of this release; --no-verify + # standalone ADBC crate remains non-publishable in this release; + # pyo3 and napi have their own workspace release paths. `--no-verify` # skips re-compiling the crate during the package step # since CI has already done that elsewhere. cargo publish \ diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 18510395..e196dcad 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -27,6 +27,7 @@ on: paths: - "src/**" - "tests/**" + - "adbc/**" - "pyo3/**" - "Cargo.toml" - "Cargo.lock" @@ -36,6 +37,7 @@ on: paths: - "src/**" - "tests/**" + - "adbc/**" - "pyo3/**" - "Cargo.toml" - "Cargo.lock" @@ -89,7 +91,9 @@ jobs: - name: Run coverage # E2E tests stay #[ignore]'d; coverage runs the same suite # as `pr-checks.yml`'s `test` job. - run: cargo llvm-cov --workspace --lcov --output-path lcov.info + run: | + cargo llvm-cov --workspace --lcov --output-path lcov.info + cargo llvm-cov --manifest-path adbc/Cargo.toml --features ffi --lcov --output-path adbc-lcov.info # Codecov upload. # @@ -105,6 +109,6 @@ jobs: - name: Upload to Codecov uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0 with: - files: lcov.info + files: lcov.info,adbc-lcov.info fail_ci_if_error: false use_oidc: true diff --git a/.github/workflows/license-check.yml b/.github/workflows/license-check.yml index e023c841..478984c0 100644 --- a/.github/workflows/license-check.yml +++ b/.github/workflows/license-check.yml @@ -30,6 +30,8 @@ on: paths: - "Cargo.toml" - "Cargo.lock" + - "adbc/Cargo.toml" + - "adbc/Cargo.lock" - "deny.toml" # napi/ is a standalone workspace with its own lockfile; its # dependency graph is invisible to a root `cargo deny` run, so @@ -42,6 +44,8 @@ on: paths: - "Cargo.toml" - "Cargo.lock" + - "adbc/Cargo.toml" + - "adbc/Cargo.lock" - "deny.toml" - "napi/Cargo.toml" - "napi/Cargo.lock" @@ -92,10 +96,12 @@ jobs: # `licenses` is the load-bearing check; `advisories` flags # RustSec security advisories; `bans` and `sources` are # empty-permissive in our deny.toml today but the slots are - # there for future hardening. The root workspace covers the - # kernel + pyo3 (pyo3 is a root workspace member). + # there for future hardening. The root workspace covers the kernel. run: cargo deny check + - name: Check licenses, advisories, bans, sources (ADBC workspace) + run: cargo deny --manifest-path "$GITHUB_WORKSPACE/adbc/Cargo.toml" --config "$GITHUB_WORKSPACE/deny.toml" check + - name: Check licenses, advisories, bans, sources (napi workspace) # napi/ is a separate Cargo workspace (its own Cargo.lock) so # its transitive graph is NOT seen by the root run above. Scan diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 73da98c6..cbfb6d61 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -73,7 +73,9 @@ jobs: components: rustfmt - name: cargo fmt --check - run: cargo +stable fmt --all -- --check + run: | + cargo +stable fmt --all -- --check + cargo +stable fmt --manifest-path adbc/Cargo.toml -- --check clippy: name: Clippy @@ -159,6 +161,45 @@ jobs: # link and call the kernel. `cc` is preinstalled on the runner. run: make c-abi-test + adbc: + name: ADBC native + C ABI + runs-on: + group: databricks-protected-runner-group + labels: linux-ubuntu-latest + env: + RUSTC_WRAPPER: sccache + SCCACHE_GHA_ENABLED: "true" + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: ./.github/actions/setup-jfrog + with: + cargo: "true" + + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 + with: + toolchain: 1.89.0 + components: clippy + + - name: Setup sccache + uses: Mozilla-Actions/sccache-action@7d986dd989559c6ecdb630a3fd2557667be217ad # v0.0.9 + + - name: Test native Rust and ADBC C ABI surfaces + working-directory: adbc + run: | + cargo clippy --all-targets --features ffi -- -D warnings + cargo test --features ffi + + - name: Build and dynamically load the ADBC driver + working-directory: adbc + run: | + cargo build --release --features ffi --lib --example ffi_smoke + ./target/release/examples/ffi_smoke "$PWD/target/release/libdatabricks_adbc.so" + + - name: Verify package contents + working-directory: adbc + run: cargo package --allow-dirty --list + check-tls-rustls: name: Build (tls-rustls feature) runs-on: @@ -187,10 +228,10 @@ jobs: # opts INTO `tls-rustls` instead. Without this job, a feature- # gated cfg typo or a dep update that breaks rustls compilation # would only surface when the downstream napi build breaks. - run: cargo check --no-default-features --features tls-rustls + run: cargo check -p databricks-sql-kernel --no-default-features --features tls-rustls - name: cargo clippy (tls-rustls) # Keep clippy honest under both backends so warnings caught # under tls-native don't disappear under tls-rustls and vice # versa. - run: cargo clippy --no-default-features --features tls-rustls --all-targets -- -D warnings + run: cargo clippy -p databricks-sql-kernel --no-default-features --features tls-rustls --all-targets -- -D warnings diff --git a/.github/workflows/securityScan.yml b/.github/workflows/securityScan.yml index 5c37cecb..09cc4203 100644 --- a/.github/workflows/securityScan.yml +++ b/.github/workflows/securityScan.yml @@ -21,14 +21,14 @@ name: Security Scan # # Scanner: OSV-Scanner v2.3.8 (purl-based via OSV.dev; federates # GHSA, NVD, RustSec, PyPA, Go vuln DB). Reads CycloneDX SBOMs -# produced by `cargo cyclonedx` over the kernel's three standalone -# workspaces: +# produced by `cargo cyclonedx` over the repository's four standalone +# workspace views: # -# 1. Kernel root `Cargo.toml` (members = ["."]) — emits one SBOM -# for `databricks-sql-kernel`. -# 2. pyo3/ standalone workspace — emits one SBOM for +# 1. Kernel root `Cargo.toml` — emits one SBOM for `databricks-sql-kernel`. +# 2. adbc/ standalone workspace — emits one SBOM for `databricks-adbc`. +# 3. pyo3/ standalone workspace — emits one SBOM for # `databricks-sql-kernel-pyo3` (built with `tls-rustls`). -# 3. napi/ standalone workspace — emits one SBOM for +# 4. napi/ standalone workspace — emits one SBOM for # `databricks-sql-kernel-napi` (also `tls-rustls`). # # The bindings are deliberately NOT members of the kernel's root @@ -107,10 +107,11 @@ jobs: - name: Install cargo-cyclonedx run: cargo install cargo-cyclonedx --version 0.5.7 --locked - # Two cyclonedx invocations cover all three published artifacts: + # Four cyclonedx invocations cover all four published artifacts: # - # - From repo root: writes one SBOM (kernel root is now a - # single-member workspace) — databricks-sql-kernel.cdx.json. + # - From repo root: writes databricks-sql-kernel.cdx.json. + # + # - From adbc/: writes databricks-adbc.cdx.json. # # - From pyo3/: standalone workspace, writes one SBOM # (databricks-sql-kernel-pyo3.cdx.json). @@ -127,9 +128,9 @@ jobs: set -euo pipefail mkdir -p /tmp/sboms - # The kernel root, pyo3, and napi are each their own - # standalone single-member workspaces (see the workspace - # comment in each Cargo.toml — pyo3 and napi need + # The kernel, ADBC, pyo3, and napi standalone workspaces cover all + # Rust artifacts (see the workspace comment in each Cargo.toml — + # pyo3 and napi need # `tls-rustls` while the kernel default is `tls-native`, # and Cargo feature unification across a shared workspace # would trip the mutual-exclusion `compile_error!` in @@ -147,6 +148,11 @@ jobs: cp "$f" "/tmp/sboms/$(basename "$f")" done + ( cd adbc && cargo cyclonedx --format json ) + for f in adbc/*.cdx.json; do + cp "$f" "/tmp/sboms/$(basename "$f")" + done + ( cd pyo3 && cargo cyclonedx --format json ) for f in pyo3/*.cdx.json; do cp "$f" "/tmp/sboms/$(basename "$f")" @@ -160,8 +166,8 @@ jobs: echo "SBOMs:" ls -lh /tmp/sboms/ # Hard-stop if we lost coverage by accident. - test "$(ls /tmp/sboms/*.cdx.json 2>/dev/null | wc -l)" -ge 3 || { - echo "::error::expected >=3 SBOMs (root crate + pyo3 + napi), got $(ls /tmp/sboms/*.cdx.json 2>/dev/null | wc -l)" + test "$(ls /tmp/sboms/*.cdx.json 2>/dev/null | wc -l)" -ge 4 || { + echo "::error::expected >=4 SBOMs (kernel + ADBC + pyo3 + napi), got $(ls /tmp/sboms/*.cdx.json 2>/dev/null | wc -l)" exit 1 } @@ -194,6 +200,7 @@ jobs: --format=json \ --output-file=/tmp/osv-out.json \ --sbom=/tmp/sboms/databricks-sql-kernel.cdx.json \ + --sbom=/tmp/sboms/databricks-adbc.cdx.json \ --sbom=/tmp/sboms/databricks-sql-kernel-pyo3.cdx.json \ --sbom=/tmp/sboms/databricks-sql-kernel-napi.cdx.json || RC=$? if [[ "$RC" -gt 1 ]]; then diff --git a/.github/workflows/trigger-integration-tests.yml b/.github/workflows/trigger-integration-tests.yml index e358685a..446f3689 100644 --- a/.github/workflows/trigger-integration-tests.yml +++ b/.github/workflows/trigger-integration-tests.yml @@ -24,7 +24,7 @@ # Modeled on adbc-drivers/databricks's `trigger-integration-tests.yml` # (the C# ADBC equivalent). Differences: # - Single language (Rust) — no per-language path-filter fan-out. -# - Source paths are kernel-relative: src/**, napi/**, pyo3/**, +# - Source paths are kernel-relative: src/**, adbc/**, napi/**, pyo3/**, # Cargo.{toml,lock}, .github/workflows/**. # - Dispatched event-type is `kernel-pr-test`. # - Check-run name is "Kernel Integration Tests" — must match the @@ -512,10 +512,10 @@ jobs: fi # Path set mirrors the in-repo rust-e2e.yml's source filter # (src/**, tests/**, Cargo.toml, Cargo.lock, workflow files) - # plus napi/ and pyo3/ wrappers. `tests/` is included because a + # plus adbc/, napi/, and pyo3/ wrappers. `tests/` is included because a # test-only change can still break kernel-protocol invariants # that integration tests catch. - if echo "$CHANGED" | grep -qE "^(src/|tests/|napi/|pyo3/|Cargo\.toml|Cargo\.lock|\.github/workflows/)"; then + if echo "$CHANGED" | grep -qE "^(src/|tests/|adbc/|napi/|pyo3/|Cargo\.toml|Cargo\.lock|\.github/workflows/)"; then echo "changed=true" >> "$GITHUB_OUTPUT" echo "kernel source files changed" else diff --git a/CLAUDE.md b/CLAUDE.md index 7f52b18f..1c1a3d1c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -22,6 +22,10 @@ async API (`Session` → `Statement` → `ExecutedStatement` / surface) intended for direct Rust use, PyO3 / napi-rs wrappers, and a custom C ABI (skeleton today) for ODBC / Go consumers. +The standalone `adbc/` workspace implements ADBC 1.1 directly against that native +Rust API. Its optional standard ADBC C ABI is an outer compatibility surface; +the ADBC-to-kernel boundary remains native Rust. + The repo was seeded from `adbc-drivers/databricks` (Rust subtree); the v0 surface lives at the crate root and the legacy ADBC layer has been removed. @@ -76,6 +80,7 @@ Session -> Metadata (flat per-method catalog API) | `metadata/` | Shared SQL builders + schemas for `Metadata` | | `ffi/` | Custom C ABI for ODBC / Go (skeleton) | | `telemetry/` | Metrics collection | +| `adbc/` | Native Rust ADBC driver and optional driver-manager C ABI | ## Error handling diff --git a/Cargo.toml b/Cargo.toml index 83eda191..4de130fd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -222,16 +222,16 @@ crate-type = ["lib", "cdylib", "staticlib"] # Workspace — the kernel is its own single-member workspace root. # -# Neither `pyo3/` nor `napi/` is a member: both bindings opt INTO +# `adbc/`, `pyo3/`, and `napi/` are not members. The bindings require their +# own build and lockfile boundaries; pyo3 and napi also opt INTO # `tls-rustls` (see the `[features]` comment above for why), while # the kernel itself defaults to `tls-native` for direct-Rust / C-ABI # consumers. A single-workspace build would unify the kernel's # feature set to `tls-native ∪ tls-rustls` across all members, # trip the mutual-exclusion `compile_error!` in `src/lib.rs`, and -# defeat the per-binding TLS choice. Each binding therefore declares -# its own `[workspace]` (see `pyo3/Cargo.toml` and `napi/Cargo.toml`) -# and reaches the kernel via `path = ".."` — same source tree, three -# workspace views (kernel root, pyo3, napi). +# defeat the per-binding TLS choice. Each sub-crate therefore declares +# its own `[workspace]` and reaches the kernel via `path = ".."` — same +# source tree, four independent workspace views. [workspace] members = ["."] diff --git a/Makefile b/Makefile index f102d484..dc78df83 100644 --- a/Makefile +++ b/Makefile @@ -12,24 +12,29 @@ # See the License for the specific language governing permissions and # limitations under the License. -.PHONY: all build test fmt lint clean check coverage coverage-check c-abi-test +.PHONY: all build test fmt lint clean check coverage coverage-check c-abi-test adbc-ffi-test all: build build: cargo build + cargo build --manifest-path adbc/Cargo.toml test: cargo test + cargo test --manifest-path adbc/Cargo.toml --features ffi fmt: - cargo fmt + cargo fmt --all + cargo fmt --manifest-path adbc/Cargo.toml fmt-check: - cargo fmt -- --check + cargo fmt --all -- --check + cargo fmt --manifest-path adbc/Cargo.toml -- --check lint: - cargo clippy -- -D warnings + cargo clippy --all-targets -- -D warnings + cargo clippy --manifest-path adbc/Cargo.toml --all-targets --features ffi -- -D warnings # Compile the hand-written C smoke tests against the cdylib and run them. # Proves the C ABI in `src/ffi/` links and behaves from a real C consumer @@ -44,10 +49,25 @@ c-abi-test: LD_LIBRARY_PATH=target/debug DYLD_LIBRARY_PATH=target/debug ./target/c-abi/$$name || exit 1; \ done -check: fmt-check lint test c-abi-test +# Prove that the ADBC crate exports a loadable ADBC 1.1 C driver while its +# internal kernel integration remains native Rust. +adbc-ffi-test: + cargo test --manifest-path adbc/Cargo.toml --features ffi + cargo build --manifest-path adbc/Cargo.toml --features ffi --lib --example ffi_smoke + @case "$$(uname -s)" in \ + Darwin*) library=libdatabricks_adbc.dylib ;; \ + MINGW*|MSYS*|CYGWIN*) library=databricks_adbc.dll ;; \ + *) library=libdatabricks_adbc.so ;; \ + esac; \ + LD_LIBRARY_PATH="$(CURDIR)/adbc/target/debug" \ + DYLD_LIBRARY_PATH="$(CURDIR)/adbc/target/debug" \ + ./adbc/target/debug/examples/ffi_smoke "$(CURDIR)/adbc/target/debug/$$library" + +check: fmt-check lint test c-abi-test adbc-ffi-test clean: cargo clean + cargo clean --manifest-path adbc/Cargo.toml coverage: cargo llvm-cov --all-features --ignore-filename-regex "tests/" --html --open diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 95b5af07..41956347 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,6 +11,9 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added +- A native Rust ADBC 1.1 driver in `adbc/`, with an optional standard ADBC C + ABI for driver-manager loading from other languages. + ### Changed ### Updated diff --git a/README.md b/README.md index 0736d378..cae3f253 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,11 @@ surface) for direct Rust use, the PyO3 (Python) and napi-rs (Node.js) wrappers, and a C ABI for ODBC / Go consumers. See [`docs/spec-v0.md`](docs/spec-v0.md) for the API spec. +The separate [`adbc/`](adbc/) Cargo workspace implements ADBC 1.1 directly over this +native Rust API. It provides both Rust traits and an optional standard ADBC C +entry point for driver managers and other languages; the kernel boundary does +not use FFI. + ## Status Early. Expect breaking changes. @@ -33,8 +38,11 @@ Early. Expect breaking changes. ```bash cargo build -cargo test -make check # fmt + clippy + tests +cargo test --workspace +make check # workspace fmt + clippy + tests and native ABI smoke tests + +# ADBC is a separate Cargo workspace and is validated explicitly by make check. +cargo test --manifest-path adbc/Cargo.toml --features ffi ``` Native consumers that statically link the kernel and publish separate crash diff --git a/adbc/Cargo.lock b/adbc/Cargo.lock new file mode 100644 index 00000000..b73d5d0a --- /dev/null +++ b/adbc/Cargo.lock @@ -0,0 +1,3233 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adbc_core" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "365059b13a01bbf6f324b5bfe328232a819679731431f78105e2883256236858" +dependencies = [ + "arrow-array", + "arrow-schema", +] + +[[package]] +name = "adbc_driver_manager" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aac8bb789ff1f493bcb5d423c65b7a1b21ba5516f5e60797b4e1c64b34a2b61" +dependencies = [ + "adbc_core", + "adbc_ffi", + "arrow-array", + "arrow-schema", + "libloading", + "path-slash", + "regex", + "toml", + "windows-registry", + "windows-sys 0.61.2", +] + +[[package]] +name = "adbc_ffi" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdef84c12e9e8858b300440c36ca94ba24fb2e188175251dc39bb44ba3584e" +dependencies = [ + "adbc_core", + "arrow-array", + "arrow-schema", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher 0.4.4", + "cpufeatures 0.2.17", +] + +[[package]] +name = "aes" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35f0f96ce78e38c3dc6d8948aa8163d06385be74000f3c7a95bf1eef35d3ea32" +dependencies = [ + "cipher 0.5.2", + "cpubits", + "cpufeatures 0.3.1", + "zeroize", +] + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "const-random", + "getrandom 0.3.4", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "approx" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" +dependencies = [ + "num-traits", +] + +[[package]] +name = "arrow-array" +version = "59.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b5b1682924f11ecf6929689c16cbc69efbb6dd141b06ad98ee1cb10d858c43" +dependencies = [ + "ahash", + "arrow-buffer", + "arrow-data", + "arrow-schema", + "chrono", + "half", + "hashbrown 0.17.1", + "libc", + "num-complex", + "num-integer", + "num-traits", +] + +[[package]] +name = "arrow-buffer" +version = "59.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5d687afc6c927965a8a759f3b68de91933d9dfa2e1bb6e156bac84b85665e92" +dependencies = [ + "bytes", + "half", + "num-bigint 0.5.1", + "num-traits", +] + +[[package]] +name = "arrow-cast" +version = "59.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f23c3379feede42135ef27ca60e67f6e643cd4343ae74e4c8b16c83f55afd85" +dependencies = [ + "arrow-array", + "arrow-buffer", + "arrow-data", + "arrow-ord", + "arrow-schema", + "arrow-select", + "atoi", + "base64 0.23.1", + "chrono", + "half", + "lexical-core", + "num-traits", + "ryu", +] + +[[package]] +name = "arrow-data" +version = "59.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0a031c7ff5e2bdb443117054fb466af1d4df5b7f0ecbe197713dc8b113b1ba" +dependencies = [ + "arrow-buffer", + "arrow-schema", + "half", + "num-integer", + "num-traits", +] + +[[package]] +name = "arrow-ipc" +version = "59.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5dd1afadda2eb821aaf851bb4c0adef60c30cc0f1a29bd02fb99dd07fb9f58d" +dependencies = [ + "arrow-array", + "arrow-buffer", + "arrow-data", + "arrow-schema", + "arrow-select", + "flatbuffers", +] + +[[package]] +name = "arrow-ord" +version = "59.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "561b8209faa2cd489764b7fd07d7cb9e8d274d78048c38de59f77c41140cb834" +dependencies = [ + "arrow-array", + "arrow-buffer", + "arrow-data", + "arrow-schema", + "arrow-select", +] + +[[package]] +name = "arrow-schema" +version = "59.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e87acb0c6bf6237fca7a50d7b51e801c98a18a5fe6f3bb34f7d77b85ca165388" +dependencies = [ + "bitflags", +] + +[[package]] +name = "arrow-select" +version = "59.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c844141958d805b47d1208e0d12aac53fcf388ce8011639fe82aa492adde0bb4" +dependencies = [ + "ahash", + "arrow-array", + "arrow-buffer", + "arrow-data", + "arrow-schema", + "num-traits", +] + +[[package]] +name = "async-compression" +version = "0.4.51" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d5755640120b24961f8231e05892e4a4f7e0d04e8aeca161508c9c397946970" +dependencies = [ + "compression-codecs", + "compression-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "async-lock" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "atoi" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" +dependencies = [ + "num-traits", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", + "zeroize", +] + +[[package]] +name = "block-padding" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-padding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cbc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +dependencies = [ + "cipher 0.4.4", +] + +[[package]] +name = "cbc" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" +dependencies = [ + "cipher 0.5.2", +] + +[[package]] +name = "cc" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common 0.1.7", + "inout 0.1.4", +] + +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "block-buffer 0.12.1", + "crypto-common 0.2.2", + "inout 0.2.5", + "zeroize", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "compression-codecs" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cae36683101b2899f48bd31f8db9839437356188e3b1ff23096e73dab09ba8fe" +dependencies = [ + "compression-core", + "flate2", + "memchr", +] + +[[package]] +name = "compression-core" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ebdda89edc534bf8d5dd2857562633b6495557e5846552ade994b99ed13c36a" + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "const-random" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359" +dependencies = [ + "const-random-macro", +] + +[[package]] +name = "const-random-macro" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e" +dependencies = [ + "getrandom 0.2.17", + "once_cell", + "tiny-keccak", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctutils" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe3e9d21d39e6f39ff46e03d5b621424f88ee23d8a1672c6bfc9ccc7f2da4f6a" +dependencies = [ + "cmov", +] + +[[package]] +name = "dashmap" +version = "6.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c" +dependencies = [ + "cfg-if", + "crossbeam-utils", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", +] + +[[package]] +name = "databricks-adbc" +version = "0.1.0" +dependencies = [ + "adbc_core", + "adbc_driver_manager", + "adbc_ffi", + "arrow-array", + "arrow-buffer", + "arrow-schema", + "databricks-sql-kernel", + "serde_json", + "tokio", +] + +[[package]] +name = "databricks-sql-kernel" +version = "1.4.0" +dependencies = [ + "aes 0.9.3", + "arrow-array", + "arrow-buffer", + "arrow-cast", + "arrow-ipc", + "arrow-ord", + "arrow-schema", + "arrow-select", + "async-trait", + "base64 0.22.1", + "cbc 0.2.1", + "chrono", + "dashmap", + "dirs", + "futures", + "geo-traits", + "hex", + "hmac 0.13.0", + "jsonwebtoken", + "lz4_flex", + "moka", + "oauth2", + "open", + "pbkdf2 0.13.0", + "pkcs8", + "rand 0.10.3", + "reqwest", + "serde", + "serde_json", + "sha2 0.11.1", + "thiserror 2.0.21", + "tokio", + "tokio-util", + "tracing", + "tracing-subscriber", + "wkb", + "wkt", + "zeroize", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid 0.10.2", + "crypto-common 0.2.2", + "ctutils", +] + +[[package]] +name = "dirs" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.2", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flatbuffers" +version = "25.12.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35f6839d7b3b98adde531effaf34f0c2badc6f4735d26fe74709d8e513a96ef3" +dependencies = [ + "bitflags", + "rustc_version", +] + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "geo-traits" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e7c353d12a704ccfab1ba8bfb1a7fe6cb18b665bf89d37f4f7890edcd260206" +dependencies = [ + "geo-types", +] + +[[package]] +name = "geo-types" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "777d18aa0f12f8b285331cd867133ee14422b3f023f6d388034c47d43e28786a" +dependencies = [ + "approx", + "num-traits", + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "num-traits", + "zerocopy", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", + "zeroize", +] + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-tls" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" +dependencies = [ + "bytes", + "http-body-util", + "hyper", + "hyper-util", + "native-tls", + "tokio", + "tokio-native-tls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "block-padding 0.3.3", + "generic-array", +] + +[[package]] +name = "inout" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b5cf4372d022092674a83b8febf5865f7a573cc0c5baec5e49c879b6a20978f" +dependencies = [ + "block-padding 0.4.2", + "hybrid-array", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "is-docker" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3" +dependencies = [ + "once_cell", +] + +[[package]] +name = "is-wsl" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5" +dependencies = [ + "is-docker", + "once_cell", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "jsonwebtoken" +version = "9.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde" +dependencies = [ + "base64 0.22.1", + "js-sys", + "pem", + "ring", + "serde", + "serde_json", + "simple_asn1", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "lexical-core" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d8d125a277f807e55a77304455eb7b1cb52f2b18c143b60e766c120bd64a594" +dependencies = [ + "lexical-parse-float", + "lexical-parse-integer", + "lexical-util", + "lexical-write-float", + "lexical-write-integer", +] + +[[package]] +name = "lexical-parse-float" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52a9f232fbd6f550bc0137dcb5f99ab674071ac2d690ac69704593cb4abbea56" +dependencies = [ + "lexical-parse-integer", + "lexical-util", +] + +[[package]] +name = "lexical-parse-integer" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a7a039f8fb9c19c996cd7b2fcce303c1b2874fe1aca544edc85c4a5f8489b34" +dependencies = [ + "lexical-util", +] + +[[package]] +name = "lexical-util" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2604dd126bb14f13fb5d1bd6a66155079cb9fa655b37f875b3a742c705dbed17" + +[[package]] +name = "lexical-write-float" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50c438c87c013188d415fbabbb1dceb44249ab81664efbd31b14ae55dabb6361" +dependencies = [ + "lexical-util", + "lexical-write-integer", +] + +[[package]] +name = "lexical-write-integer" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "409851a618475d2d5796377cad353802345cba92c867d9fbcde9cf4eac4e14df" +dependencies = [ + "lexical-util", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c943259e342f1e06ff2da7a83eabdfe7f92ce10262688dbf1895ff0b3e6e4652" +dependencies = [ + "libc", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "lz4_flex" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecbdfe44b1bd960b68170b417450a628c43f7cf56bb3c5317e61cb230ee7f226" +dependencies = [ + "twox-hash", +] + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "moka" +version = "0.12.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4293f18e7567a1caf3c584855554377025c65e0aa445344d04171f5ad63d19b9" +dependencies = [ + "async-lock", + "crossbeam-channel", + "crossbeam-epoch", + "crossbeam-utils", + "equivalent", + "event-listener", + "futures-util", + "parking_lot", + "portable-atomic", + "smallvec", + "tagptr", + "uuid", +] + +[[package]] +name = "native-tls" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "oauth2" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51e219e79014df21a225b1860a479e2dcd7cbd9130f4defd4bd0e191ea31d67d" +dependencies = [ + "base64 0.22.1", + "chrono", + "getrandom 0.2.17", + "http", + "rand 0.8.8", + "reqwest", + "serde", + "serde_json", + "serde_path_to_error", + "sha2 0.10.9", + "thiserror 1.0.69", + "url", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "open" +version = "5.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d8c8b8e725ad26404d6896eb2f064294a0a7b4f1d9120210d85544684c4ca95" +dependencies = [ + "is-wsl", + "libc", +] + +[[package]] +name = "openssl" +version = "0.10.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" +dependencies = [ + "bitflags", + "cfg-if", + "foreign-types", + "libc", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "openssl-sys" +version = "0.9.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "path-slash" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e91099d4268b0e11973f036e885d652fb0b21fedcf69738c627f94db6a44f42" + +[[package]] +name = "pbkdf2" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" +dependencies = [ + "digest 0.10.7", + "hmac 0.12.1", +] + +[[package]] +name = "pbkdf2" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629" +dependencies = [ + "digest 0.11.3", + "hmac 0.13.0", +] + +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64 0.22.1", + "serde_core", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkcs5" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e847e2c91a18bfa887dd028ec33f2fe6f25db77db3619024764914affe8b69a6" +dependencies = [ + "aes 0.8.4", + "cbc 0.1.2", + "der", + "pbkdf2 0.12.2", + "scrypt", + "sha2 0.10.9", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "pkcs5", + "rand_core 0.6.4", + "spki", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "redox_users" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" +dependencies = [ + "getrandom 0.2.17", + "libredox", + "thiserror 2.0.21", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-tls", + "hyper-util", + "js-sys", + "log", + "native-tls", + "percent-encoding", + "pin-project-lite", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-native-tls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "salsa20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213" +dependencies = [ + "cipher 0.4.4", +] + +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "scrypt" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f" +dependencies = [ + "pbkdf2 0.12.2", + "salsa20", + "sha2 0.10.9", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simple_asn1" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" +dependencies = [ + "num-bigint 0.4.8", + "num-traits", + "thiserror 2.0.21", + "time", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tagptr" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tiny-keccak" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" +dependencies = [ + "crunchy", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "1.1.8+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +dependencies = [ + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.17+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "async-compression", + "bitflags", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "pin-project-lite", + "tokio", + "tokio-util", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "twox-hash" +version = "2.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", + "serde_derive", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.126" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.76" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c62df1340f32221cb9c54d6a27b030e3dba64361d4a95bed55f9aacb44da291d" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.126" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.126" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.126" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wkb" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04ab2f2845abe967a213998446345a1a6fc9a8f318cd88f668a8e507861d13bc" +dependencies = [ + "byteorder", + "geo-traits", + "num_enum", + "thiserror 1.0.69", +] + +[[package]] +name = "wkt" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "efb2b923ccc882312e559ffaa832a055ba9d1ac0cc8e86b3e25453247e4b81d7" +dependencies = [ + "geo-traits", + "log", + "num-traits", + "thiserror 1.0.69", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/adbc/Cargo.toml b/adbc/Cargo.toml new file mode 100644 index 00000000..091bb9ad --- /dev/null +++ b/adbc/Cargo.toml @@ -0,0 +1,53 @@ +[package] +name = "databricks-adbc" +version = "0.1.0" +edition = "2021" +rust-version = "1.89" +authors = ["Databricks"] +license = "Apache-2.0" +description = "ADBC driver for Databricks built on the Databricks SQL Kernel" +repository = "https://github.com/databricks/databricks-sql-kernel" +readme = "README.md" +keywords = ["databricks", "adbc", "arrow", "database", "sql"] +categories = ["database"] +include = [ + "/src/**", + "/tests/**", + "/examples/**", + "/README.md", + "/LICENSE", + "/PACKAGING.md", +] +# Remove only after the public kernel crate and release process are available. +publish = false + +[dependencies] +adbc_core = "0.24" +adbc_ffi = { version = "0.24", optional = true } +arrow-array = "59" +arrow-buffer = "59" +arrow-schema = "59" +# Native Rust integration with the kernel crate in this repository. The +# version is retained so Cargo can replace the path when packaging after both +# crates become publishable. +databricks-sql-kernel = { version = "1.4.0", path = ".." } +serde_json = "1" +tokio = { version = "1", features = ["rt-multi-thread"] } + +[dev-dependencies] +adbc_driver_manager = "0.24" + +[features] +default = [] +ffi = ["dep:adbc_ffi"] + +[lib] +crate-type = ["lib", "cdylib", "staticlib"] + +[[example]] +name = "ffi_smoke" +required-features = ["ffi"] + +[workspace] +members = ["."] +resolver = "2" diff --git a/adbc/LICENSE b/adbc/LICENSE new file mode 100644 index 00000000..61fd3863 --- /dev/null +++ b/adbc/LICENSE @@ -0,0 +1,210 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +-------------------------------------------------------------------------------- + +This project includes code from Apache Arrow ADBC. + +Copyright: 2022 The Apache Software Foundation. +Home page: https://arrow.apache.org/ +License: http://www.apache.org/licenses/LICENSE-2.0 diff --git a/adbc/PACKAGING.md b/adbc/PACKAGING.md new file mode 100644 index 00000000..de548db6 --- /dev/null +++ b/adbc/PACKAGING.md @@ -0,0 +1,33 @@ +# Packaging and release gates + +The crate produces three library forms: + +- `rlib` for native Rust consumers; +- `cdylib` for ADBC driver-manager loading; +- `staticlib` for consumers that link the ADBC entry point statically. + +The optional `ffi` feature exports `AdbcDatabricksInit` and the conventional +`AdbcDriverInit` alias. This is an outer ADBC compatibility layer: the driver +continues to call the SQL kernel through its native Rust API. + +Repository CI must validate all of the following before release: + +1. `cargo test --manifest-path adbc/Cargo.toml --features ffi` passes on the declared MSRV. +2. A release `cdylib` dynamically loads through both exported entry points + using `adbc_driver_manager` and allocates an ADBC database. +3. `cargo package --manifest-path adbc/Cargo.toml --list` contains only the manifest's + source, tests, examples, documentation, and license files. +4. Repository license, advisory, and SBOM checks explicitly scan the standalone + ADBC dependency graph. +5. Platform-specific release jobs validate Linux, macOS, and Windows artifacts. + +Publication remains disabled while the repository and kernel crate are not +publicly released. A release must publish `databricks-sql-kernel` first, then +publish `databricks-adbc` with the matching version requirement. Both crates +are built from the same repository source during development; no kernel FFI or +C ABI is involved in that dependency. + +The declared MSRV is Rust 1.89. Cargo dependencies used by internal CI must +resolve through the Databricks package proxy. Release artifacts must include +Apache 2.0 licensing and generated third-party attribution under the owning +repository's release process. diff --git a/adbc/README.md b/adbc/README.md new file mode 100644 index 00000000..113a7c17 --- /dev/null +++ b/adbc/README.md @@ -0,0 +1,193 @@ +# Databricks ADBC Driver for Rust + +This crate implements ADBC 1.1 for Databricks. It calls the Databricks SQL +Kernel through its native Rust API and returns Arrow 59 record batches without +an IPC or C-ABI conversion between the driver and kernel. + +The crate provides two consumer surfaces: + +- the Rust `adbc_core` 0.24 traits; and +- an optional ADBC C driver for driver managers and other languages. + +The C surface does not change the internal integration: it is an export layer +over the same Rust implementation. + +## Build + +```text +cargo build --manifest-path adbc/Cargo.toml --release +cargo build --manifest-path adbc/Cargo.toml --release --features ffi +``` + +The `ffi` build exports both `AdbcDatabricksInit` and the conventional +`AdbcDriverInit` alias. The release library is produced as an `rlib`, `cdylib`, +and `staticlib`; see `PACKAGING.md` for release gates. + +This crate is a standalone Cargo workspace inside the kernel repository. Cargo +builds the kernel directly from `../` for repository development. The +accompanying version constraint becomes the registry dependency when the +crates are published; publish the matching kernel version first. + +## Connect from Rust + +Create a `Driver`, then create a database with a workspace URI, one +warehouse selector, and authentication options: + +Native Rust applications may instead create a database with +`Database::with_runtime(Arc)`. The runtime must use +Tokio's multi-thread scheduler, remains owned by the application, and is shared +by every connection created from that database. The standard ADBC `Driver` +surface creates a bounded driver-owned runtime shared at database scope. + +```rust,no_run +use adbc_core::options::{OptionDatabase, OptionValue}; +use adbc_core::{Database as _, Driver as _}; +use databricks_adbc::Driver; + +let mut driver = Driver; +let database = driver.new_database_with_opts([ + ( + OptionDatabase::Uri, + OptionValue::String("https://example.cloud.databricks.com".into()), + ), + ( + OptionDatabase::Other("adbc.databricks.http_path".into()), + OptionValue::String("/sql/1.0/warehouses/warehouse-id".into()), + ), + ( + OptionDatabase::Other("adbc.databricks.auth.token".into()), + OptionValue::String(std::env::var("DATABRICKS_TOKEN")?), + ), +])?; +# Ok::<(), Box>(()) +``` + +Exactly one of `adbc.databricks.http_path` and +`adbc.databricks.warehouse_id` is required. Preserve an organization query +parameter in the HTTP path when the workspace connection details include one. +Canonical `adbc.databricks.*` names take precedence over compatibility aliases. + +## Authentication + +Set `adbc.databricks.auth.type` to one of `pat`, `oauth_m2m`, `oauth_u2m`, +`oauth_m2m_private_key`, or `azure_service_principal`. When the type is omitted, +the driver infers it only when the supplied credentials are unambiguous. + +| Mode | Required options | +| --- | --- | +| PAT | `adbc.databricks.auth.token` | +| OAuth M2M | `adbc.databricks.oauth.client_id`, `adbc.databricks.oauth.client_secret` | +| OAuth U2M | interactive login; optional client ID, scopes, redirect ports, callback timeout, and encrypted token-cache settings | +| Private-key OAuth M2M | client ID, `adbc.databricks.oauth.jwt.key_file`; optional key ID, algorithm, and passphrase | +| Azure service principal | `adbc.databricks.azure.client_id`, client secret, tenant ID, and workspace resource ID | + +`adbc.databricks.identity_federation_client_id` can be added to supported base +authentication modes. Client secrets, tokens, passphrases, proxy passwords, and +private keys are write-only and redacted from debug output. Supply them at +runtime; do not place them in source code, manifests, logs, or connection URLs. +Do not include connection options, environment dumps, token-cache contents, or +credential files in bug reports. Rotate a credential immediately if it may +have appeared in output retained by an application or support system. + +## Configuration + +The main database option families are: + +| Family | Options | +| --- | --- | +| Namespace | `adbc.databricks.catalog`, `adbc.databricks.schema` | +| Session | `adbc.databricks.session_conf.`, `adbc.databricks.ssp_ansi_mode`, `adbc.databricks.ssp_timezone`, `adbc.databricks.query_tags` | +| HTTP | request/overall timeouts, idle pool size, retry limits/backoff, response compression, JSON custom headers | +| Proxy | URL, username, password, bypass hosts | +| TLS/mTLS | CA file or PEM, client certificate/key file or PEM, self-signed and hostname-verification controls | +| Logging | filter and file | +| Telemetry | enablement, batch/flush/retry settings, close timeout, circuit breaker settings | +| Results | complex datatype support, geospatial representation, CloudFetch enablement and buffering | +| Execution | `adbc.databricks.enable_direct_results` (default `true`); set `false` to use `wait_timeout=0s` and status polling | +| Metadata | `adbc.databricks.metadata.escape_catalog_name` | + +Proxy credentials must use the dedicated options; URL userinfo is rejected. +Certificate and key options must be supplied as a pair. File-backed credential +and TLS values are read during database initialization. +The self-signed-certificate and hostname-verification bypasses weaken TLS and +must remain disabled outside isolated test environments. +Telemetry numeric options accept either ADBC integer values or their decimal +string forms, as used by connection-string and cross-driver adapters. + +`adbc.databricks.metadata.escape_catalog_name` defaults to `true`. It escapes +only unescaped `_` characters in `GetObjects` and metadata-command catalog +patterns, matching the catalog-name behavior of the Python and Node drivers. +It preserves `%` wildcards and existing `\_` escapes and does not alter schema, +table, or column patterns. Set it to `false` for raw ADBC catalog-pattern +semantics. + +Statement options include positional or named parameter style, query tags, +the portable `adbc.apache.statement.query_timeout_s` client deadline (with `0` +meaning unlimited), a millisecond Databricks client-timeout alias, server +timeout, row limit, and +`adbc.databricks.statement.rows_fetched_per_block` for client-observed Arrow +batch slicing, and `adbc.databricks.statement.conf.`. `bind` and `bind_stream` accept Arrow +batches; multi-row bindings execute sequentially and expose one logical result +stream. `prepare` is client-side. Parameter schemas may contain nullable Arrow +`Null` fields when the server does not expose exact inferred types. + +For compatibility with metadata-statement consumers, set +`adbc.apache.statement.is_metadata_command` to the string `true`, set the SQL +text to `GetCatalogs`, `GetSchemas`, `GetTables`, `GetColumns`, +`GetPrimaryKeys`, or `GetCrossReference`, and supply +filters through `adbc.get_metadata.target_catalog`, `target_db_schema`, +`target_table`, `target_column`, and `target_table_types`. `GetCrossReference` +also accepts the foreign-target catalog, schema, and table keys. +`adbc.get_metadata.escape_pattern_wildcards` defaults to `false`; when set to +`true`, backslash, `_`, and `%` are escaped so the supplied filters are treated +as literal identifiers. These +commands return the flat JDBC metadata schemas used by the other Databricks +drivers; `GetColumns` includes the Databricks `BASE_TYPE_NAME` extension. This +compatibility surface is separate from standard nested ADBC `GetObjects`. + +Native Rust callers can use `Statement::submit` to obtain a borrowing +`SubmittedStatement`, poll its status, cancel it, or await/fetch its result. +The handle prevents mutation or resubmission of the statement while the +operation is pending. Client query deadlines and rows-per-block slicing apply +equally to synchronous and submitted execution. Dropping a submitted handle or +an incompletely consumed reader triggers best-effort server cleanup. + +`adbc.databricks.cloudfetch.enabled` is wired to the kernel result +configuration. The current kernel/server combination does not yet support the +`false` path because SEA rejects inline Arrow results; disabling CloudFetch is +therefore not a production-supported configuration in this release. + +## ADBC behavior + +The driver supports query/update execution, cancellation, result draining, +`GetInfo`, `GetObjects`, table types, table schemas, catalogs/schemas, and +dedicated primary-key/cross-reference metadata commands. As in the C# driver, +`GetObjects` leaves `table_constraints` null; applications request key metadata +through the dedicated commands described above. Errors preserve ADBC status, +SQLSTATE, vendor code, and Databricks details when supplied by the kernel. + +Transactions are ignored by the current kernel configuration: autocommit stays +enabled, and disabling it returns `NotImplemented`. Partitioned execution, +reading partitions, statistics, and progress reporting are optional ADBC +surfaces and currently return `NotImplemented`. Native Rust connection +cancellation is supported. The optional C driver intentionally reports +connection and statement cancellation as `NotImplemented` because `adbc_ffi` +0.24 cannot export concurrent cancel calls without violating Rust aliasing +rules. Native Rust cancellation handles remain available internally. + +The standard ADBC methods are synchronous. The native Rust submit/poll extension +provides caller-driven non-blocking execution. Both surfaces are safe to call +from outside Tokio or from current-thread and multi-thread Tokio runtimes; +kernel work is bridged without nesting `Runtime::block_on` on the caller +runtime. + +## Compatibility and status + +The current implementation targets Rust 1.89+, Rust edition 2021, ADBC 1.1 (`adbc_core` 0.24), +Arrow 59, and `databricks-sql-kernel` 1.4. Linux x86-64 is the locally validated +platform. Windows and macOS artifacts require their platform release gates +before a production release. + +Repository CI validates the native Rust surface, the optional ADBC C ABI, and +dynamic loading through both exported entry points. Cross-driver qualification +and release evidence remain separate from this public API documentation. diff --git a/adbc/examples/benchmark.rs b/adbc/examples/benchmark.rs new file mode 100644 index 00000000..1109a2d1 --- /dev/null +++ b/adbc/examples/benchmark.rs @@ -0,0 +1,592 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Client-observed Rust ADBC overhead benchmark against the direct Rust kernel. + +use std::env; +use std::fs::{self, File}; +use std::io::{BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::{Instant, SystemTime, UNIX_EPOCH}; + +use adbc_core::options::{OptionDatabase, OptionValue}; +use adbc_core::{Connection as _, Database as _, Driver as _, Statement as _}; +use databricks_adbc::{Connection, Driver}; +use databricks_sql_kernel::{AuthConfig, ResultBatch, Session}; +use serde_json::{json, Value}; + +const DEFAULT_SIZES: &str = "0.25,0.5,1,2,3,4,5,10,25,50,100"; +const PAYLOAD_BYTES: u64 = 1024; +const LOGICAL_BYTES_PER_ROW: u64 = PAYLOAD_BYTES + 8; + +fn kernel_revision() -> String { + let Ok(output) = Command::new("git") + .args(["rev-parse", "HEAD"]) + .current_dir(env!("CARGO_MANIFEST_DIR")) + .output() + else { + return "unavailable".into(); + }; + if !output.status.success() { + return "unavailable".into(); + } + String::from_utf8_lossy(&output.stdout).trim().to_owned() +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Implementation { + Adbc, + Kernel, +} + +impl Implementation { + fn label(self) -> &'static str { + match self { + Self::Adbc => "rust-adbc", + Self::Kernel => "rust-kernel-direct", + } + } + fn index(self) -> usize { + match self { + Self::Adbc => 0, + Self::Kernel => 1, + } + } +} + +#[derive(Clone, Copy, Debug)] +struct Observation { + latency_ms: f64, + rows: usize, + arrow_bytes: usize, + batches: usize, +} +impl Observation { + fn shape(self) -> (usize, usize, usize) { + (self.rows, self.arrow_bytes, self.batches) + } +} + +struct LiveConfig { + host: String, + http_path: String, + token: String, +} +struct KernelClient { + runtime: tokio::runtime::Runtime, + session: Session, +} + +impl KernelClient { + fn open(config: &LiveConfig) -> Result> { + let runtime = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build()?; + let session = runtime.block_on( + Session::builder() + .http_path(&config.host, &config.http_path) + .auth(AuthConfig::Pat { + token: config.token.clone(), + identity_federation_client_id: None, + }) + .open(), + )?; + Ok(Self { runtime, session }) + } + + fn observe(&self, sql: &str) -> Result> { + let mut statement = self.session.statement(); + statement.spec().sql(sql); + let started = Instant::now(); + let mut executed = self.runtime.block_on(statement.execute())?; + let (mut rows, mut arrow_bytes, mut batches) = (0, 0, 0); + while let Some(batch) = self.runtime.block_on(executed.next_batch())? { + match batch { + ResultBatch::Arrow(batch) => { + rows += batch.num_rows(); + arrow_bytes += batch.get_array_memory_size(); + batches += 1; + } + _ => return Err("kernel returned a non-Arrow result batch".into()), + } + } + Ok(Observation { + latency_ms: started.elapsed().as_secs_f64() * 1000.0, + rows, + arrow_bytes, + batches, + }) + } +} + +fn required_env(name: &str) -> Result> { + env::var(name).map_err(|_| format!("{name} must be set").into()) +} + +fn parse_positive_usize(name: &str, default: usize) -> Result> { + let value = env::var(name) + .unwrap_or_else(|_| default.to_string()) + .parse::()?; + if value == 0 { + return Err(format!("{name} must be positive").into()); + } + Ok(value) +} + +fn parse_sizes(raw: &str) -> Result, Box> { + let sizes: Vec<_> = raw + .split(',') + .map(|value| { + let size = value.trim().parse::()?; + if !size.is_finite() || size <= 0.0 { + return Err(format!("invalid logical size {value:?}").into()); + } + Ok(size) + }) + .collect::>>()?; + if sizes.is_empty() { + return Err("at least one logical size is required".into()); + } + Ok(sizes) +} + +fn sizes() -> Result, Box> { + parse_sizes(&env::var("DATABRICKS_BENCH_SIZES_MIB").unwrap_or_else(|_| DEFAULT_SIZES.into())) +} + +fn query(size_mib: f64) -> String { + let target_bytes = (size_mib * 1024.0 * 1024.0).ceil() as u64; + let rows = target_bytes.div_ceil(LOGICAL_BYTES_PER_ROW); + format!("SELECT id, repeat('x', {PAYLOAD_BYTES}) AS payload FROM range({rows})") +} + +fn order_for(repetition: usize) -> [Implementation; 2] { + if repetition.is_multiple_of(2) { + [Implementation::Adbc, Implementation::Kernel] + } else { + [Implementation::Kernel, Implementation::Adbc] + } +} + +fn percentile(sorted: &[f64], fraction: f64) -> f64 { + let rank = fraction * (sorted.len() - 1) as f64; + let (lower, upper) = (rank.floor() as usize, rank.ceil() as usize); + sorted[lower] + (sorted[upper] - sorted[lower]) * (rank - lower as f64) +} + +fn paired_overhead(adbc: Observation, kernel: Observation) -> (f64, f64) { + ( + adbc.latency_ms - kernel.latency_ms, + adbc.latency_ms / kernel.latency_ms, + ) +} + +fn paired_sample_csv(size_mib: f64, repetition: usize, overhead_ms: f64, ratio: f64) -> String { + [ + "rust-adbc-vs-kernel".into(), + size_mib.to_string(), + "paired_sample".into(), + repetition.to_string(), + String::new(), + String::new(), + String::new(), + String::new(), + String::new(), + String::new(), + String::new(), + format!("{overhead_ms:.3}"), + format!("{ratio:.6}"), + String::new(), + String::new(), + String::new(), + String::new(), + ] + .join(",") +} + +fn paired_summary_csv( + size_mib: f64, + p50_overhead_ms: f64, + p95_overhead_ms: f64, + p50_ratio: f64, + p95_ratio: f64, +) -> String { + [ + "rust-adbc-vs-kernel".into(), + size_mib.to_string(), + "paired_summary".into(), + String::new(), + String::new(), + String::new(), + String::new(), + String::new(), + String::new(), + String::new(), + String::new(), + String::new(), + String::new(), + format!("{p50_overhead_ms:.3}"), + format!("{p95_overhead_ms:.3}"), + format!("{p50_ratio:.6}"), + format!("{p95_ratio:.6}"), + ] + .join(",") +} + +fn open_adbc(config: &LiveConfig) -> Result> { + let mut driver = Driver; + let database = driver.new_database_with_opts([ + ( + OptionDatabase::Uri, + OptionValue::String(config.host.clone()), + ), + ( + OptionDatabase::Other("adbc.databricks.http_path".into()), + OptionValue::String(config.http_path.clone()), + ), + ( + OptionDatabase::Other("adbc.databricks.auth.type".into()), + OptionValue::String("pat".into()), + ), + ( + OptionDatabase::Other("adbc.databricks.auth.token".into()), + OptionValue::String(config.token.clone()), + ), + ])?; + Ok(database.new_connection()?) +} + +fn observe_adbc( + connection: &mut Connection, + sql: &str, +) -> Result> { + let mut statement = connection.new_statement()?; + statement.set_sql_query(sql)?; + let started = Instant::now(); + let reader = statement.execute()?; + let (mut rows, mut arrow_bytes, mut batches) = (0, 0, 0); + for batch in reader { + let batch = batch?; + rows += batch.num_rows(); + arrow_bytes += batch.get_array_memory_size(); + batches += 1; + } + Ok(Observation { + latency_ms: started.elapsed().as_secs_f64() * 1000.0, + rows, + arrow_bytes, + batches, + }) +} + +fn load_live_config() -> Result> { + let token = fs::read_to_string(required_env("DATABRICKS_TOKEN_FILE")?)? + .trim() + .to_owned(); + if token.is_empty() { + return Err("DATABRICKS_TOKEN_FILE is empty".into()); + } + Ok(LiveConfig { + host: required_env("DATABRICKS_HOST")?, + http_path: required_env("DATABRICKS_HTTP_PATH")?, + token, + }) +} + +fn output_prefix() -> Result> { + let prefix = PathBuf::from(required_env("DATABRICKS_BENCH_OUTPUT_PREFIX")?); + if prefix.as_os_str().is_empty() { + return Err("DATABRICKS_BENCH_OUTPUT_PREFIX must not be empty".into()); + } + Ok(prefix) +} + +fn output_path(prefix: &Path, extension: &str) -> PathBuf { + let mut value = prefix.as_os_str().to_owned(); + value.push(format!(".{extension}")); + PathBuf::from(value) +} + +fn dry_run(sizes: &[f64], warmups: usize, samples: usize) -> Value { + json!({ + "mode": "dry-run", + "logical_bytes_per_row": LOGICAL_BYTES_PER_ROW, + "warmups_per_implementation": warmups, + "samples_per_implementation": samples, + "ordering": "AB/BA alternated by repetition within every size and phase", + "timed_region": "execute through complete Arrow fetch", + "matrix": sizes.iter().map(|size| json!({ + "size_mib": size, "sql": query(*size), + "warmup_orders": (0..warmups).map(|i| order_for(i).map(Implementation::label)).collect::>(), + "sample_orders": (0..samples).map(|i| order_for(i).map(Implementation::label)).collect::>(), + })).collect::>(), + }) +} + +fn observe( + implementation: Implementation, + adbc: &mut Connection, + kernel: &KernelClient, + sql: &str, +) -> Result> { + match implementation { + Implementation::Adbc => observe_adbc(adbc, sql), + Implementation::Kernel => kernel.observe(sql), + } +} + +fn main() -> Result<(), Box> { + let dry = env::args().any(|arg| arg == "--dry-run"); + let warmups = parse_positive_usize("DATABRICKS_BENCH_WARMUPS", 5)?; + let samples = parse_positive_usize("DATABRICKS_BENCH_SAMPLES", 30)?; + let sizes = sizes()?; + if dry { + println!( + "{}", + serde_json::to_string_pretty(&dry_run(&sizes, warmups, samples))? + ); + return Ok(()); + } + + let prefix = output_prefix()?; + let config = load_live_config()?; + let mut adbc = open_adbc(&config)?; + let kernel = KernelClient::open(&config)?; + let started_at_unix_ms = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis(); + let mut csv = BufWriter::new(File::create(output_path(&prefix, "csv"))?); + writeln!( + csv, + "implementation,size_mib,phase,repetition,position,latency_ms,rows,arrow_bytes,batches,p50_ms,p95_ms,overhead_ms,ratio,p50_overhead_ms,p95_overhead_ms,p50_ratio,p95_ratio" + )?; + let (mut json_samples, mut summaries) = (Vec::new(), Vec::new()); + let (mut paired_samples, mut paired_summaries) = (Vec::new(), Vec::new()); + + for size_mib in &sizes { + let sql = query(*size_mib); + for repetition in 0..warmups { + let mut shapes = Vec::new(); + for (position, implementation) in order_for(repetition).into_iter().enumerate() { + let value = observe(implementation, &mut adbc, &kernel, &sql)?; + shapes.push(value.shape()); + writeln!( + csv, + "{},{size_mib},warmup,{},{},{:.3},{},{},{},,,,,,,,,", + implementation.label(), + repetition + 1, + position + 1, + value.latency_ms, + value.rows, + value.arrow_bytes, + value.batches + )?; + } + if shapes[0] != shapes[1] { + return Err(format!("result shape mismatch during {size_mib} MiB warmup").into()); + } + } + + let mut observations = [Vec::with_capacity(samples), Vec::with_capacity(samples)]; + for repetition in 0..samples { + let mut shapes = Vec::new(); + for (position, implementation) in order_for(repetition).into_iter().enumerate() { + let value = observe(implementation, &mut adbc, &kernel, &sql)?; + shapes.push(value.shape()); + observations[implementation.index()].push(value); + writeln!( + csv, + "{},{size_mib},sample,{},{},{:.3},{},{},{},,,,,,,,,", + implementation.label(), + repetition + 1, + position + 1, + value.latency_ms, + value.rows, + value.arrow_bytes, + value.batches + )?; + json_samples.push(json!({"implementation": implementation.label(), "size_mib": size_mib, + "repetition": repetition + 1, "position": position + 1, "latency_ms": value.latency_ms, + "rows": value.rows, "arrow_bytes": value.arrow_bytes, "batches": value.batches})); + } + if shapes[0] != shapes[1] { + return Err(format!("result shape mismatch during {size_mib} MiB sample").into()); + } + } + + for implementation in [Implementation::Adbc, Implementation::Kernel] { + let values = &observations[implementation.index()]; + let mut latencies: Vec<_> = values.iter().map(|v| v.latency_ms).collect(); + latencies.sort_by(f64::total_cmp); + let shape = values[0]; + let p50 = percentile(&latencies, 0.50); + let p95 = percentile(&latencies, 0.95); + writeln!( + csv, + "{},{size_mib},summary,,,,{},{},{},{:.3},{:.3},,,,,,", + implementation.label(), + shape.rows, + shape.arrow_bytes, + shape.batches, + p50, + p95 + )?; + summaries.push( + json!({"implementation": implementation.label(), "size_mib": size_mib, + "p50_ms": p50, "p95_ms": p95, + "rows": shape.rows, "arrow_bytes": shape.arrow_bytes, "batches": shape.batches}), + ); + } + + let mut overheads = Vec::with_capacity(samples); + let mut ratios = Vec::with_capacity(samples); + for (repetition, (adbc, kernel)) in observations[0] + .iter() + .zip(observations[1].iter()) + .enumerate() + { + let (overhead_ms, ratio) = paired_overhead(*adbc, *kernel); + overheads.push(overhead_ms); + ratios.push(ratio); + writeln!( + csv, + "{}", + paired_sample_csv(*size_mib, repetition + 1, overhead_ms, ratio) + )?; + paired_samples.push(json!({ + "size_mib": size_mib, + "repetition": repetition + 1, + "first": order_for(repetition)[0].label(), + "adbc_latency_ms": adbc.latency_ms, + "kernel_latency_ms": kernel.latency_ms, + "overhead_ms": overhead_ms, + "ratio": ratio, + })); + } + overheads.sort_by(f64::total_cmp); + ratios.sort_by(f64::total_cmp); + let p50_overhead_ms = percentile(&overheads, 0.50); + let p95_overhead_ms = percentile(&overheads, 0.95); + let p50_ratio = percentile(&ratios, 0.50); + let p95_ratio = percentile(&ratios, 0.95); + writeln!( + csv, + "{}", + paired_summary_csv( + *size_mib, + p50_overhead_ms, + p95_overhead_ms, + p50_ratio, + p95_ratio, + ) + )?; + paired_summaries.push(json!({ + "size_mib": size_mib, + "p50_overhead_ms": p50_overhead_ms, + "p95_overhead_ms": p95_overhead_ms, + "p50_ratio": p50_ratio, + "p95_ratio": p95_ratio, + })); + csv.flush()?; + } + + let report = json!({"schema_version": 1, "metadata": { + "started_at_unix_ms": started_at_unix_ms, "host": config.host, "http_path": config.http_path, + "credentials": "token read from DATABRICKS_TOKEN_FILE; value not retained", + "driver_version": env!("CARGO_PKG_VERSION"), + "kernel_revision": kernel_revision(), + "build_profile": if cfg!(debug_assertions) { "debug" } else { "release" }, + "client_os": env::consts::OS, "client_arch": env::consts::ARCH, + "logical_bytes_per_row": LOGICAL_BYTES_PER_ROW, "sizes_mib": sizes, + "warmups_per_implementation": warmups, "samples_per_implementation": samples, + "ordering": "AB/BA alternated by repetition within every size and phase", + "timed_region": "execute through complete Arrow fetch", + "connections": "one persistent connection/session per implementation"}, + "queries": sizes.iter().map(|s| json!({"size_mib": s, "sql": query(*s)})).collect::>(), + "summaries": summaries, "samples": json_samples, + "paired_summaries": paired_summaries, "paired_samples": paired_samples}); + serde_json::to_writer_pretty( + BufWriter::new(File::create(output_path(&prefix, "json"))?), + &report, + )?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn default_sizes_match_matrix() { + assert_eq!( + parse_sizes(DEFAULT_SIZES).unwrap(), + vec![0.25, 0.5, 1.0, 2.0, 3.0, 4.0, 5.0, 10.0, 25.0, 50.0, 100.0] + ); + } + #[test] + fn query_is_deterministic() { + assert_eq!( + query(0.25), + "SELECT id, repeat('x', 1024) AS payload FROM range(255)" + ); + assert_eq!(query(0.25), query(0.25)); + } + #[test] + fn ordering_alternates() { + assert_eq!(order_for(0), [Implementation::Adbc, Implementation::Kernel]); + assert_eq!(order_for(1), [Implementation::Kernel, Implementation::Adbc]); + } + #[test] + fn percentile_interpolates() { + assert_eq!(percentile(&[1.0, 2.0, 3.0, 4.0], 0.50), 2.5); + assert!((percentile(&[1.0, 2.0, 3.0, 4.0], 0.95) - 3.85).abs() < 1e-12); + } + #[test] + fn paired_overhead_preserves_signed_difference_and_ratio() { + let adbc = Observation { + latency_ms: 12.0, + rows: 1, + arrow_bytes: 2, + batches: 3, + }; + let kernel = Observation { + latency_ms: 10.0, + ..adbc + }; + assert_eq!(paired_overhead(adbc, kernel), (2.0, 1.2)); + let faster_adbc = Observation { + latency_ms: 8.0, + ..adbc + }; + assert_eq!(paired_overhead(faster_adbc, kernel), (-2.0, 0.8)); + } + #[test] + fn paired_csv_rows_match_the_declared_schema() { + let sample = paired_sample_csv(0.25, 1, -2.0, 0.8); + let summary = paired_summary_csv(0.25, -1.0, 2.0, 0.9, 1.1); + assert_eq!(sample.split(',').count(), 17); + assert_eq!(summary.split(',').count(), 17); + assert_eq!(sample.split(',').nth(11), Some("-2.000")); + assert_eq!(summary.split(',').nth(13), Some("-1.000")); + } + #[test] + fn dry_run_is_secret_free_and_complete() { + let p = dry_run(&[0.25], 5, 30); + let s = serde_json::to_string(&p).unwrap(); + assert!(!s.contains("token")); + assert_eq!(p["matrix"][0]["warmup_orders"].as_array().unwrap().len(), 5); + assert_eq!( + p["matrix"][0]["sample_orders"].as_array().unwrap().len(), + 30 + ); + } +} diff --git a/adbc/examples/ffi_smoke.rs b/adbc/examples/ffi_smoke.rs new file mode 100644 index 00000000..28f520aa --- /dev/null +++ b/adbc/examples/ffi_smoke.rs @@ -0,0 +1,101 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use adbc_core::options::AdbcVersion; +use adbc_core::Driver as _; +use adbc_driver_manager::ManagedDriver; +use std::path::PathBuf; + +const ENTRYPOINTS: [&[u8]; 2] = [b"AdbcDatabricksInit", b"AdbcDriverInit"]; + +fn main() -> Result<(), Box> { + let library = std::env::args_os() + .nth(1) + .map(PathBuf::from) + .ok_or("usage: ffi_smoke ")?; + + if !library.is_absolute() { + return Err("driver library path must be absolute".into()); + } + + let mut evidence = String::new(); + for entrypoint in ENTRYPOINTS { + let entrypoint_name = std::str::from_utf8(entrypoint)?; + let mut ffi_driver = adbc_ffi::FFI_AdbcDriver::default(); + let mut ffi_error = adbc_ffi::FFI_AdbcError::default(); + let status = match entrypoint_name { + "AdbcDatabricksInit" => unsafe { + databricks_adbc::AdbcDatabricksInit( + AdbcVersion::V110.into(), + std::ptr::from_mut(&mut ffi_driver).cast(), + &mut ffi_error, + ) + }, + "AdbcDriverInit" => unsafe { + databricks_adbc::AdbcDriverInit( + AdbcVersion::V110.into(), + std::ptr::from_mut(&mut ffi_driver).cast(), + &mut ffi_error, + ) + }, + _ => unreachable!("fixed entrypoint list"), + }; + if status != adbc_core::constants::ADBC_STATUS_OK { + return Err(format!("{entrypoint_name} initialization returned {status}").into()); + } + if ffi_driver.ConnectionCancel.is_some() || ffi_driver.StatementCancel.is_some() { + return Err(format!("{entrypoint_name} unsafely advertised cancellation").into()); + } + + let connection_cancel = adbc_ffi::driver_method!(ffi_driver, ConnectionCancel); + let mut uninitialized_connection = adbc_ffi::FFI_AdbcConnection::default(); + let cancel_status = + unsafe { connection_cancel(&mut uninitialized_connection, &mut ffi_error) }; + if cancel_status != adbc_core::constants::ADBC_STATUS_NOT_IMPLEMENTED { + return Err(format!( + "{entrypoint_name} ConnectionCancel fallback returned {cancel_status}" + ) + .into()); + } + + let statement_cancel = adbc_ffi::driver_method!(ffi_driver, StatementCancel); + let mut uninitialized_statement = adbc_ffi::FFI_AdbcStatement::default(); + let cancel_status = + unsafe { statement_cancel(&mut uninitialized_statement, &mut ffi_error) }; + if cancel_status != adbc_core::constants::ADBC_STATUS_NOT_IMPLEMENTED { + return Err(format!( + "{entrypoint_name} StatementCancel fallback returned {cancel_status}" + ) + .into()); + } + + for (version, version_name) in [(AdbcVersion::V100, "1.0"), (AdbcVersion::V110, "1.1")] { + let mut driver = + ManagedDriver::load_dynamic_from_filename(&library, Some(entrypoint), version)?; + let _database = driver.new_database()?; + let result = format!( + "{{\"entrypoint\":\"{entrypoint_name}\",\"adbc_version\":\"{version_name}\",\"driver_manager_version\":\"0.24.0\",\"database_allocated\":true}}" + ); + println!("{result}"); + evidence.push_str(&result); + evidence.push('\n'); + } + } + + if let Some(output) = std::env::args_os().nth(2) { + std::fs::write(output, evidence)?; + } + + Ok(()) +} diff --git a/adbc/examples/high_concurrency_benchmark.rs b/adbc/examples/high_concurrency_benchmark.rs new file mode 100644 index 00000000..d7696240 --- /dev/null +++ b/adbc/examples/high_concurrency_benchmark.rs @@ -0,0 +1,475 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Paired high-concurrency benchmark for the Rust ADBC and direct-kernel paths. + +use std::env; +use std::fs::{self, File}; +use std::io::BufWriter; +use std::path::PathBuf; +use std::process::Command; +use std::sync::{Arc, Barrier}; +use std::thread; +use std::time::{Instant, SystemTime, UNIX_EPOCH}; + +use adbc_core::options::{OptionDatabase, OptionValue}; +use adbc_core::{Connection as _, Database as _, Driver as _, Statement as _}; +use databricks_adbc::{Connection, Driver}; +use databricks_sql_kernel::{AuthConfig, ResultBatch, Session}; +use serde_json::{json, Value}; + +const DEFAULT_CONCURRENCY: usize = 16; +const DEFAULT_SIZE_MIB: f64 = 5.0; +const DEFAULT_WARMUPS: usize = 2; +const DEFAULT_SAMPLES: usize = 10; +const PAYLOAD_BYTES: u64 = 1024; +const LOGICAL_BYTES_PER_ROW: u64 = PAYLOAD_BYTES + 8; + +fn kernel_revision() -> String { + let Ok(output) = Command::new("git") + .args(["rev-parse", "HEAD"]) + .current_dir(env!("CARGO_MANIFEST_DIR")) + .output() + else { + return "unavailable".into(); + }; + if !output.status.success() { + return "unavailable".into(); + } + String::from_utf8_lossy(&output.stdout).trim().to_owned() +} + +#[derive(Clone)] +struct LiveConfig { + host: String, + http_path: String, + token: String, +} + +#[derive(Clone, Copy, Debug)] +struct Observation { + latency_ms: f64, + rows: usize, + arrow_bytes: usize, + batches: usize, +} + +struct KernelClient { + runtime: tokio::runtime::Runtime, + session: Session, +} + +impl KernelClient { + fn open(config: &LiveConfig) -> Result> { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()?; + let session = runtime.block_on( + Session::builder() + .http_path(&config.host, &config.http_path) + .auth(AuthConfig::Pat { + token: config.token.clone(), + identity_federation_client_id: None, + }) + .open(), + )?; + Ok(Self { runtime, session }) + } + + fn observe(&self, sql: &str) -> Result { + let mut statement = self.session.statement(); + statement.spec().sql(sql); + let started = Instant::now(); + let mut executed = self + .runtime + .block_on(statement.execute()) + .map_err(|error| error.to_string())?; + let (mut rows, mut arrow_bytes, mut batches) = (0, 0, 0); + while let Some(batch) = self + .runtime + .block_on(executed.next_batch()) + .map_err(|error| error.to_string())? + { + match batch { + ResultBatch::Arrow(batch) => { + rows += batch.num_rows(); + arrow_bytes += batch.get_array_memory_size(); + batches += 1; + } + _ => return Err("kernel returned a non-Arrow result batch".into()), + } + } + Ok(Observation { + latency_ms: started.elapsed().as_secs_f64() * 1000.0, + rows, + arrow_bytes, + batches, + }) + } +} + +fn required_env(name: &str) -> Result> { + env::var(name).map_err(|_| format!("{name} must be set").into()) +} + +fn parse_positive_usize(name: &str, default: usize) -> Result> { + let value = env::var(name) + .unwrap_or_else(|_| default.to_string()) + .parse::()?; + if value == 0 { + return Err(format!("{name} must be positive").into()); + } + Ok(value) +} + +fn parse_positive_f64(name: &str, default: f64) -> Result> { + let value = env::var(name) + .unwrap_or_else(|_| default.to_string()) + .parse::()?; + if !value.is_finite() || value <= 0.0 { + return Err(format!("{name} must be positive and finite").into()); + } + Ok(value) +} + +fn query(size_mib: f64) -> String { + let target_bytes = (size_mib * 1024.0 * 1024.0).ceil() as u64; + let rows = target_bytes.div_ceil(LOGICAL_BYTES_PER_ROW); + format!("SELECT id, repeat('x', {PAYLOAD_BYTES}) AS payload FROM range({rows})") +} + +fn open_adbc(config: &LiveConfig) -> Result> { + let mut driver = Driver; + let database = driver.new_database_with_opts([ + ( + OptionDatabase::Uri, + OptionValue::String(config.host.clone()), + ), + ( + OptionDatabase::Other("adbc.databricks.http_path".into()), + OptionValue::String(config.http_path.clone()), + ), + ( + OptionDatabase::Other("adbc.databricks.auth.type".into()), + OptionValue::String("pat".into()), + ), + ( + OptionDatabase::Other("adbc.databricks.auth.token".into()), + OptionValue::String(config.token.clone()), + ), + ])?; + Ok(database.new_connection()?) +} + +fn observe_adbc(connection: &mut Connection, sql: &str) -> Result { + let mut statement = connection + .new_statement() + .map_err(|error| error.to_string())?; + statement + .set_sql_query(sql) + .map_err(|error| error.to_string())?; + let started = Instant::now(); + let reader = statement.execute().map_err(|error| error.to_string())?; + let (mut rows, mut arrow_bytes, mut batches) = (0, 0, 0); + for batch in reader { + let batch = batch.map_err(|error| error.to_string())?; + rows += batch.num_rows(); + arrow_bytes += batch.get_array_memory_size(); + batches += 1; + } + Ok(Observation { + latency_ms: started.elapsed().as_secs_f64() * 1000.0, + rows, + arrow_bytes, + batches, + }) +} + +fn run_adbc_wave(clients: &mut [Connection], sql: &str) -> Result<(f64, Vec), String> { + let barrier = Arc::new(Barrier::new(clients.len() + 1)); + let started = Instant::now(); + let observations = thread::scope(|scope| { + let mut handles = Vec::with_capacity(clients.len()); + for client in clients { + let barrier = Arc::clone(&barrier); + handles.push(scope.spawn(move || { + barrier.wait(); + observe_adbc(client, sql) + })); + } + barrier.wait(); + handles + .into_iter() + .map(|handle| { + handle + .join() + .map_err(|_| "ADBC worker panicked".to_string())? + }) + .collect::, _>>() + })?; + Ok((started.elapsed().as_secs_f64() * 1000.0, observations)) +} + +fn run_kernel_wave(clients: &[KernelClient], sql: &str) -> Result<(f64, Vec), String> { + let barrier = Arc::new(Barrier::new(clients.len() + 1)); + let started = Instant::now(); + let observations = thread::scope(|scope| { + let mut handles = Vec::with_capacity(clients.len()); + for client in clients { + let barrier = Arc::clone(&barrier); + handles.push(scope.spawn(move || { + barrier.wait(); + client.observe(sql) + })); + } + barrier.wait(); + handles + .into_iter() + .map(|handle| { + handle + .join() + .map_err(|_| "kernel worker panicked".to_string())? + }) + .collect::, _>>() + })?; + Ok((started.elapsed().as_secs_f64() * 1000.0, observations)) +} + +fn percentile(sorted: &[f64], fraction: f64) -> f64 { + let rank = fraction * (sorted.len() - 1) as f64; + let (lower, upper) = (rank.floor() as usize, rank.ceil() as usize); + sorted[lower] + (sorted[upper] - sorted[lower]) * (rank - lower as f64) +} + +fn validate_shapes(observations: &[Observation]) -> Result<(usize, usize, usize), String> { + let first = observations + .first() + .ok_or_else(|| "wave did not produce observations".to_string())?; + let shape = (first.rows, first.arrow_bytes, first.batches); + if observations + .iter() + .any(|value| (value.rows, value.arrow_bytes, value.batches) != shape) + { + return Err("result shape differed within a concurrent wave".into()); + } + Ok(shape) +} + +fn load_live_config() -> Result> { + let token = fs::read_to_string(required_env("DATABRICKS_TOKEN_FILE")?)? + .trim() + .to_owned(); + if token.is_empty() { + return Err("DATABRICKS_TOKEN_FILE is empty".into()); + } + Ok(LiveConfig { + host: required_env("DATABRICKS_HOST")?, + http_path: required_env("DATABRICKS_HTTP_PATH")?, + token, + }) +} + +fn dry_run(concurrency: usize, size_mib: f64, warmups: usize, samples: usize) -> Value { + json!({ + "mode": "dry-run", + "concurrency": concurrency, + "size_mib": size_mib, + "warmups_per_implementation": warmups, + "samples_per_implementation": samples, + "sql": query(size_mib), + "timed_region": "barrier release through complete Arrow fetch by every concurrent client", + "connections": "one persistent connection/session per concurrent client and implementation", + "ordering": "ADBC/kernel order alternates by repetition", + }) +} + +fn main() -> Result<(), Box> { + let concurrency = parse_positive_usize("DATABRICKS_BENCH_CONCURRENCY", DEFAULT_CONCURRENCY)?; + let size_mib = parse_positive_f64("DATABRICKS_BENCH_SIZE_MIB", DEFAULT_SIZE_MIB)?; + let warmups = parse_positive_usize("DATABRICKS_BENCH_WARMUPS", DEFAULT_WARMUPS)?; + let samples = parse_positive_usize("DATABRICKS_BENCH_SAMPLES", DEFAULT_SAMPLES)?; + if env::args().any(|argument| argument == "--dry-run") { + println!( + "{}", + serde_json::to_string_pretty(&dry_run(concurrency, size_mib, warmups, samples))? + ); + return Ok(()); + } + + let config = load_live_config()?; + let output = PathBuf::from(required_env("DATABRICKS_BENCH_OUTPUT")?); + let sql = query(size_mib); + let started_at_unix_ms = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis(); + let mut adbc_clients = (0..concurrency) + .map(|_| open_adbc(&config)) + .collect::, _>>()?; + let kernel_clients = (0..concurrency) + .map(|_| KernelClient::open(&config)) + .collect::, _>>()?; + + let mut observations = Vec::new(); + for repetition in 0..(warmups + samples) { + let phase = if repetition < warmups { + "warmup" + } else { + "sample" + }; + let sample = repetition.saturating_sub(warmups) + 1; + let adbc_first = repetition.is_multiple_of(2); + for implementation in if adbc_first { + ["rust-adbc", "rust-kernel-direct"] + } else { + ["rust-kernel-direct", "rust-adbc"] + } { + let (wall_latency_ms, values) = if implementation == "rust-adbc" { + run_adbc_wave(&mut adbc_clients, &sql)? + } else { + run_kernel_wave(&kernel_clients, &sql)? + }; + let shape = validate_shapes(&values)?; + observations.push(json!({ + "phase": phase, + "repetition": if phase == "warmup" { repetition + 1 } else { sample }, + "implementation": implementation, + "wall_latency_ms": wall_latency_ms, + "query_latency_ms": values.iter().map(|value| value.latency_ms).collect::>(), + "rows_per_query": shape.0, + "arrow_bytes_per_query": shape.1, + "batches_per_query": shape.2, + })); + } + } + + let mut summaries = Vec::new(); + for implementation in ["rust-adbc", "rust-kernel-direct"] { + let mut latencies = observations + .iter() + .filter(|value| value["phase"] == "sample" && value["implementation"] == implementation) + .map(|value| { + value["wall_latency_ms"] + .as_f64() + .expect("latency is numeric") + }) + .collect::>(); + latencies.sort_by(f64::total_cmp); + summaries.push(json!({ + "implementation": implementation, + "p50_wall_latency_ms": percentile(&latencies, 0.50), + "p95_wall_latency_ms": percentile(&latencies, 0.95), + "throughput_queries_per_second_at_p50": concurrency as f64 * 1000.0 / percentile(&latencies, 0.50), + })); + } + let shapes = observations + .iter() + .map(|value| { + ( + value["rows_per_query"].as_u64(), + value["arrow_bytes_per_query"].as_u64(), + value["batches_per_query"].as_u64(), + ) + }) + .collect::>(); + if shapes.iter().any(|shape| shape != &shapes[0]) { + return Err("result shape differed between ADBC and direct-kernel waves".into()); + } + + let mut paired_samples = Vec::with_capacity(samples); + let (mut overheads, mut ratios) = (Vec::with_capacity(samples), Vec::with_capacity(samples)); + for repetition in 1..=samples { + let wall_latency = |implementation: &str| { + observations + .iter() + .find(|value| { + value["phase"] == "sample" + && value["repetition"] == repetition + && value["implementation"] == implementation + }) + .and_then(|value| value["wall_latency_ms"].as_f64()) + .expect("every measured repetition has both implementations") + }; + let adbc_latency_ms = wall_latency("rust-adbc"); + let kernel_latency_ms = wall_latency("rust-kernel-direct"); + let overhead_ms = adbc_latency_ms - kernel_latency_ms; + let ratio = adbc_latency_ms / kernel_latency_ms; + overheads.push(overhead_ms); + ratios.push(ratio); + paired_samples.push(json!({ + "repetition": repetition, + "first": if (repetition + warmups - 1).is_multiple_of(2) { "rust-adbc" } else { "rust-kernel-direct" }, + "adbc_wall_latency_ms": adbc_latency_ms, + "kernel_wall_latency_ms": kernel_latency_ms, + "overhead_ms": overhead_ms, + "ratio": ratio, + })); + } + overheads.sort_by(f64::total_cmp); + ratios.sort_by(f64::total_cmp); + let report = json!({ + "schema_version": 1, + "metadata": { + "started_at_unix_ms": started_at_unix_ms, + "completed_at_unix_ms": SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis(), + "host": config.host, + "http_path": config.http_path, + "credentials": "token read from DATABRICKS_TOKEN_FILE; value not retained", + "driver_version": env!("CARGO_PKG_VERSION"), + "kernel_revision": kernel_revision(), + "build_profile": if cfg!(debug_assertions) { "debug" } else { "release" }, + "concurrency": concurrency, + "size_mib": size_mib, + "warmups_per_implementation": warmups, + "samples_per_implementation": samples, + "timed_region": "barrier release through complete Arrow fetch by every concurrent client", + "connections": "one persistent connection/session per concurrent client and implementation", + "ordering": "ADBC/kernel order alternates by repetition", + }, + "query": sql, + "summaries": summaries, + "paired_summary": { + "p50_wall_overhead_ms": percentile(&overheads, 0.50), + "p95_wall_overhead_ms": percentile(&overheads, 0.95), + "p50_wall_ratio": percentile(&ratios, 0.50), + "p95_wall_ratio": percentile(&ratios, 0.95), + }, + "paired_samples": paired_samples, + "observations": observations, + }); + serde_json::to_writer_pretty(BufWriter::new(File::create(output)?), &report)?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn deterministic_query_uses_requested_logical_size() { + assert_eq!( + query(0.25), + "SELECT id, repeat('x', 1024) AS payload FROM range(255)" + ); + } + + #[test] + fn dry_run_records_concurrency_contract() { + let plan = dry_run(16, 5.0, 2, 10); + assert_eq!(plan["concurrency"], 16); + assert_eq!(plan["warmups_per_implementation"], 2); + assert_eq!(plan["samples_per_implementation"], 10); + assert_eq!( + plan["ordering"], + "ADBC/kernel order alternates by repetition" + ); + } +} diff --git a/adbc/src/cancellation.rs b/adbc/src/cancellation.rs new file mode 100644 index 00000000..e364c0fb --- /dev/null +++ b/adbc/src/cancellation.rs @@ -0,0 +1,281 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; + +use adbc_core::error::{Result, Status}; + +use crate::error::adbc_error; + +type Cancel = Arc Result<()> + Send + Sync>; +type IsActive = Arc bool + Send + Sync>; + +#[derive(Clone)] +struct Entry { + cancel: Cancel, + is_active: IsActive, + cancelled: Arc, +} + +#[derive(Default)] +pub(crate) struct CancellationRegistry { + next_id: AtomicU64, + active: Mutex>, +} + +impl CancellationRegistry { + pub(crate) fn register(self: &Arc, cancel: Cancel) -> Result { + self.register_while(cancel, Arc::new(|| true)) + } + + pub(crate) fn register_while( + self: &Arc, + cancel: Cancel, + is_active: IsActive, + ) -> Result { + self.register_while_with_signal(cancel, is_active, Arc::new(AtomicBool::new(false))) + } + + pub(crate) fn register_while_with_signal( + self: &Arc, + cancel: Cancel, + is_active: IsActive, + cancelled: Arc, + ) -> Result { + let id = self.next_id.fetch_add(1, Ordering::Relaxed); + self.active + .lock() + .map_err(|_| adbc_error("connection cancellation lock is poisoned", Status::Internal))? + .insert( + id, + Entry { + cancel, + is_active, + cancelled: Arc::clone(&cancelled), + }, + ); + Ok(OperationGuard { + registry: Arc::clone(self), + id, + cancelled, + }) + } + + pub(crate) fn cancel(&self) -> Result<()> { + let active = self + .active + .lock() + .map_err(|_| adbc_error("connection cancellation lock is poisoned", Status::Internal))? + .values() + .cloned() + .collect::>(); + let mut found_active = false; + let mut first_error = None; + for entry in active { + // User-provided activity and cancellation callbacks must run after + // releasing the registry lock because they may re-enter it. + if !(entry.is_active)() { + continue; + } + found_active = true; + match (entry.cancel)() { + Ok(()) => entry.cancelled.store(true, Ordering::Release), + Err(error) if first_error.is_none() => { + first_error = Some(adbc_error( + format!("connection could not cancel an active operation: {error}"), + Status::Unknown, + )); + } + Err(_) => {} + } + } + if !found_active { + return Err(adbc_error( + "connection has no active operation to cancel", + Status::InvalidState, + )); + } + first_error.map_or(Ok(()), Err) + } + + fn remove(&self, id: u64) { + self.active + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .remove(&id); + } +} + +pub(crate) struct OperationGuard { + registry: Arc, + id: u64, + cancelled: Arc, +} + +impl OperationGuard { + pub(crate) fn is_cancelled(&self) -> bool { + self.cancelled.load(Ordering::Acquire) + } +} + +impl Drop for OperationGuard { + fn drop(&mut self) { + self.registry.remove(self.id); + } +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::AtomicUsize; + + use super::*; + + #[test] + fn idle_connection_returns_invalid_state() { + let registry = CancellationRegistry::default(); + assert_eq!(registry.cancel().unwrap_err().status, Status::InvalidState); + } + + #[test] + fn cancel_dispatches_every_active_operation_without_holding_registry_lock() { + let registry = Arc::new(CancellationRegistry::default()); + let calls = Arc::new(AtomicUsize::new(0)); + let guards = (0..2) + .map(|_| { + let calls = Arc::clone(&calls); + let registry = Arc::clone(®istry); + Arc::clone(®istry) + .register(Arc::new(move || { + calls.fetch_add(1, Ordering::Relaxed); + let reentrant = registry.register(Arc::new(|| Ok(())))?; + drop(reentrant); + Ok(()) + })) + .unwrap() + }) + .collect::>(); + + registry.cancel().unwrap(); + + assert_eq!(calls.load(Ordering::Relaxed), 2); + drop(guards); + assert_eq!(registry.cancel().unwrap_err().status, Status::InvalidState); + } + + #[test] + fn activity_checks_run_without_holding_registry_lock() { + let registry = Arc::new(CancellationRegistry::default()); + let activity_registry = Arc::clone(®istry); + let _guard = registry + .register_while( + Arc::new(|| Ok(())), + Arc::new(move || { + let reentrant = activity_registry.register(Arc::new(|| Ok(()))).unwrap(); + drop(reentrant); + true + }), + ) + .unwrap(); + + registry.cancel().unwrap(); + } + + #[test] + fn guard_removes_entry_from_poisoned_registry() { + let registry = Arc::new(CancellationRegistry::default()); + let guard = registry.register(Arc::new(|| Ok(()))).unwrap(); + let poisoning_registry = Arc::clone(®istry); + let _ = std::panic::catch_unwind(move || { + let _lock = poisoning_registry.active.lock().unwrap(); + panic!("poison registry for test"); + }); + + drop(guard); + + assert!(registry + .active + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .is_empty()); + } + + #[test] + fn one_failure_does_not_prevent_other_operations_from_being_cancelled() { + let registry = Arc::new(CancellationRegistry::default()); + let calls = Arc::new(AtomicUsize::new(0)); + let _failing = registry + .register(Arc::new(|| Err(adbc_error("cancel failed", Status::IO)))) + .unwrap(); + let callback_calls = Arc::clone(&calls); + let _successful = registry + .register(Arc::new(move || { + callback_calls.fetch_add(1, Ordering::Relaxed); + Ok(()) + })) + .unwrap(); + + assert_eq!(registry.cancel().unwrap_err().status, Status::Unknown); + assert_eq!(calls.load(Ordering::Relaxed), 1); + } + + #[test] + fn completed_operation_is_no_longer_cancelled() { + let registry = Arc::new(CancellationRegistry::default()); + let calls = Arc::new(AtomicUsize::new(0)); + let callback_calls = Arc::clone(&calls); + let guard = registry + .register(Arc::new(move || { + callback_calls.fetch_add(1, Ordering::Relaxed); + Ok(()) + })) + .unwrap(); + drop(guard); + + assert_eq!(registry.cancel().unwrap_err().status, Status::InvalidState); + assert_eq!(calls.load(Ordering::Relaxed), 0); + } + + #[test] + fn successful_dispatch_marks_operation_cancelled() { + let registry = Arc::new(CancellationRegistry::default()); + let guard = registry.register(Arc::new(|| Ok(()))).unwrap(); + + assert!(!guard.is_cancelled()); + registry.cancel().unwrap(); + assert!(guard.is_cancelled()); + } + + #[test] + fn failed_dispatch_does_not_mark_operation_cancelled() { + let registry = Arc::new(CancellationRegistry::default()); + let guard = registry + .register(Arc::new(|| Err(adbc_error("cancel failed", Status::IO)))) + .unwrap(); + + assert!(registry.cancel().is_err()); + assert!(!guard.is_cancelled()); + } + + #[test] + fn inactive_registration_is_equivalent_to_idle() { + let registry = Arc::new(CancellationRegistry::default()); + let _guard = registry + .register_while(Arc::new(|| Ok(())), Arc::new(|| false)) + .unwrap(); + + assert_eq!(registry.cancel().unwrap_err().status, Status::InvalidState); + } +} diff --git a/adbc/src/config.rs b/adbc/src/config.rs new file mode 100644 index 00000000..123916e1 --- /dev/null +++ b/adbc/src/config.rs @@ -0,0 +1,1771 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::collections::HashMap; +use std::path::PathBuf; +use std::time::Duration; + +use adbc_core::error::{Result, Status}; +use adbc_core::options::OptionValue; +use databricks_sql_kernel as kernel; + +use crate::error::{adbc_error, map_kernel_error, unsupported}; + +pub(crate) const HOST: &str = "adbc.databricks.host"; +pub(crate) const HTTP_PATH: &str = "adbc.databricks.http_path"; +pub(crate) const WAREHOUSE_ID: &str = "adbc.databricks.warehouse_id"; +pub(crate) const ACCESS_TOKEN: &str = "adbc.databricks.auth.token"; +pub(crate) const CATALOG: &str = "adbc.databricks.catalog"; +pub(crate) const SCHEMA: &str = "adbc.databricks.schema"; +const AUTH_TYPE: &str = "adbc.databricks.auth.type"; +const GRANT_TYPE: &str = "adbc.databricks.oauth.grant_type"; +const IDENTITY_FEDERATION_CLIENT_ID: &str = "adbc.databricks.identity_federation_client_id"; +const OAUTH_CLIENT_ID: &str = "adbc.databricks.oauth.client_id"; +const OAUTH_CLIENT_SECRET: &str = "adbc.databricks.oauth.client_secret"; +const OAUTH_SCOPES: &str = "adbc.databricks.oauth.scopes"; +const OAUTH_SCOPE: &str = "adbc.databricks.oauth.scope"; +const OAUTH_TOKEN_URL: &str = "adbc.databricks.oauth.token_url"; +const OAUTH_REDIRECT_PORTS: &str = "adbc.databricks.oauth.redirect_ports"; +const OAUTH_CALLBACK_TIMEOUT_MS: &str = "adbc.databricks.oauth.callback_timeout_ms"; +const TOKEN_CACHE_ENABLED: &str = "adbc.databricks.oauth.token_cache.enabled"; +const TOKEN_CACHE_PASSPHRASE: &str = "adbc.databricks.oauth.token_cache.passphrase"; +const JWT_KEY_FILE: &str = "adbc.databricks.oauth.jwt.key_file"; +const JWT_KID: &str = "adbc.databricks.oauth.jwt.kid"; +const JWT_PASSPHRASE: &str = "adbc.databricks.oauth.jwt.passphrase"; +const JWT_ALGORITHM: &str = "adbc.databricks.oauth.jwt.algorithm"; +const AZURE_CLIENT_ID: &str = "adbc.databricks.azure.client_id"; +const AZURE_CLIENT_SECRET: &str = "adbc.databricks.azure.client_secret"; +const AZURE_TENANT_ID: &str = "adbc.databricks.azure.tenant_id"; +const AZURE_WORKSPACE_RESOURCE_ID: &str = "adbc.databricks.azure.workspace_resource_id"; +const HTTP_PREFIX: &str = "adbc.databricks.http."; +const PROXY_PREFIX: &str = "adbc.databricks.proxy."; +const TLS_PREFIX: &str = "adbc.databricks.tls."; +const TELEMETRY_PREFIX: &str = "adbc.databricks.telemetry."; +const LOG_PREFIX: &str = "adbc.databricks.log."; +const SESSION_CONF_PREFIX: &str = "adbc.databricks.session_conf."; +const SERVER_SIDE_PROPERTY_PREFIX: &str = "adbc.databricks.ssp_"; +const QUERY_TAGS: &str = "adbc.databricks.query_tags"; +const ENABLE_COMPLEX_DATATYPE_SUPPORT: &str = "adbc.databricks.enable_complex_datatype_support"; +const GEOSPATIAL_REPRESENTATION: &str = "adbc.databricks.geospatial.result_representation"; +const ENABLE_GEOSPATIAL: &str = "adbc.databricks.enable_geospatial_support"; +const CLOUDFETCH_MAX_CHUNKS_IN_MEMORY: &str = "adbc.databricks.cloudfetch.max_chunks_in_memory"; +const CLOUDFETCH_ENABLED: &str = "adbc.databricks.cloudfetch.enabled"; +const PROTOCOL: &str = "adbc.databricks.protocol"; +pub(crate) const ESCAPE_CATALOG_NAME: &str = "adbc.databricks.metadata.escape_catalog_name"; + +#[derive(Clone, Default)] +pub(crate) struct SecretString(String); + +impl SecretString { + fn new(value: String) -> Self { + Self(value) + } + fn expose(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Debug for SecretString { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("") + } +} + +#[derive(Clone, Default)] +struct SecretBytes(Vec); + +impl SecretBytes { + fn new(value: Vec) -> Self { + Self(value) + } + fn expose(&self) -> &[u8] { + &self.0 + } +} + +impl std::fmt::Debug for SecretBytes { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("") + } +} + +#[derive(Clone)] +struct Preferred { + canonical: Option, + alias: Option, +} + +impl Default for Preferred { + fn default() -> Self { + Self { + canonical: None, + alias: None, + } + } +} + +impl Preferred { + fn set(&mut self, value: T, canonical: bool) { + if canonical { + self.canonical = Some(value); + } else { + self.alias = Some(value); + } + } + fn get(&self) -> Option<&T> { + self.canonical.as_ref().or(self.alias.as_ref()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum AuthMode { + Pat, + OAuthM2M, + OAuthU2M, + OAuthM2MPrivateKey, + AzureServicePrincipal, + OAuthFederation, +} + +#[derive(Clone, Default)] +pub(crate) struct DatabaseConfig { + uri: Option, + host: Preferred, + http_path: Preferred, + warehouse_id: Option, + catalog: Preferred, + schema: Preferred, + auth_mode: Preferred, + username: Option, + password: Option, + token: Preferred, + oauth_client_id: Option, + oauth_client_secret: Option, + oauth_scopes: Preferred>, + oauth_token_url: Option, + oauth_redirect_ports: Option>, + oauth_callback_timeout: Option, + token_cache_enabled: Option, + token_cache_passphrase: Option, + identity_federation_client_id: Option, + jwt_key_file: Option, + jwt_kid: Option, + jwt_passphrase: Option, + jwt_algorithm: Option, + azure_client_id: Option, + azure_client_secret: Option, + azure_tenant_id: Option, + azure_workspace_resource_id: Option, + http: kernel::HttpConfig, + proxy: kernel::ProxyConfig, + tls_ca_file: Option, + tls_ca_pem: Option>, + tls_accept_self_signed: bool, + tls_skip_hostname_verification: bool, + tls_client_cert_file: Option, + tls_client_cert_pem: Option>, + tls_client_key_file: Option, + tls_client_key_pem: Option, + logging: kernel::LoggingConfig, + telemetry: kernel::TelemetryConfig, + result: kernel::ResultConfig, + session_conf: HashMap, + query_tags: Option, + escape_catalog_name: Option, + geospatial: Preferred, +} + +impl std::fmt::Debug for DatabaseConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("DatabaseConfig") + .field("uri", &self.uri.as_ref().map(|_| "")) + .field("host", &self.host.get()) + .field("http_path", &self.http_path.get()) + .field("warehouse_id", &self.warehouse_id) + .field("catalog", &self.catalog.get()) + .field("schema", &self.schema.get()) + .field("auth_mode", &self.auth_mode.get()) + .field("token", &self.token.get()) + .field("oauth_client_secret", &self.oauth_client_secret) + .field("token_cache_passphrase", &self.token_cache_passphrase) + .field("jwt_passphrase", &self.jwt_passphrase) + .field("azure_client_secret", &self.azure_client_secret) + .field( + "sea_response_compression_enabled", + &self.http.sea_response_compression_enabled, + ) + .field("http_request_timeout", &self.http.request_timeout) + .field("http_overall_timeout", &self.http.overall_timeout) + .field( + "http_pool_max_idle_per_host", + &self.http.pool_max_idle_per_host, + ) + .field("http_retry_min_wait", &self.http.retry_min_wait) + .field("http_retry_max_wait", &self.http.retry_max_wait) + .field("http_retry_max_retries", &self.http.retry_max_retries) + .field("proxy", &self.proxy) + .field("tls_client_key_pem", &self.tls_client_key_pem) + .field("session_conf_count", &self.session_conf.len()) + .field("custom_header_count", &self.http.custom_headers.len()) + .finish_non_exhaustive() + } +} + +pub(crate) struct ResolvedConfig { + pub(crate) host: String, + pub(crate) http_path: Option, + pub(crate) warehouse_id: Option, + pub(crate) catalog: Option, + pub(crate) schema: Option, + pub(crate) auth: kernel::AuthConfig, + pub(crate) http: kernel::HttpConfig, + pub(crate) proxy: Option, + pub(crate) tls: kernel::TlsConfig, + pub(crate) logging: kernel::LoggingConfig, + pub(crate) telemetry: kernel::TelemetryConfig, + pub(crate) result: kernel::ResultConfig, + pub(crate) session_conf: HashMap, + pub(crate) escape_catalog_name: bool, + pub(crate) geospatial: kernel::GeospatialResultRepresentation, +} + +impl DatabaseConfig { + pub(crate) fn set_option(&mut self, key: &str, value: OptionValue) -> Result<()> { + if let Some(name) = key.strip_prefix(SESSION_CONF_PREFIX) { + if name.is_empty() { + return Err(adbc_error( + "session-conf name must not be empty", + Status::InvalidArguments, + )); + } + self.session_conf + .insert(name.to_string(), string_value(value, key)?); + return Ok(()); + } + if let Some(name) = strip_prefix_ignore_ascii_case(key, SERVER_SIDE_PROPERTY_PREFIX) { + validate_server_side_property_name(name)?; + self.session_conf + .insert(name.to_string(), string_value(value, key)?); + return Ok(()); + } + match key { + adbc_core::constants::ADBC_OPTION_URI => self.uri = Some(string_value(value, key)?), + HOST => self.host.set(string_value(value, key)?, true), + "databricks.host" => self.host.set(string_value(value, key)?, false), + HTTP_PATH => self.http_path.set(string_value(value, key)?, true), + "databricks.http_path" | "http_path" | "HTTPPath" => { + self.http_path.set(string_value(value, key)?, false) + } + WAREHOUSE_ID | "databricks.warehouse_id" => { + self.warehouse_id = Some(string_value(value, key)?) + } + adbc_core::constants::ADBC_OPTION_USERNAME => { + self.username = Some(string_value(value, key)?) + } + adbc_core::constants::ADBC_OPTION_PASSWORD => { + self.password = Some(SecretString::new(string_value(value, key)?)) + } + ACCESS_TOKEN => self + .token + .set(SecretString::new(string_value(value, key)?), true), + "databricks.access_token" | "access_token" | "token" | "Auth_AccessToken" => self + .token + .set(SecretString::new(string_value(value, key)?), false), + CATALOG => self.catalog.set(string_value(value, key)?, false), + SCHEMA => self.schema.set(string_value(value, key)?, false), + "adbc.connection.catalog" => self.catalog.set(string_value(value, key)?, true), + "adbc.connection.db_schema" => self.schema.set(string_value(value, key)?, true), + AUTH_TYPE => self + .auth_mode + .set(parse_auth_mode(&string_value(value, key)?)?, true), + GRANT_TYPE => self + .auth_mode + .set(parse_grant_type(&string_value(value, key)?)?, false), + OAUTH_CLIENT_ID => self.oauth_client_id = Some(string_value(value, key)?), + OAUTH_CLIENT_SECRET => { + self.oauth_client_secret = Some(SecretString::new(string_value(value, key)?)) + } + OAUTH_SCOPES => self + .oauth_scopes + .set(parse_scopes(&string_value(value, key)?), true), + OAUTH_SCOPE => self + .oauth_scopes + .set(parse_scopes(&string_value(value, key)?), false), + OAUTH_TOKEN_URL => self.oauth_token_url = Some(string_value(value, key)?), + OAUTH_REDIRECT_PORTS => { + self.oauth_redirect_ports = Some(parse_ports(&string_value(value, key)?, key)?) + } + OAUTH_CALLBACK_TIMEOUT_MS => { + self.oauth_callback_timeout = Some(duration(value, key, false)?) + } + TOKEN_CACHE_ENABLED => self.token_cache_enabled = Some(boolean(value, key)?), + TOKEN_CACHE_PASSPHRASE => { + self.token_cache_passphrase = Some(SecretString::new(string_value(value, key)?)) + } + IDENTITY_FEDERATION_CLIENT_ID => { + self.identity_federation_client_id = Some(string_value(value, key)?) + } + JWT_KEY_FILE | "Auth_JWT_Key_File" => { + self.jwt_key_file = Some(string_value(value, key)?) + } + JWT_KID | "Auth_KID" => self.jwt_kid = Some(string_value(value, key)?), + JWT_PASSPHRASE | "Auth_JWT_Passphrase" => { + self.jwt_passphrase = Some(SecretString::new(string_value(value, key)?)) + } + JWT_ALGORITHM | "Auth_JWT_Algorithm" => { + self.jwt_algorithm = Some(string_value(value, key)?) + } + "UseJWTAssertion" => { + if boolean_compat(value, key)? { + self.auth_mode.set(AuthMode::OAuthM2MPrivateKey, false); + } + } + AZURE_CLIENT_ID => self.azure_client_id = Some(string_value(value, key)?), + AZURE_CLIENT_SECRET => { + self.azure_client_secret = Some(SecretString::new(string_value(value, key)?)) + } + AZURE_TENANT_ID => self.azure_tenant_id = Some(string_value(value, key)?), + AZURE_WORKSPACE_RESOURCE_ID => { + self.azure_workspace_resource_id = Some(string_value(value, key)?) + } + QUERY_TAGS => self.query_tags = Some(string_value(value, key)?), + ESCAPE_CATALOG_NAME => self.escape_catalog_name = Some(boolean_compat(value, key)?), + ENABLE_COMPLEX_DATATYPE_SUPPORT => { + self.result.complex_types_as_json = !boolean(value, key)? + } + GEOSPATIAL_REPRESENTATION => self + .geospatial + .set(parse_geospatial(&string_value(value, key)?)?, true), + ENABLE_GEOSPATIAL => self.geospatial.set( + if boolean(value, key)? { + kernel::GeospatialResultRepresentation::Binary + } else { + kernel::GeospatialResultRepresentation::String + }, + false, + ), + CLOUDFETCH_MAX_CHUNKS_IN_MEMORY | "databricks.cloudfetch.max_chunks_in_memory" => { + self.result.cloudfetch_max_chunks_in_memory = positive_usize_compat(value, key)? + } + CLOUDFETCH_ENABLED | "databricks.cloudfetch.enabled" => { + self.result.cloudfetch_enabled = boolean_compat(value, key)? + } + PROTOCOL => { + let protocol = string_value(value, key)?; + if !protocol.eq_ignore_ascii_case("rest") { + return Err(unsupported(&format!( + "database option {key:?} value {protocol:?}; only REST/SEA is supported" + ))); + } + } + "adbc.databricks.sea_response_compression_enabled" => { + self.http.sea_response_compression_enabled = boolean(value, key)? + } + "adbc.databricks.http_request_timeout" => { + self.http.request_timeout = duration_seconds(value, key)? + } + "SocketTimeout" => self.http.request_timeout = duration(value, key, false)?, + _ if key.starts_with(HTTP_PREFIX) => self.set_http(key, value)?, + _ if key.starts_with(PROXY_PREFIX) => self.set_proxy(key, value)?, + _ if key.starts_with(TLS_PREFIX) => self.set_tls(key, value)?, + _ if key.starts_with(TELEMETRY_PREFIX) => self.set_telemetry(key, value)?, + _ if key.starts_with(LOG_PREFIX) => self.set_logging(key, value)?, + _ => return Err(unsupported(&format!("database option {key:?}"))), + } + Ok(()) + } + + fn set_http(&mut self, key: &str, value: OptionValue) -> Result<()> { + match key { + "adbc.databricks.http.request_timeout_ms" => { + self.http.request_timeout = duration(value, key, false)? + } + "adbc.databricks.http.overall_timeout_ms" => { + self.http.overall_timeout = duration(value, key, false)? + } + "adbc.databricks.http.pool_max_idle_per_host" => { + self.http.pool_max_idle_per_host = positive_usize(value, key)? + } + "adbc.databricks.http.retry_min_wait_ms" => { + self.http.retry_min_wait = duration(value, key, true)? + } + "adbc.databricks.http.retry_max_wait_ms" => { + self.http.retry_max_wait = duration(value, key, true)? + } + "adbc.databricks.http.retry_max_retries" => { + self.http.retry_max_retries = nonnegative_u32(value, key)? + } + "adbc.databricks.http.headers" => { + self.http.custom_headers = parse_headers(&string_value(value, key)?)? + } + _ => return Err(unsupported(&format!("database option {key:?}"))), + } + Ok(()) + } + + fn set_proxy(&mut self, key: &str, value: OptionValue) -> Result<()> { + match key { + "adbc.databricks.proxy.url" => self.proxy.url = Some(string_value(value, key)?), + "adbc.databricks.proxy.username" => { + self.proxy.username = Some(string_value(value, key)?) + } + "adbc.databricks.proxy.password" => { + self.proxy.password = Some(string_value(value, key)?) + } + "adbc.databricks.proxy.bypass_hosts" => { + self.proxy.bypass_hosts = Some(string_value(value, key)?) + } + _ => return Err(unsupported(&format!("database option {key:?}"))), + } + Ok(()) + } + + fn set_tls(&mut self, key: &str, value: OptionValue) -> Result<()> { + match key { + "adbc.databricks.tls.ca_file" => self.tls_ca_file = Some(string_value(value, key)?), + "adbc.databricks.tls.ca_pem" => self.tls_ca_pem = Some(bytes_value(value, key)?), + "adbc.databricks.tls.accept_self_signed" => { + self.tls_accept_self_signed = boolean(value, key)? + } + "adbc.databricks.tls.skip_hostname_verification" => { + self.tls_skip_hostname_verification = boolean(value, key)? + } + "adbc.databricks.tls.client_cert_file" => { + self.tls_client_cert_file = Some(string_value(value, key)?) + } + "adbc.databricks.tls.client_cert_pem" => { + self.tls_client_cert_pem = Some(bytes_value(value, key)?) + } + "adbc.databricks.tls.client_key_file" => { + self.tls_client_key_file = Some(string_value(value, key)?) + } + "adbc.databricks.tls.client_key_pem" => { + self.tls_client_key_pem = Some(SecretBytes::new(bytes_value(value, key)?)) + } + _ => return Err(unsupported(&format!("database option {key:?}"))), + } + Ok(()) + } + + fn set_logging(&mut self, key: &str, value: OptionValue) -> Result<()> { + match key { + "adbc.databricks.log.filter" => self.logging.filter = Some(string_value(value, key)?), + "adbc.databricks.log.file" => { + self.logging.file = Some(PathBuf::from(string_value(value, key)?)) + } + _ => return Err(unsupported(&format!("database option {key:?}"))), + } + Ok(()) + } + + fn set_telemetry(&mut self, key: &str, value: OptionValue) -> Result<()> { + match key { + "adbc.databricks.telemetry.enabled" => { + self.telemetry.enabled = Some(boolean(value, key)?) + } + "adbc.databricks.telemetry.batch_size" => { + self.telemetry.batch_size = positive_usize_compat(value, key)? + } + "adbc.databricks.telemetry.flush_interval_ms" => { + self.telemetry.flush_interval = duration_compat(value, key, false)? + } + "adbc.databricks.telemetry.max_retries" => { + self.telemetry.max_retries = nonnegative_u32_compat(value, key)? + } + "adbc.databricks.telemetry.retry_delay_ms" => { + self.telemetry.retry_delay = duration_compat(value, key, true)? + } + "adbc.databricks.telemetry.close_flush_timeout_ms" => { + self.telemetry.close_flush_timeout = duration_compat(value, key, false)? + } + "adbc.databricks.telemetry.circuit_breaker_enabled" => { + self.telemetry.circuit_breaker_enabled = boolean(value, key)? + } + "adbc.databricks.telemetry.circuit_breaker_threshold" => { + self.telemetry.circuit_breaker_threshold = nonnegative_u32_compat(value, key)? + } + "adbc.databricks.telemetry.circuit_breaker_timeout_ms" => { + self.telemetry.circuit_breaker_timeout = duration_compat(value, key, false)? + } + _ => return Err(unsupported(&format!("database option {key:?}"))), + } + Ok(()) + } + + pub(crate) fn get_string(&self, key: &str) -> Result { + if is_secret_key(key) { + return Err(unsupported(&format!("reading secret option {key:?}"))); + } + let value = if let Some(name) = key.strip_prefix(SESSION_CONF_PREFIX) { + self.session_conf.get(name).cloned() + } else if let Some(name) = strip_prefix_ignore_ascii_case(key, SERVER_SIDE_PROPERTY_PREFIX) + { + validate_server_side_property_name(name)?; + self.session_conf.get(name).cloned() + } else { + match key { + adbc_core::constants::ADBC_OPTION_URI => self.uri.clone(), + HOST => self.host.get().cloned(), + HTTP_PATH | "databricks.http_path" => self.http_path.get().cloned(), + WAREHOUSE_ID | "databricks.warehouse_id" => self.warehouse_id.clone(), + CATALOG | "adbc.connection.catalog" => self.catalog.get().cloned(), + SCHEMA | "adbc.connection.db_schema" => self.schema.get().cloned(), + AUTH_TYPE => self + .auth_mode + .get() + .map(|mode| auth_mode_name(*mode).to_string()), + GEOSPATIAL_REPRESENTATION => self.geospatial.get().map(|value| match value { + kernel::GeospatialResultRepresentation::String => "string".to_string(), + kernel::GeospatialResultRepresentation::Binary => "binary".to_string(), + _ => "unknown".to_string(), + }), + ESCAPE_CATALOG_NAME => Some(self.escape_catalog_name.unwrap_or(true).to_string()), + _ => None, + } + }; + value.ok_or_else(|| { + adbc_error( + format!("database option {key:?} is not set"), + Status::NotFound, + ) + }) + } + + pub(crate) fn resolve(&self) -> Result { + self.validate()?; + let (uri_host, uri_path, uri_warehouse) = parse_uri(self.uri.as_deref())?; + let host = self.host.get().cloned().or(uri_host).ok_or_else(|| { + adbc_error( + "required database option uri or adbc.databricks.host is missing", + Status::InvalidState, + ) + })?; + let http_path = self.http_path.get().cloned().or(uri_path); + let warehouse_id = self.warehouse_id.clone().or(uri_warehouse); + if http_path.is_some() == warehouse_id.is_some() { + return Err(adbc_error( + "exactly one of http_path or warehouse_id is required", + Status::InvalidState, + )); + } + if (self.tls_client_cert_file.is_some() || self.tls_client_cert_pem.is_some()) + && !host.to_ascii_lowercase().starts_with("https://") + { + return Err(adbc_error( + "mTLS requires an HTTPS workspace URI", + Status::InvalidArguments, + )); + } + let auth = self.resolve_auth()?; + let tls = self.resolve_tls()?; + let mut session_conf = self.session_conf.clone(); + if let Some(tags) = &self.query_tags { + if let Some(existing) = session_conf.get("QUERY_TAGS") { + if existing != tags { + return Err(adbc_error( + "adbc.databricks.query_tags conflicts with session_conf.QUERY_TAGS", + Status::InvalidArguments, + )); + } + } else { + session_conf.insert("QUERY_TAGS".to_string(), tags.clone()); + } + } + Ok(ResolvedConfig { + host, + http_path, + warehouse_id, + catalog: self.catalog.get().cloned(), + schema: self.schema.get().cloned(), + auth, + http: self.http.clone(), + proxy: self.proxy.url.as_ref().map(|_| self.proxy.clone()), + tls, + logging: self.logging.clone(), + telemetry: self.telemetry.clone(), + result: self.result.clone(), + session_conf, + escape_catalog_name: self.escape_catalog_name.unwrap_or(true), + geospatial: self.geospatial.get().copied().unwrap_or_default(), + }) + } + + fn validate(&self) -> Result<()> { + if self.http_path.get().is_some() && self.warehouse_id.is_some() { + return Err(adbc_error( + "http_path and warehouse_id are mutually exclusive", + Status::InvalidArguments, + )); + } + if self.http.retry_min_wait > self.http.retry_max_wait { + return Err(adbc_error( + "retry_min_wait_ms must not exceed retry_max_wait_ms", + Status::InvalidArguments, + )); + } + if self.proxy.username.is_some() && self.proxy.url.is_none() { + return Err(adbc_error( + "proxy username requires proxy URL", + Status::InvalidArguments, + )); + } + if self.proxy.password.is_some() && self.proxy.username.is_none() { + return Err(adbc_error( + "proxy password requires proxy username", + Status::InvalidArguments, + )); + } + if let Some(url) = &self.proxy.url { + if !(url.starts_with("http://") || url.starts_with("https://")) { + return Err(adbc_error( + "proxy URL must use http or https", + Status::InvalidArguments, + )); + } + } + if self + .proxy + .url + .as_deref() + .is_some_and(proxy_url_has_userinfo) + { + return Err(adbc_error( + "proxy URL must not contain embedded credentials; use proxy username and password options", + Status::InvalidArguments, + )); + } + if self.tls_ca_file.is_some() && self.tls_ca_pem.is_some() { + return Err(adbc_error( + "tls.ca_file and tls.ca_pem are mutually exclusive", + Status::InvalidArguments, + )); + } + if self.tls_client_cert_file.is_some() && self.tls_client_cert_pem.is_some() { + return Err(adbc_error( + "client certificate file and bytes are mutually exclusive", + Status::InvalidArguments, + )); + } + if self.tls_client_key_file.is_some() && self.tls_client_key_pem.is_some() { + return Err(adbc_error( + "client key file and bytes are mutually exclusive", + Status::InvalidArguments, + )); + } + let has_cert = self.tls_client_cert_file.is_some() || self.tls_client_cert_pem.is_some(); + let has_key = self.tls_client_key_file.is_some() || self.tls_client_key_pem.is_some(); + if has_cert != has_key { + return Err(adbc_error( + "mTLS client certificate and key must be supplied together", + Status::InvalidArguments, + )); + } + if self.telemetry.circuit_breaker_enabled && self.telemetry.circuit_breaker_threshold == 0 { + return Err(adbc_error( + "telemetry circuit breaker threshold must be positive", + Status::InvalidArguments, + )); + } + Ok(()) + } + + fn resolve_auth(&self) -> Result { + let mode = self + .auth_mode + .get() + .copied() + .or_else(|| self.infer_auth_mode()) + .ok_or_else(|| { + adbc_error( + "authentication type cannot be inferred", + Status::InvalidState, + ) + })?; + let federation = self.identity_federation_client_id.clone(); + match mode { + AuthMode::Pat => kernel::AuthConfig::pat( + self.token + .get() + .or(self.password.as_ref()) + .map(|v| v.expose().to_string()), + federation, + ) + .map_err(map_kernel_error), + AuthMode::OAuthM2M => kernel::AuthConfig::oauth_m2m( + self.oauth_client_id.clone().or(self.username.clone()), + self.oauth_client_secret + .as_ref() + .or(self.password.as_ref()) + .map(|v| v.expose().to_string()), + self.oauth_scopes.get().cloned(), + self.oauth_token_url.clone(), + federation, + ) + .map_err(map_kernel_error), + AuthMode::OAuthU2M => Ok(kernel::AuthConfig::oauth_u2m( + self.oauth_client_id.clone(), + self.oauth_redirect_ports.clone(), + self.oauth_scopes.get().cloned(), + self.oauth_token_url.clone(), + self.oauth_callback_timeout, + Some(kernel::TokenCacheConfig { + enabled: self.token_cache_enabled.unwrap_or(true), + passphrase: self + .token_cache_passphrase + .as_ref() + .map(|v| v.expose().to_string()), + }), + federation, + )), + AuthMode::OAuthM2MPrivateKey => kernel::AuthConfig::oauth_m2m_private_key( + self.oauth_client_id.clone().or(self.username.clone()), + self.jwt_key_file.clone(), + self.jwt_kid.clone(), + self.jwt_passphrase.as_ref().map(|v| v.expose().to_string()), + self.jwt_algorithm.clone(), + self.oauth_scopes.get().cloned(), + self.oauth_token_url.clone(), + ) + .map_err(map_kernel_error), + AuthMode::AzureServicePrincipal => kernel::AuthConfig::azure_service_principal( + self.azure_client_id.clone(), + self.azure_client_secret + .as_ref() + .map(|v| v.expose().to_string()), + self.azure_tenant_id.clone(), + self.azure_workspace_resource_id.clone(), + federation, + ) + .map_err(map_kernel_error), + AuthMode::OAuthFederation => Err(unsupported("direct OAuth federation (kernel gap)")), + } + } + + fn infer_auth_mode(&self) -> Option { + if self.azure_client_id.is_some() || self.azure_client_secret.is_some() { + Some(AuthMode::AzureServicePrincipal) + } else if self.jwt_key_file.is_some() || self.jwt_kid.is_some() { + Some(AuthMode::OAuthM2MPrivateKey) + } else if self.oauth_client_secret.is_some() { + Some(AuthMode::OAuthM2M) + } else if self.token.get().is_some() || self.password.is_some() { + Some(AuthMode::Pat) + } else { + None + } + } + + fn resolve_tls(&self) -> Result { + let read = |path: &str, option: &str| { + std::fs::read(path).map_err(|_| { + adbc_error( + format!("could not read file configured by {option}"), + Status::InvalidArguments, + ) + }) + }; + let ca = match (&self.tls_ca_pem, &self.tls_ca_file) { + (Some(bytes), _) => Some(bytes.clone()), + (_, Some(path)) => Some(read(path, "adbc.databricks.tls.ca_file")?), + _ => None, + }; + let cert = match (&self.tls_client_cert_pem, &self.tls_client_cert_file) { + (Some(bytes), _) => Some(bytes.clone()), + (_, Some(path)) => Some(read(path, "adbc.databricks.tls.client_cert_file")?), + _ => None, + }; + let key = match (&self.tls_client_key_pem, &self.tls_client_key_file) { + (Some(bytes), _) => Some(bytes.expose().to_vec()), + (_, Some(path)) => Some(read(path, "adbc.databricks.tls.client_key_file")?), + _ => None, + }; + let mut tls = kernel::TlsConfig::default(); + tls.custom_ca_cert = ca; + tls.accept_self_signed = self.tls_accept_self_signed; + tls.skip_hostname_verification = self.tls_skip_hostname_verification; + tls.client_cert_pem = cert; + tls.client_key_pem = key; + Ok(tls) + } +} + +fn strip_prefix_ignore_ascii_case<'a>(value: &'a str, prefix: &str) -> Option<&'a str> { + let candidate = value.get(..prefix.len())?; + candidate + .eq_ignore_ascii_case(prefix) + .then(|| &value[prefix.len()..]) +} + +fn validate_server_side_property_name(name: &str) -> Result<()> { + if name.is_empty() + || !name + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.')) + { + return Err(adbc_error( + "server-side property name must contain only ASCII letters, digits, dots, and underscores", + Status::InvalidArguments, + )); + } + Ok(()) +} + +fn proxy_url_has_userinfo(url: &str) -> bool { + url.split_once("://") + .map(|(_, rest)| rest.split(['/', '?', '#']).next().unwrap_or(rest)) + .is_some_and(|authority| authority.contains('@')) +} + +fn parse_auth_mode(value: &str) -> Result { + match value { + "pat" => Ok(AuthMode::Pat), + "oauth_m2m" => Ok(AuthMode::OAuthM2M), + "oauth_u2m" => Ok(AuthMode::OAuthU2M), + "oauth_m2m_private_key" => Ok(AuthMode::OAuthM2MPrivateKey), + "azure_service_principal" => Ok(AuthMode::AzureServicePrincipal), + "oauth_federation" => Ok(AuthMode::OAuthFederation), + _ => Err(adbc_error( + format!("invalid authentication type {value:?}"), + Status::InvalidArguments, + )), + } +} +fn parse_grant_type(value: &str) -> Result { + match value { + "access_token" => Ok(AuthMode::Pat), + "client_credentials" => Ok(AuthMode::OAuthM2M), + _ => Err(adbc_error( + "invalid OAuth grant_type", + Status::InvalidArguments, + )), + } +} +fn auth_mode_name(mode: AuthMode) -> &'static str { + match mode { + AuthMode::Pat => "pat", + AuthMode::OAuthM2M => "oauth_m2m", + AuthMode::OAuthU2M => "oauth_u2m", + AuthMode::OAuthM2MPrivateKey => "oauth_m2m_private_key", + AuthMode::AzureServicePrincipal => "azure_service_principal", + AuthMode::OAuthFederation => "oauth_federation", + } +} +fn parse_scopes(value: &str) -> Vec { + value + .split([',', ' ']) + .filter(|v| !v.is_empty()) + .map(str::to_string) + .collect() +} +fn parse_ports(value: &str, key: &str) -> Result> { + value + .split(',') + .map(|v| { + v.trim().parse::().map_err(|_| { + adbc_error( + format!("option {key:?} requires comma-separated ports"), + Status::InvalidArguments, + ) + }) + }) + .collect() +} +fn parse_geospatial(value: &str) -> Result { + match value { + "string" => Ok(kernel::GeospatialResultRepresentation::String), + "binary" => Ok(kernel::GeospatialResultRepresentation::Binary), + _ => Err(adbc_error( + "geospatial result representation must be string or binary", + Status::InvalidArguments, + )), + } +} +fn string_value(value: OptionValue, key: &str) -> Result { + match value { + OptionValue::String(value) => Ok(value), + _ => Err(adbc_error( + format!("option {key:?} requires a string"), + Status::InvalidArguments, + )), + } +} +fn bytes_value(value: OptionValue, key: &str) -> Result> { + match value { + OptionValue::Bytes(value) => Ok(value), + _ => Err(adbc_error( + format!("option {key:?} requires bytes"), + Status::InvalidArguments, + )), + } +} +fn boolean(value: OptionValue, key: &str) -> Result { + bool::try_from(value).map_err(|_| { + adbc_error( + format!("option {key:?} requires true or false"), + Status::InvalidArguments, + ) + }) +} +fn boolean_compat(value: OptionValue, key: &str) -> Result { + match value { + OptionValue::Int(0) => Ok(false), + OptionValue::Int(1) => Ok(true), + other => boolean(other, key), + } +} +fn integer(value: OptionValue, key: &str) -> Result { + match value { + OptionValue::Int(value) => Ok(value), + _ => Err(adbc_error( + format!("option {key:?} requires an integer"), + Status::InvalidArguments, + )), + } +} +fn integer_compat(value: OptionValue, key: &str) -> Result { + match value { + OptionValue::String(value) => value.parse().map_err(|_| { + adbc_error( + format!("option {key:?} requires an integer"), + Status::InvalidArguments, + ) + }), + other => integer(other, key), + } +} +fn positive_usize(value: OptionValue, key: &str) -> Result { + let value = integer(value, key)?; + usize::try_from(value) + .ok() + .filter(|v| *v > 0) + .ok_or_else(|| { + adbc_error( + format!("option {key:?} requires a positive integer"), + Status::InvalidArguments, + ) + }) +} +fn positive_usize_compat(value: OptionValue, key: &str) -> Result { + let value = integer_compat(value, key)?; + usize::try_from(value) + .ok() + .filter(|v| *v > 0) + .ok_or_else(|| { + adbc_error( + format!("option {key:?} requires a positive integer"), + Status::InvalidArguments, + ) + }) +} +fn nonnegative_u32(value: OptionValue, key: &str) -> Result { + u32::try_from(integer(value, key)?).map_err(|_| { + adbc_error( + format!("option {key:?} requires a nonnegative integer"), + Status::InvalidArguments, + ) + }) +} +fn nonnegative_u32_compat(value: OptionValue, key: &str) -> Result { + u32::try_from(integer_compat(value, key)?).map_err(|_| { + adbc_error( + format!("option {key:?} requires a nonnegative integer"), + Status::InvalidArguments, + ) + }) +} +fn duration(value: OptionValue, key: &str, allow_zero: bool) -> Result { + let value = integer(value, key)?; + let value = u64::try_from(value).map_err(|_| { + adbc_error( + format!("option {key:?} requires nonnegative milliseconds"), + Status::InvalidArguments, + ) + })?; + if !allow_zero && value == 0 { + return Err(adbc_error( + format!("option {key:?} must be positive"), + Status::InvalidArguments, + )); + } + Ok(Duration::from_millis(value)) +} +fn duration_compat(value: OptionValue, key: &str, allow_zero: bool) -> Result { + let value = u64::try_from(integer_compat(value, key)?).map_err(|_| { + adbc_error( + format!("option {key:?} requires nonnegative milliseconds"), + Status::InvalidArguments, + ) + })?; + if !allow_zero && value == 0 { + return Err(adbc_error( + format!("option {key:?} must be positive"), + Status::InvalidArguments, + )); + } + Ok(Duration::from_millis(value)) +} +fn duration_seconds(value: OptionValue, key: &str) -> Result { + let value = u64::try_from(integer(value, key)?).map_err(|_| { + adbc_error( + format!("option {key:?} requires nonnegative seconds"), + Status::InvalidArguments, + ) + })?; + if value == 0 { + return Err(adbc_error( + format!("option {key:?} must be positive"), + Status::InvalidArguments, + )); + } + Ok(Duration::from_secs(value)) +} +fn is_secret_key(key: &str) -> bool { + let key = key.to_ascii_lowercase(); + [ + "token", + "secret", + "password", + "passphrase", + "private_key", + "client_key", + "credential", + ] + .iter() + .any(|part| key.contains(part)) +} + +fn parse_headers(value: &str) -> Result> { + let entries: Vec> = serde_json::from_str(value).map_err(|_| { + adbc_error( + "adbc.databricks.http.headers must be a JSON array of string name/value objects", + Status::InvalidArguments, + ) + })?; + entries + .into_iter() + .map(|mut entry| { + let name = entry.remove("name").ok_or_else(|| { + adbc_error( + "HTTP header entry is missing name", + Status::InvalidArguments, + ) + })?; + let value = entry.remove("value").ok_or_else(|| { + adbc_error( + "HTTP header entry is missing value", + Status::InvalidArguments, + ) + })?; + if !entry.is_empty() { + return Err(adbc_error( + "HTTP header entry contains unknown fields", + Status::InvalidArguments, + )); + } + let lower = name.to_ascii_lowercase(); + if matches!( + lower.as_str(), + "authorization" + | "host" + | "content-length" + | "x-databricks-org-id" + | "x-request-id" + | "traceparent" + | "tracestate" + ) { + return Err(adbc_error( + format!("HTTP header {name:?} is managed by the driver"), + Status::InvalidArguments, + )); + } + Ok((name, value)) + }) + .collect() +} + +fn parse_uri(uri: Option<&str>) -> Result<(Option, Option, Option)> { + let Some(uri) = uri else { + return Ok((None, None, None)); + }; + if uri.contains('@') { + return Err(adbc_error( + "URI must not contain embedded credentials", + Status::InvalidArguments, + )); + } + if uri.starts_with("http://") || uri.starts_with("https://") { + return Ok((Some(uri.to_string()), None, None)); + } + let rest = uri.strip_prefix("databricks://").ok_or_else(|| { + adbc_error( + "URI must use https or databricks scheme", + Status::InvalidArguments, + ) + })?; + let (host, query) = rest.split_once('?').unwrap_or((rest, "")); + if host.is_empty() { + return Err(adbc_error( + "Databricks URI host is empty", + Status::InvalidArguments, + )); + } + let mut path = None; + let mut warehouse = None; + for item in query.split('&').filter(|item| !item.is_empty()) { + let (key, value) = item.split_once('=').unwrap_or((item, "")); + match key { + "http_path" => path = Some(value.to_string()), + "warehouse_id" => warehouse = Some(value.to_string()), + _ => {} + } + } + Ok((Some(format!("https://{host}")), path, warehouse)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn set(config: &mut DatabaseConfig, key: &str, value: impl Into) { + config.set_option(key, value.into()).unwrap(); + } + + #[test] + fn debug_redacts_every_secret_and_value_bag() { + let mut config = DatabaseConfig::default(); + set(&mut config, ACCESS_TOKEN, "sentinel-token"); + set(&mut config, OAUTH_CLIENT_SECRET, "sentinel-client-secret"); + set( + &mut config, + TOKEN_CACHE_PASSPHRASE, + "sentinel-cache-passphrase", + ); + set(&mut config, JWT_PASSPHRASE, "sentinel-jwt-passphrase"); + set(&mut config, AZURE_CLIENT_SECRET, "sentinel-azure-secret"); + set( + &mut config, + "adbc.databricks.proxy.password", + "sentinel-proxy-password", + ); + set( + &mut config, + "adbc.databricks.http.headers", + r#"[{"name":"x-custom","value":"sentinel-header"}]"#, + ); + set( + &mut config, + "adbc.databricks.session_conf.secretish", + "sentinel-conf", + ); + let debug = format!("{config:?}"); + for sentinel in [ + "sentinel-token", + "sentinel-client-secret", + "sentinel-cache-passphrase", + "sentinel-jwt-passphrase", + "sentinel-azure-secret", + "sentinel-proxy-password", + "sentinel-header", + "sentinel-conf", + ] { + assert!(!debug.contains(sentinel)); + } + } + + #[test] + fn catalog_name_escaping_defaults_true_and_can_be_disabled() { + let mut config = DatabaseConfig::default(); + assert_eq!(config.get_string(ESCAPE_CATALOG_NAME).unwrap(), "true"); + set(&mut config, ESCAPE_CATALOG_NAME, "false"); + assert_eq!(config.get_string(ESCAPE_CATALOG_NAME).unwrap(), "false"); + } + + #[test] + fn cloudfetch_max_chunks_option_configures_kernel_result_buffering() { + let mut config = DatabaseConfig::default(); + set(&mut config, CLOUDFETCH_MAX_CHUNKS_IN_MEMORY, "8"); + assert_eq!(config.result.cloudfetch_max_chunks_in_memory, 8); + + set( + &mut config, + "databricks.cloudfetch.max_chunks_in_memory", + "1", + ); + assert_eq!(config.result.cloudfetch_max_chunks_in_memory, 1); + + let error = config + .set_option(CLOUDFETCH_MAX_CHUNKS_IN_MEMORY, "0".into()) + .unwrap_err(); + assert_eq!(error.status, Status::InvalidArguments); + } + + #[test] + fn cloudfetch_enabled_option_configures_kernel_result_delivery() { + let mut config = DatabaseConfig::default(); + set(&mut config, CLOUDFETCH_ENABLED, "false"); + assert!(!config.result.cloudfetch_enabled); + + set(&mut config, "databricks.cloudfetch.enabled", "true"); + assert!(config.result.cloudfetch_enabled); + } + + #[test] + fn complex_datatype_support_configures_kernel_result_shape() { + let mut config = DatabaseConfig::default(); + + set(&mut config, ENABLE_COMPLEX_DATATYPE_SUPPORT, "false"); + assert!(config.result.complex_types_as_json); + + set(&mut config, ENABLE_COMPLEX_DATATYPE_SUPPORT, "true"); + assert!(!config.result.complex_types_as_json); + + let error = config + .set_option(ENABLE_COMPLEX_DATATYPE_SUPPORT, "not-a-boolean".into()) + .unwrap_err(); + assert_eq!(error.status, Status::InvalidArguments); + } + + #[test] + fn generic_ssp_options_configure_kernel_session_confs() { + let mut config = DatabaseConfig::default(); + set(&mut config, "adbc.databricks.ssp_ansi_mode", "true"); + set(&mut config, "adbc.databricks.ssp_timezone", "UTC"); + set( + &mut config, + "ADBC.DATABRICKS.SSP_spark.sql.ansi.enabled", + "false", + ); + + assert_eq!( + config.session_conf.get("ansi_mode"), + Some(&"true".to_string()) + ); + assert_eq!( + config.session_conf.get("timezone"), + Some(&"UTC".to_string()) + ); + assert_eq!( + config.session_conf.get("spark.sql.ansi.enabled"), + Some(&"false".to_string()) + ); + assert_eq!( + config.get_string("adbc.databricks.ssp_ansi_mode").unwrap(), + "true" + ); + assert_eq!( + config + .get_string("ADBC.DATABRICKS.SSP_spark.sql.ansi.enabled") + .unwrap(), + "false" + ); + } + + #[test] + fn generic_ssp_options_reject_empty_or_unsafe_names() { + let mut config = DatabaseConfig::default(); + for key in [ + "adbc.databricks.ssp_", + "adbc.databricks.ssp_bad name", + "adbc.databricks.ssp_also;bad", + "adbc.databricks.ssp_non-ascii-é", + ] { + let error = config.set_option(key, "value".into()).unwrap_err(); + assert_eq!(error.status, Status::InvalidArguments, "{key}"); + } + } + + #[test] + fn session_conf_and_ssp_collisions_use_last_set_value() { + let mut config = DatabaseConfig::default(); + set( + &mut config, + "adbc.databricks.session_conf.use_cached_result", + "true", + ); + set( + &mut config, + "adbc.databricks.ssp_use_cached_result", + "false", + ); + assert_eq!( + config.session_conf.get("use_cached_result"), + Some(&"false".to_string()) + ); + + set( + &mut config, + "adbc.databricks.session_conf.use_cached_result", + "true", + ); + assert_eq!( + config + .get_string("adbc.databricks.ssp_use_cached_result") + .unwrap(), + "true" + ); + } + + #[test] + fn protocol_option_accepts_rest_only() { + let mut config = DatabaseConfig::default(); + set(&mut config, PROTOCOL, "rest"); + set(&mut config, PROTOCOL, "REST"); + + let error = config.set_option(PROTOCOL, "thrift".into()).unwrap_err(); + assert_eq!(error.status, Status::NotImplemented); + } + + #[test] + fn proxy_url_rejects_embedded_credentials() { + let mut config = DatabaseConfig::default(); + set( + &mut config, + "adbc.databricks.proxy.url", + "https://user:secret@proxy.example.com:8443", + ); + let error = config.validate().unwrap_err(); + assert_eq!(error.status, Status::InvalidArguments); + assert!(!error.message.contains("secret")); + + set( + &mut config, + "adbc.databricks.proxy.url", + "https://proxy.example.com:8443/path@segment", + ); + assert!(config.validate().is_ok()); + } + + #[test] + fn proxy_basic_auth_reaches_kernel_config() { + let mut config = DatabaseConfig::default(); + set(&mut config, HOST, "https://example.databricks.com"); + set(&mut config, HTTP_PATH, "/sql/1.0/warehouses/warehouse-id"); + set(&mut config, ACCESS_TOKEN, "sentinel-token"); + set( + &mut config, + "adbc.databricks.proxy.url", + "https://proxy.example.com:8443", + ); + set(&mut config, "adbc.databricks.proxy.username", "proxy-user"); + set( + &mut config, + "adbc.databricks.proxy.password", + "sentinel-proxy-password", + ); + set( + &mut config, + "adbc.databricks.proxy.bypass_hosts", + "localhost,.example.com", + ); + + let proxy = config.resolve().unwrap().proxy.unwrap(); + assert_eq!(proxy.url.as_deref(), Some("https://proxy.example.com:8443")); + assert_eq!(proxy.username.as_deref(), Some("proxy-user")); + assert_eq!(proxy.password.as_deref(), Some("sentinel-proxy-password")); + assert_eq!( + proxy.bypass_hosts.as_deref(), + Some("localhost,.example.com") + ); + assert!(!format!("{proxy:?}").contains("sentinel-proxy-password")); + } + + #[test] + fn logging_options_reach_kernel_config() { + let mut config = DatabaseConfig::default(); + set(&mut config, HOST, "https://example.databricks.com"); + set(&mut config, HTTP_PATH, "/sql/1.0/warehouses/warehouse-id"); + set(&mut config, ACCESS_TOKEN, "sentinel-token"); + set( + &mut config, + "adbc.databricks.log.filter", + "databricks::sql::kernel=debug", + ); + set( + &mut config, + "adbc.databricks.log.file", + "/tmp/databricks-rust-adbc-test.log", + ); + + let logging = config.resolve().unwrap().logging; + assert_eq!( + logging.filter.as_deref(), + Some("databricks::sql::kernel=debug") + ); + assert_eq!( + logging.file.as_deref(), + Some(std::path::Path::new("/tmp/databricks-rust-adbc-test.log")) + ); + } + + #[test] + fn resolved_auth_debug_redacts_every_secret() { + let mut pat = DatabaseConfig::default(); + set(&mut pat, AUTH_TYPE, "pat"); + set(&mut pat, ACCESS_TOKEN, "sentinel-pat-token"); + + let mut m2m = DatabaseConfig::default(); + set(&mut m2m, AUTH_TYPE, "oauth_m2m"); + set(&mut m2m, OAUTH_CLIENT_ID, "client-id"); + set(&mut m2m, OAUTH_CLIENT_SECRET, "sentinel-m2m-secret"); + + let mut u2m = DatabaseConfig::default(); + set(&mut u2m, AUTH_TYPE, "oauth_u2m"); + set( + &mut u2m, + TOKEN_CACHE_PASSPHRASE, + "sentinel-cache-passphrase", + ); + + let mut private_key = DatabaseConfig::default(); + set(&mut private_key, AUTH_TYPE, "oauth_m2m_private_key"); + set(&mut private_key, OAUTH_CLIENT_ID, "client-id"); + set(&mut private_key, JWT_KEY_FILE, "/path/to/key.pem"); + set(&mut private_key, JWT_KID, "key-id"); + set(&mut private_key, JWT_PASSPHRASE, "sentinel-jwt-passphrase"); + + let mut azure = DatabaseConfig::default(); + set(&mut azure, AUTH_TYPE, "azure_service_principal"); + set(&mut azure, AZURE_CLIENT_ID, "client-id"); + set(&mut azure, AZURE_CLIENT_SECRET, "sentinel-azure-secret"); + + for (config, sentinel) in [ + (pat, "sentinel-pat-token"), + (m2m, "sentinel-m2m-secret"), + (u2m, "sentinel-cache-passphrase"), + (private_key, "sentinel-jwt-passphrase"), + (azure, "sentinel-azure-secret"), + ] { + let debug = format!("{:?}", config.resolve_auth().unwrap()); + assert!(!debug.contains(sentinel)); + } + } + + #[test] + fn identity_federation_client_id_reaches_supported_auth_variants() { + fn with_federation(mut config: DatabaseConfig) -> DatabaseConfig { + set( + &mut config, + IDENTITY_FEDERATION_CLIENT_ID, + "federation-client-id", + ); + config + } + + let mut pat = with_federation(DatabaseConfig::default()); + set(&mut pat, ACCESS_TOKEN, "token"); + + let mut m2m = with_federation(DatabaseConfig::default()); + set(&mut m2m, OAUTH_CLIENT_ID, "client-id"); + set(&mut m2m, OAUTH_CLIENT_SECRET, "client-secret"); + + let mut u2m = with_federation(DatabaseConfig::default()); + set(&mut u2m, AUTH_TYPE, "oauth_u2m"); + + let mut azure = with_federation(DatabaseConfig::default()); + set(&mut azure, AZURE_CLIENT_ID, "azure-client-id"); + set(&mut azure, AZURE_CLIENT_SECRET, "azure-client-secret"); + + for config in [pat, m2m, u2m, azure] { + let debug = format!("{:?}", config.resolve_auth().unwrap()); + assert!(debug.contains("federation-client-id")); + } + } + + #[test] + fn u2m_token_cache_options_reach_kernel_auth_config() { + let mut config = DatabaseConfig::default(); + set(&mut config, AUTH_TYPE, "oauth_u2m"); + set(&mut config, OAUTH_CLIENT_ID, "u2m-client-id"); + set(&mut config, OAUTH_REDIRECT_PORTS, "8020,8025"); + set(&mut config, OAUTH_SCOPES, "sql,offline_access"); + set(&mut config, TOKEN_CACHE_ENABLED, false); + set( + &mut config, + TOKEN_CACHE_PASSPHRASE, + "sentinel-cache-passphrase", + ); + set( + &mut config, + IDENTITY_FEDERATION_CLIENT_ID, + "federation-client-id", + ); + + match config.resolve_auth().unwrap() { + kernel::AuthConfig::OAuthU2M { + client_id, + redirect_ports, + scopes, + token_cache, + identity_federation_client_id, + .. + } => { + assert_eq!(client_id.as_deref(), Some("u2m-client-id")); + assert_eq!(redirect_ports, Some(vec![8020, 8025])); + assert_eq!(scopes, Some(vec!["sql".into(), "offline_access".into()])); + let token_cache = token_cache.expect("driver must set token-cache policy"); + assert!(!token_cache.enabled); + assert_eq!( + token_cache.passphrase.as_deref(), + Some("sentinel-cache-passphrase") + ); + assert_eq!( + identity_federation_client_id.as_deref(), + Some("federation-client-id") + ); + } + other => panic!("expected OAuthU2M, got {other:?}"), + } + } + + #[test] + fn private_key_options_reach_kernel_auth_config() { + let mut config = DatabaseConfig::default(); + set(&mut config, AUTH_TYPE, "oauth_m2m_private_key"); + set(&mut config, OAUTH_CLIENT_ID, "private-key-client-id"); + set(&mut config, JWT_KEY_FILE, "/path/to/private-key.pem"); + set(&mut config, JWT_KID, "private-key-id"); + set(&mut config, JWT_PASSPHRASE, "sentinel-jwt-passphrase"); + set(&mut config, JWT_ALGORITHM, "PS256"); + set(&mut config, OAUTH_SCOPES, "all-apis,sql"); + + match config.resolve_auth().unwrap() { + kernel::AuthConfig::OAuthM2MPrivateKey { + client_id, + jwt_key_file, + jwt_kid, + jwt_passphrase, + jwt_algorithm, + scopes, + .. + } => { + assert_eq!(client_id, "private-key-client-id"); + assert_eq!(jwt_key_file, "/path/to/private-key.pem"); + assert_eq!(jwt_kid, "private-key-id"); + assert_eq!(jwt_passphrase.as_deref(), Some("sentinel-jwt-passphrase")); + assert_eq!(jwt_algorithm.as_deref(), Some("PS256")); + assert_eq!(scopes, Some(vec!["all-apis".into(), "sql".into()])); + } + other => panic!("expected OAuthM2MPrivateKey, got {other:?}"), + } + } + + #[test] + fn azure_service_principal_options_reach_kernel_auth_config() { + let mut config = DatabaseConfig::default(); + set(&mut config, AUTH_TYPE, "azure_service_principal"); + set(&mut config, AZURE_CLIENT_ID, "azure-client-id"); + set(&mut config, AZURE_CLIENT_SECRET, "sentinel-azure-secret"); + set(&mut config, AZURE_TENANT_ID, "azure-tenant-id"); + set( + &mut config, + AZURE_WORKSPACE_RESOURCE_ID, + "/subscriptions/test/resourceGroups/test/providers/Microsoft.Databricks/workspaces/test", + ); + set( + &mut config, + IDENTITY_FEDERATION_CLIENT_ID, + "federation-client-id", + ); + + match config.resolve_auth().unwrap() { + kernel::AuthConfig::AzureServicePrincipal { + azure_client_id, + azure_client_secret, + azure_tenant_id, + azure_workspace_resource_id, + identity_federation_client_id, + } => { + assert_eq!(azure_client_id, "azure-client-id"); + assert_eq!(azure_client_secret, "sentinel-azure-secret"); + assert_eq!(azure_tenant_id.as_deref(), Some("azure-tenant-id")); + assert_eq!( + azure_workspace_resource_id.as_deref(), + Some( + "/subscriptions/test/resourceGroups/test/providers/Microsoft.Databricks/workspaces/test" + ) + ); + assert_eq!( + identity_federation_client_id.as_deref(), + Some("federation-client-id") + ); + } + other => panic!("expected AzureServicePrincipal, got {other:?}"), + } + } + + #[test] + fn canonical_value_wins_regardless_of_order() { + let mut config = DatabaseConfig::default(); + set(&mut config, HTTP_PATH, "/sql/1.0/warehouses/canonical"); + set(&mut config, "http_path", "/sql/1.0/warehouses/alias"); + assert_eq!( + config.http_path.get().unwrap(), + "/sql/1.0/warehouses/canonical" + ); + } + + #[test] + fn secret_options_are_write_only() { + let mut config = DatabaseConfig::default(); + set(&mut config, ACCESS_TOKEN, "sentinel-token"); + assert_eq!( + config.get_string(ACCESS_TOKEN).unwrap_err().status, + Status::NotImplemented + ); + } + + #[test] + fn headers_reject_security_sensitive_names() { + let mut config = DatabaseConfig::default(); + let error = config + .set_option( + "adbc.databricks.http.headers", + r#"[{"name":"Authorization","value":"secret"}]"#.into(), + ) + .unwrap_err(); + assert_eq!(error.status, Status::InvalidArguments); + assert!(!error.message.contains("secret")); + } + + #[test] + fn http_pool_and_custom_headers_reach_kernel_config() { + let mut config = DatabaseConfig::default(); + set(&mut config, HOST, "https://example.databricks.com"); + set(&mut config, HTTP_PATH, "/sql/1.0/warehouses/warehouse-id"); + set(&mut config, ACCESS_TOKEN, "sentinel-token"); + set( + &mut config, + "adbc.databricks.http.pool_max_idle_per_host", + 37_i64, + ); + set( + &mut config, + "adbc.databricks.http.headers", + r#"[{"name":"x-databricks-test","value":"sentinel"}]"#, + ); + + let resolved = config.resolve().unwrap(); + assert_eq!(resolved.http.pool_max_idle_per_host, 37); + assert_eq!( + resolved.http.custom_headers, + vec![("x-databricks-test".into(), "sentinel".into())] + ); + } + + #[test] + fn telemetry_options_reach_kernel_config() { + let mut config = DatabaseConfig::default(); + set(&mut config, HOST, "https://example.databricks.com"); + set(&mut config, HTTP_PATH, "/sql/1.0/warehouses/warehouse-id"); + set(&mut config, ACCESS_TOKEN, "sentinel-token"); + set(&mut config, "adbc.databricks.telemetry.enabled", true); + set(&mut config, "adbc.databricks.telemetry.batch_size", "17"); + set( + &mut config, + "adbc.databricks.telemetry.flush_interval_ms", + "2300", + ); + set(&mut config, "adbc.databricks.telemetry.max_retries", "4"); + set( + &mut config, + "adbc.databricks.telemetry.retry_delay_ms", + "250", + ); + set( + &mut config, + "adbc.databricks.telemetry.close_flush_timeout_ms", + "3100", + ); + set( + &mut config, + "adbc.databricks.telemetry.circuit_breaker_enabled", + true, + ); + set( + &mut config, + "adbc.databricks.telemetry.circuit_breaker_threshold", + "7", + ); + set( + &mut config, + "adbc.databricks.telemetry.circuit_breaker_timeout_ms", + "4200", + ); + + let telemetry = config.resolve().unwrap().telemetry; + assert_eq!(telemetry.enabled, Some(true)); + assert_eq!(telemetry.batch_size, 17); + assert_eq!(telemetry.flush_interval, Duration::from_millis(2300)); + assert_eq!(telemetry.max_retries, 4); + assert_eq!(telemetry.retry_delay, Duration::from_millis(250)); + assert_eq!(telemetry.close_flush_timeout, Duration::from_millis(3100)); + assert!(telemetry.circuit_breaker_enabled); + assert_eq!(telemetry.circuit_breaker_threshold, 7); + assert_eq!( + telemetry.circuit_breaker_timeout, + Duration::from_millis(4200) + ); + } + + #[test] + fn telemetry_numeric_options_reject_invalid_strings() { + for (key, value) in [ + ("adbc.databricks.telemetry.batch_size", "0"), + ("adbc.databricks.telemetry.flush_interval_ms", "invalid"), + ("adbc.databricks.telemetry.max_retries", "-1"), + ] { + let mut config = DatabaseConfig::default(); + let error = config.set_option(key, value.into()).unwrap_err(); + assert_eq!(error.status, Status::InvalidArguments, "{key}"); + } + } + + #[test] + fn conflicts_are_rejected_before_network() { + let mut config = DatabaseConfig::default(); + set(&mut config, HTTP_PATH, "/sql/1.0/warehouses/a"); + set(&mut config, WAREHOUSE_ID, "b"); + let Err(error) = config.resolve() else { + panic!("conflicting endpoint options should fail"); + }; + assert_eq!(error.status, Status::InvalidArguments); + } + + #[test] + fn http_path_preserves_workspace_organization_query() { + let mut config = DatabaseConfig::default(); + set(&mut config, HOST, "https://example.databricks.com"); + set( + &mut config, + HTTP_PATH, + "/sql/1.0/warehouses/warehouse-id?o=123456789", + ); + set(&mut config, ACCESS_TOKEN, "sentinel-token"); + + assert_eq!( + config.resolve().unwrap().http_path.as_deref(), + Some("/sql/1.0/warehouses/warehouse-id?o=123456789") + ); + } + + #[test] + fn reserved_direct_custom_federation_is_not_implemented() { + let mut config = DatabaseConfig::default(); + set(&mut config, AUTH_TYPE, "oauth_federation"); + assert_eq!( + config.resolve_auth().unwrap_err().status, + Status::NotImplemented + ); + } +} diff --git a/adbc/src/connection.rs b/adbc/src/connection.rs new file mode 100644 index 00000000..2d906c90 --- /dev/null +++ b/adbc/src/connection.rs @@ -0,0 +1,410 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::{ + collections::HashSet, + sync::{Arc, Mutex}, +}; + +use adbc_core::error::{Result, Status}; +use adbc_core::options::{InfoCode, ObjectDepth, OptionConnection, OptionValue}; +use arrow_array::cast::AsArray as _; +use arrow_array::{Array as _, RecordBatch, RecordBatchReader}; +use arrow_schema::{DataType, Schema}; +use databricks_sql_kernel as kernel; + +use crate::cancellation::CancellationRegistry; +use crate::error::{adbc_error, map_kernel_error, option_not_found, unsupported}; +use crate::runtime::{RuntimeExt as _, RuntimeHandle}; +use crate::Statement; + +#[path = "metadata.rs"] +pub(crate) mod metadata; + +pub struct Connection { + session: Option, + runtime: Arc, + vendor_version: Mutex>, + escape_catalog_name: bool, + cancellation: Arc, +} + +impl Connection { + pub(crate) fn new( + session: kernel::Session, + runtime: Arc, + escape_catalog_name: bool, + ) -> Self { + Self { + session: Some(session), + runtime, + vendor_version: Mutex::new(None), + escape_catalog_name, + cancellation: Arc::new(CancellationRegistry::default()), + } + } + + fn session(&self) -> Result<&kernel::Session> { + self.session + .as_ref() + .ok_or_else(|| adbc_error("connection is closed", Status::InvalidState)) + } + + fn execute_session_command(&self, sql: String) -> Result<()> { + let mut statement = self.session()?.statement(); + let canceller = statement.canceller(); + let runtime = Arc::clone(&self.runtime); + let _operation = self.cancellation.register(Arc::new(move || { + let dispatched = runtime + .block_on_safe(canceller.cancel()) + .map_err(map_kernel_error)?; + if dispatched { + Ok(()) + } else { + Err(adbc_error( + "connection cancellation raced before the server statement identifier was available", + Status::Unknown, + )) + } + }))?; + statement.spec().sql(sql); + let mut executed = self + .runtime + .block_on_safe(statement.execute()) + .map_err(map_kernel_error)?; + while self + .runtime + .block_on_safe(executed.next_batch()) + .map_err(map_kernel_error)? + .is_some() + {} + Ok(()) + } + + fn set_current_catalog(&mut self, value: String) -> Result<()> { + let quoted = quote_session_identifier(&value)?; + self.execute_session_command(format!("USE CATALOG {quoted}")) + } + + fn set_current_schema(&mut self, value: String) -> Result<()> { + let quoted = quote_session_identifier(&value)?; + self.execute_session_command(format!("USE SCHEMA {quoted}")) + } + + fn current_namespace(&self) -> Result<(String, String)> { + let mut statement = self.session()?.statement(); + let canceller = statement.canceller(); + let runtime = Arc::clone(&self.runtime); + let _operation = self.cancellation.register(Arc::new(move || { + let dispatched = runtime + .block_on_safe(canceller.cancel()) + .map_err(map_kernel_error)?; + if dispatched { + Ok(()) + } else { + Err(adbc_error( + "connection cancellation raced before the server statement identifier was available", + Status::Unknown, + )) + } + }))?; + statement + .spec() + .sql("SELECT current_catalog(), current_schema()"); + let mut executed = self + .runtime + .block_on_safe(statement.execute()) + .map_err(map_kernel_error)?; + let namespace = match self + .runtime + .block_on_safe(executed.next_batch()) + .map_err(map_kernel_error)? + { + Some(kernel::ResultBatch::Arrow(batch)) + if batch.num_rows() > 0 && batch.num_columns() >= 2 => + { + ( + required_namespace_value(batch, 0, "current catalog")?, + required_namespace_value(batch, 1, "current schema")?, + ) + } + Some(_) => { + return Err(adbc_error( + "current namespace query returned an invalid result", + Status::InvalidData, + )); + } + None => { + return Err(adbc_error( + "current namespace query returned no result", + Status::InvalidData, + )); + } + }; + while self + .runtime + .block_on_safe(executed.next_batch()) + .map_err(map_kernel_error)? + .is_some() + {} + Ok(namespace) + } +} + +impl Drop for Connection { + fn drop(&mut self) { + if let Some(session) = self.session.take() { + // Await DeleteSession before the connection-owned runtime is dropped. + // Kernel Session::Drop is intentionally fire-and-forget, which is not + // sufficient here because this runtime is the task executor. + let _ = self.runtime.block_on_safe(session.close()); + } + } +} + +fn quote_session_identifier(value: &str) -> Result { + if value.is_empty() || value.trim().is_empty() { + return Err(adbc_error( + "identifier must not be empty or whitespace", + Status::InvalidArguments, + )); + } + if value.contains('\0') { + return Err(adbc_error( + "identifier must not contain a NUL byte", + Status::InvalidArguments, + )); + } + if value.len() > 255 { + return Err(adbc_error( + "identifier exceeds the 255-byte limit", + Status::InvalidArguments, + )); + } + Ok(format!("`{}`", value.replace('`', "``"))) +} + +fn required_namespace_value(batch: &RecordBatch, column: usize, label: &str) -> Result { + let value = batch.column(column); + if value.is_null(0) { + return Err(adbc_error( + format!("current namespace query returned null {label}"), + Status::InvalidData, + )); + } + match value.data_type() { + DataType::Utf8 => Ok(value.as_string::().value(0).to_owned()), + DataType::LargeUtf8 => Ok(value.as_string::().value(0).to_owned()), + other => Err(adbc_error( + format!("current namespace query returned {other} for {label}, expected UTF-8"), + Status::InvalidData, + )), + } +} + +fn string_option(value: OptionValue, key: &str) -> Result { + match value { + OptionValue::String(value) => Ok(value), + _ => Err(adbc_error( + format!("connection option {key} requires a string"), + Status::InvalidArguments, + )), + } +} + +impl adbc_core::Optionable for Connection { + type Option = OptionConnection; + + fn set_option(&mut self, key: OptionConnection, value: OptionValue) -> Result<()> { + match key { + OptionConnection::AutoCommit => { + let requested = bool::try_from(value)?; + self.runtime + .block_on_safe(self.session()?.set_autocommit(requested)) + .map_err(map_kernel_error)?; + if self.session()?.autocommit() != requested { + return Err(unsupported( + "disabling autocommit while transactions are ignored", + )); + } + Ok(()) + } + OptionConnection::CurrentCatalog => { + let catalog = string_option(value, "CurrentCatalog")?; + self.set_current_catalog(catalog) + } + OptionConnection::CurrentSchema => { + let schema = string_option(value, "CurrentSchema")?; + self.set_current_schema(schema) + } + _ => Err(unsupported(&format!("connection option {key:?}"))), + } + } + + fn get_option_string(&self, key: OptionConnection) -> Result { + match key { + OptionConnection::AutoCommit => Ok(self.session()?.autocommit().to_string()), + OptionConnection::CurrentCatalog => { + self.current_namespace().map(|(catalog, _)| catalog) + } + OptionConnection::CurrentSchema => self.current_namespace().map(|(_, schema)| schema), + _ => Err(option_not_found("connection string", key.as_ref())), + } + } + fn get_option_bytes(&self, key: OptionConnection) -> Result> { + Err(option_not_found("connection bytes", key.as_ref())) + } + fn get_option_int(&self, key: OptionConnection) -> Result { + Err(option_not_found("connection integer", key.as_ref())) + } + fn get_option_double(&self, key: OptionConnection) -> Result { + Err(option_not_found("connection double", key.as_ref())) + } +} + +impl adbc_core::Connection for Connection { + type StatementType = Statement; + + fn new_statement(&mut self) -> Result { + Ok(Statement::new( + self.session()?.statement(), + self.session()?.metadata(), + Arc::clone(&self.runtime), + Arc::clone(&self.cancellation), + self.escape_catalog_name, + )) + } + fn cancel(&mut self) -> Result<()> { + self.cancellation.cancel() + } + fn get_info( + &self, + codes: Option>, + ) -> Result> { + metadata::get_info(self.session()?, &self.runtime, &self.vendor_version, codes) + } + fn get_objects( + &self, + depth: ObjectDepth, + catalog: Option<&str>, + db_schema: Option<&str>, + table_name: Option<&str>, + table_type: Option>, + column_name: Option<&str>, + ) -> Result> { + metadata::get_objects( + self.session()?, + &self.runtime, + depth, + catalog, + db_schema, + table_name, + table_type, + column_name, + self.escape_catalog_name, + ) + } + fn get_table_schema( + &self, + catalog: Option<&str>, + db_schema: Option<&str>, + table_name: &str, + ) -> Result { + metadata::get_table_schema( + self.session()?, + &self.runtime, + catalog, + db_schema, + table_name, + ) + } + fn get_table_types(&self) -> Result> { + metadata::get_table_types(self.session()?, &self.runtime) + } + fn get_statistic_names(&self) -> Result> { + Err(unsupported("get_statistic_names")) + } + fn get_statistics( + &self, + _catalog: Option<&str>, + _db_schema: Option<&str>, + _table_name: Option<&str>, + _approximate: bool, + ) -> Result> { + Err(unsupported("get_statistics")) + } + fn commit(&mut self) -> Result<()> { + self.runtime + .block_on_safe(self.session()?.commit()) + .map_err(map_kernel_error) + } + fn rollback(&mut self) -> Result<()> { + self.runtime + .block_on_safe(self.session()?.rollback()) + .map_err(map_kernel_error) + } + fn read_partition( + &self, + _partition: impl AsRef<[u8]>, + ) -> Result> { + Err(unsupported("read_partition")) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn session_identifiers_are_quoted_and_validated() { + assert_eq!(quote_session_identifier("a`b").unwrap(), "`a``b`"); + for invalid in ["", " ", "a\0b"] { + assert_eq!( + quote_session_identifier(invalid).unwrap_err().status, + Status::InvalidArguments + ); + } + assert_eq!( + quote_session_identifier(&"a".repeat(256)) + .unwrap_err() + .status, + Status::InvalidArguments + ); + } + + #[test] + fn namespace_values_accept_both_arrow_string_widths() { + let schema = Arc::new(Schema::new(vec![ + arrow_schema::Field::new("catalog", DataType::Utf8, false), + arrow_schema::Field::new("schema", DataType::LargeUtf8, false), + ])); + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(arrow_array::StringArray::from(vec!["catalog"])), + Arc::new(arrow_array::LargeStringArray::from(vec!["schema"])), + ], + ) + .unwrap(); + + assert_eq!( + required_namespace_value(&batch, 0, "catalog").unwrap(), + "catalog" + ); + assert_eq!( + required_namespace_value(&batch, 1, "schema").unwrap(), + "schema" + ); + } +} diff --git a/adbc/src/database.rs b/adbc/src/database.rs new file mode 100644 index 00000000..dcfadb71 --- /dev/null +++ b/adbc/src/database.rs @@ -0,0 +1,294 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::sync::{Arc, Mutex}; + +use adbc_core::error::Result; +use adbc_core::options::{OptionConnection, OptionDatabase, OptionValue}; +use adbc_core::Optionable as _; +use databricks_sql_kernel as kernel; + +use crate::config::DatabaseConfig; +use crate::error::option_not_found; +use crate::runtime::{RuntimeExt as _, RuntimeHandle}; +use crate::Connection; + +const DRIVER_NAME: &str = "Databricks ADBC Driver for Rust"; + +fn driver_system_configuration() -> kernel::DriverSystemConfiguration { + kernel::DriverSystemConfiguration { + driver_name: Some(DRIVER_NAME.into()), + driver_version: Some(env!("CARGO_PKG_VERSION").into()), + ..Default::default() + } +} + +#[derive(Clone, Debug)] +pub struct Database { + config: DatabaseConfig, + runtime: Arc>>>, +} + +impl Database { + /// Create a database that executes kernel work on a caller-owned runtime. + /// + /// All connections created from this database share the runtime. Dropping + /// the database or its connections never shuts down an injected runtime. + pub fn with_runtime(runtime: Arc) -> Result { + if !matches!( + runtime.handle().runtime_flavor(), + tokio::runtime::RuntimeFlavor::MultiThread + ) { + return Err(adbc_core::error::Error::with_message_and_status( + "an injected runtime must use the Tokio multi-thread scheduler", + adbc_core::error::Status::InvalidArguments, + )); + } + Ok(Self { + config: DatabaseConfig::default(), + runtime: Arc::new(Mutex::new(Some(RuntimeHandle::injected(runtime)))), + }) + } + + fn runtime(&self) -> Result> { + let mut runtime = self.runtime.lock().map_err(|_| { + adbc_core::error::Error::with_message_and_status( + "database runtime lock is poisoned", + adbc_core::error::Status::Internal, + ) + })?; + if let Some(runtime) = runtime.as_ref() { + return Ok(Arc::clone(runtime)); + } + let created = RuntimeHandle::create().map_err(|source| { + adbc_core::error::Error::with_message_and_status( + source.to_string(), + adbc_core::error::Status::Internal, + ) + })?; + *runtime = Some(Arc::clone(&created)); + Ok(created) + } + + fn open(&self) -> Result { + let resolved = self.config.resolve()?; + let mut builder = kernel::Session::builder() + .auth(resolved.auth) + .http(resolved.http) + .tls(resolved.tls) + .logging(resolved.logging) + .telemetry(resolved.telemetry) + .result(resolved.result) + .driver_system_configuration(driver_system_configuration()) + .session_conf(resolved.session_conf) + .geospatial_result_representation(resolved.geospatial); + if let Some(proxy) = resolved.proxy { + builder = builder.proxy(proxy); + } + builder = if let Some(http_path) = &resolved.http_path { + builder.http_path(&resolved.host, http_path) + } else { + builder.connection(kernel::ConnectionConfig::new( + &resolved.host, + resolved.warehouse_id.as_deref().unwrap_or_default(), + )) + }; + if resolved.catalog.is_some() || resolved.schema.is_some() { + let mut defaults = kernel::DefaultOpts::default(); + defaults.catalog.clone_from(&resolved.catalog); + defaults.schema.clone_from(&resolved.schema); + builder = builder.defaults(defaults); + } + let runtime = self.runtime()?; + let session = runtime + .block_on_safe(builder.open()) + .map_err(crate::error::map_kernel_error)?; + Ok(Connection::new( + session, + runtime, + resolved.escape_catalog_name, + )) + } +} + +impl Default for Database { + fn default() -> Self { + Self { + config: DatabaseConfig::default(), + runtime: Arc::new(Mutex::new(None)), + } + } +} + +impl adbc_core::Optionable for Database { + type Option = OptionDatabase; + + fn set_option(&mut self, key: OptionDatabase, value: OptionValue) -> Result<()> { + self.config.set_option(key.as_ref(), value) + } + + fn get_option_string(&self, key: OptionDatabase) -> Result { + self.config.get_string(key.as_ref()) + } + + fn get_option_bytes(&self, key: OptionDatabase) -> Result> { + Err(option_not_found("database bytes", key.as_ref())) + } + fn get_option_int(&self, key: OptionDatabase) -> Result { + Err(option_not_found("database integer", key.as_ref())) + } + fn get_option_double(&self, key: OptionDatabase) -> Result { + Err(option_not_found("database double", key.as_ref())) + } +} + +impl adbc_core::Database for Database { + type ConnectionType = Connection; + + fn new_connection(&self) -> Result { + self.open() + } + + fn new_connection_with_opts( + &self, + opts: impl IntoIterator, + ) -> Result { + let mut connection = self.open()?; + for (key, value) in opts { + connection.set_option(key, value)?; + } + Ok(connection) + } +} + +#[cfg(test)] +mod tests { + use adbc_core::{Database as _, Driver as _}; + + use crate::config::{ACCESS_TOKEN, ESCAPE_CATALOG_NAME, HTTP_PATH}; + use crate::Driver; + + use super::*; + + #[test] + fn options_round_trip() { + let database = Driver + .new_database_with_opts([ + (OptionDatabase::Uri, "https://example.databricks.com".into()), + ( + OptionDatabase::Other(HTTP_PATH.into()), + "/sql/1.0/warehouses/abc".into(), + ), + (OptionDatabase::Other(ACCESS_TOKEN.into()), "secret".into()), + ]) + .unwrap(); + assert_eq!( + database.get_option_string(OptionDatabase::Uri).unwrap(), + "https://example.databricks.com" + ); + assert_eq!( + database + .get_option_string(OptionDatabase::Other(ESCAPE_CATALOG_NAME.into())) + .unwrap(), + "true" + ); + + let mut database = database; + database + .set_option( + OptionDatabase::Other(ESCAPE_CATALOG_NAME.into()), + "false".into(), + ) + .unwrap(); + assert_eq!( + database + .get_option_string(OptionDatabase::Other(ESCAPE_CATALOG_NAME.into())) + .unwrap(), + "false" + ); + } + + #[test] + fn debug_does_not_expose_access_token() { + let database = Driver + .new_database_with_opts([( + OptionDatabase::Other(ACCESS_TOKEN.into()), + "sentinel-access-token".into(), + )]) + .unwrap(); + let debug = format!("{database:?}"); + assert!(debug.contains("")); + assert!(!debug.contains("sentinel-access-token")); + } + + #[test] + fn required_options_are_validated_before_network_io() { + let error = Database::default().new_connection().err().unwrap(); + assert_eq!(error.status, adbc_core::error::Status::InvalidState); + } + + #[test] + fn kernel_receives_rust_adbc_driver_identity() { + let identity = driver_system_configuration(); + assert_eq!(identity.driver_name.as_deref(), Some(DRIVER_NAME)); + assert_eq!( + identity.driver_version.as_deref(), + Some(env!("CARGO_PKG_VERSION")) + ); + } + + #[test] + fn clones_share_driver_owned_runtime() { + let database = Database::default(); + let clone = database.clone(); + assert!(Arc::ptr_eq( + &database.runtime().unwrap(), + &clone.runtime().unwrap() + )); + } + + #[test] + fn injected_runtime_is_shared_by_database_clones() { + let injected = Arc::new( + tokio::runtime::Builder::new_multi_thread() + .worker_threads(1) + .enable_all() + .build() + .unwrap(), + ); + let database = Database::with_runtime(Arc::clone(&injected)).unwrap(); + let clone = database.clone(); + assert!(Arc::ptr_eq( + &database.runtime().unwrap(), + &clone.runtime().unwrap() + )); + drop(database); + drop(clone); + assert_eq!(injected.block_on(async { 42 }), 42); + } + + #[test] + fn current_thread_runtime_cannot_be_injected() { + let runtime = Arc::new( + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(), + ); + assert_eq!( + Database::with_runtime(runtime).unwrap_err().status, + adbc_core::error::Status::InvalidArguments + ); + } +} diff --git a/adbc/src/driver.rs b/adbc/src/driver.rs new file mode 100644 index 00000000..dac15cdb --- /dev/null +++ b/adbc/src/driver.rs @@ -0,0 +1,41 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use adbc_core::error::Result; +use adbc_core::options::{OptionDatabase, OptionValue}; +use adbc_core::Optionable as _; + +use crate::Database; + +#[derive(Debug, Default)] +pub struct Driver; + +impl adbc_core::Driver for Driver { + type DatabaseType = Database; + + fn new_database(&mut self) -> Result { + Ok(Database::default()) + } + + fn new_database_with_opts( + &mut self, + opts: impl IntoIterator, + ) -> Result { + let mut database = Database::default(); + for (key, value) in opts { + database.set_option(key, value)?; + } + Ok(database) + } +} diff --git a/adbc/src/error.rs b/adbc/src/error.rs new file mode 100644 index 00000000..54cbe4a9 --- /dev/null +++ b/adbc/src/error.rs @@ -0,0 +1,136 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use adbc_core::error::{Error, Status}; +use databricks_sql_kernel as kernel; + +pub(crate) fn adbc_error(message: impl Into, status: Status) -> Error { + Error::with_message_and_status(message, status) +} + +pub(crate) fn unsupported(operation: &str) -> Error { + adbc_error( + format!("{operation} is not implemented by this driver"), + Status::NotImplemented, + ) +} + +pub(crate) fn option_not_found(kind: &str, key: &str) -> Error { + adbc_error( + format!("{kind} option {key} was not found"), + Status::NotFound, + ) +} + +pub(crate) fn map_kernel_error(source: kernel::Error) -> Error { + let status = match source.code { + kernel::ErrorCode::InvalidArgument => Status::InvalidArguments, + kernel::ErrorCode::Unauthenticated => Status::Unauthenticated, + kernel::ErrorCode::PermissionDenied => Status::Unauthorized, + kernel::ErrorCode::NotFound => Status::NotFound, + kernel::ErrorCode::ResourceExhausted + | kernel::ErrorCode::Unavailable + | kernel::ErrorCode::NetworkError => Status::IO, + kernel::ErrorCode::Timeout => Status::Timeout, + kernel::ErrorCode::Cancelled => Status::Cancelled, + kernel::ErrorCode::DataLoss => Status::InvalidData, + kernel::ErrorCode::InvalidStatementHandle => Status::InvalidState, + kernel::ErrorCode::Internal => Status::Internal, + kernel::ErrorCode::SqlError => sql_status(source.sql_state.as_deref()), + _ => Status::Unknown, + }; + let mut mapped = adbc_error(source.message, status); + mapped.vendor_code = source.vendor_code.unwrap_or_default(); + if let Some(sqlstate) = source.sql_state.filter(|value| value.len() == 5) { + for (target, source) in mapped.sqlstate.iter_mut().zip(sqlstate.bytes()) { + *target = source as std::ffi::c_char; + } + } + mapped.details = source + .error_code + .map(|code| vec![("databricks.error_code".to_string(), code.into_bytes())]); + mapped +} + +fn sql_status(sqlstate: Option<&str>) -> Status { + match sqlstate { + Some(state) if state.starts_with("23") => Status::Integrity, + Some("42P01" | "42703" | "42704" | "42S02") => Status::NotFound, + Some("42P07" | "42710" | "42S01") => Status::AlreadyExists, + Some(state) if state.starts_with("22") || state.starts_with("42") => Status::InvalidData, + Some(state) if state.starts_with("25") => Status::InvalidState, + Some(state) if state.starts_with("28") => Status::Unauthenticated, + _ => Status::InvalidData, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn unsupported_operations_use_not_implemented() { + assert_eq!( + unsupported("partitioned execution").status, + Status::NotImplemented + ); + } + + #[test] + fn unknown_option_getters_use_not_found() { + assert_eq!( + option_not_found("statement string", "unknown").status, + Status::NotFound + ); + } + + #[test] + fn kernel_error_preserves_sqlstate_and_vendor_code() { + let mapped = map_kernel_error( + kernel::Error::sql_error() + .message("bad query") + .with_sql_state("42000") + .with_vendor_code(42), + ); + assert_eq!(mapped.status, Status::InvalidData); + assert_eq!(mapped.vendor_code, 42); + assert_eq!( + mapped.sqlstate, + (*b"42000").map(|byte| byte as std::ffi::c_char) + ); + } + + #[test] + fn kernel_error_maps_handle_and_sqlstate_categories() { + let handle = map_kernel_error(kernel::Error::invalid_statement_handle()); + assert_eq!(handle.status, Status::InvalidState); + + for (sqlstate, expected) in [ + ("23505", Status::Integrity), + ("42P01", Status::NotFound), + ("42703", Status::NotFound), + ("42P07", Status::AlreadyExists), + ("42601", Status::InvalidData), + ("25000", Status::InvalidState), + ("28000", Status::Unauthenticated), + ] { + let mapped = map_kernel_error( + kernel::Error::sql_error() + .message("server error") + .with_sql_state(sqlstate), + ); + assert_eq!(mapped.status, expected, "SQLSTATE {sqlstate}"); + } + } +} diff --git a/adbc/src/lib.rs b/adbc/src/lib.rs new file mode 100644 index 00000000..c8fcd3e9 --- /dev/null +++ b/adbc/src/lib.rs @@ -0,0 +1,170 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! ADBC driver for Databricks backed by the Databricks SQL Kernel. + +mod cancellation; +mod config; +mod connection; +mod database; +mod driver; +mod error; +mod reader; +mod runtime; +mod statement; + +pub use connection::Connection; +pub use database::Database; +pub use driver::Driver; +pub use statement::{ + AsyncStatementStatus, Statement, StatementCancellationHandle, SubmittedStatement, +}; + +#[cfg(feature = "ffi")] +unsafe fn initialize_ffi_driver( + version: std::os::raw::c_int, + driver: *mut std::os::raw::c_void, + error: *mut adbc_ffi::FFI_AdbcError, +) -> adbc_core::error::AdbcStatusCode { + let version = adbc_ffi::check_err!(adbc_core::options::AdbcVersion::try_from(version), error); + if !matches!( + version, + adbc_core::options::AdbcVersion::V100 | adbc_core::options::AdbcVersion::V110 + ) { + let error_value = adbc_core::error::Error::with_message_and_status( + format!( + "Unsupported ADBC version: got={version:?} expected one of {:?}", + [ + adbc_core::options::AdbcVersion::V100, + adbc_core::options::AdbcVersion::V110, + ] + ), + adbc_core::error::Status::NotImplemented, + ); + adbc_ffi::check_err!(Err::<(), _>(error_value), error); + } + adbc_ffi::check_not_null!(driver, error); + + let mut ffi_driver = ::ffi_driver(); + // adbc_ffi 0.24 obtains unsynchronized mutable references before calling + // either cancel method. Advertising them would violate Rust aliasing when + // cancellation races an operation, before this driver's thread-safe + // cancellation handles are reached. Null slots select the standard + // NOT_IMPLEMENTED fallbacks. + ffi_driver.ConnectionCancel = None; + ffi_driver.StatementCancel = None; + let size = match version { + adbc_core::options::AdbcVersion::V100 => { + std::mem::offset_of!(adbc_ffi::FFI_AdbcDriver, ErrorGetDetailCount) + } + adbc_core::options::AdbcVersion::V110 => std::mem::size_of::(), + _ => unreachable!("unsupported versions return before driver initialization"), + }; + unsafe { + std::ptr::copy_nonoverlapping( + std::ptr::from_ref(&ffi_driver).cast::(), + driver.cast::(), + size, + ); + } + adbc_core::constants::ADBC_STATUS_OK +} + +/// Initialize the Databricks ADBC 1.0 or 1.1 C driver. +/// +/// # Safety +/// +/// `driver` must point to writable storage for an `FFI_AdbcDriver`. When +/// non-null, `error` must point to writable storage for an `FFI_AdbcError`. +#[cfg(feature = "ffi")] +#[allow(non_snake_case)] +#[unsafe(no_mangle)] +pub unsafe extern "C" fn AdbcDatabricksInit( + version: std::os::raw::c_int, + driver: *mut std::os::raw::c_void, + error: *mut adbc_ffi::FFI_AdbcError, +) -> adbc_core::error::AdbcStatusCode { + unsafe { initialize_ffi_driver(version, driver, error) } +} + +/// Conventional driver-manager alias for [`AdbcDatabricksInit`]. +/// +/// # Safety +/// +/// The pointer requirements are identical to [`AdbcDatabricksInit`]. +#[cfg(feature = "ffi")] +#[allow(non_snake_case)] +#[unsafe(no_mangle)] +pub unsafe extern "C" fn AdbcDriverInit( + version: std::os::raw::c_int, + driver: *mut std::os::raw::c_void, + error: *mut adbc_ffi::FFI_AdbcError, +) -> adbc_core::error::AdbcStatusCode { + unsafe { AdbcDatabricksInit(version, driver, error) } +} + +#[cfg(all(test, feature = "ffi"))] +mod ffi_tests { + use adbc_core::options::AdbcVersion; + + use super::*; + + #[test] + fn ffi_cancel_methods_use_safe_not_implemented_fallbacks() { + for initialize in [AdbcDatabricksInit, AdbcDriverInit] { + let mut driver = adbc_ffi::FFI_AdbcDriver::default(); + let mut error = adbc_ffi::FFI_AdbcError::default(); + let status = unsafe { + initialize( + AdbcVersion::V110.into(), + std::ptr::from_mut(&mut driver).cast(), + &mut error, + ) + }; + assert_eq!(status, adbc_core::constants::ADBC_STATUS_OK); + assert!(driver.ConnectionCancel.is_none()); + assert!(driver.StatementCancel.is_none()); + + let connection_cancel = adbc_ffi::driver_method!(driver, ConnectionCancel); + let mut connection = adbc_ffi::FFI_AdbcConnection::default(); + let status = unsafe { connection_cancel(&mut connection, &mut error) }; + assert_eq!(status, adbc_core::constants::ADBC_STATUS_NOT_IMPLEMENTED); + + let statement_cancel = adbc_ffi::driver_method!(driver, StatementCancel); + let mut statement = adbc_ffi::FFI_AdbcStatement::default(); + let status = unsafe { statement_cancel(&mut statement, &mut error) }; + assert_eq!(status, adbc_core::constants::ADBC_STATUS_NOT_IMPLEMENTED); + } + } + + #[test] + fn ffi_v100_initialization_writes_only_the_v100_prefix() { + const CANARY_SIZE: usize = 32; + let prefix_size = std::mem::offset_of!(adbc_ffi::FFI_AdbcDriver, ErrorGetDetailCount); + for initialize in [AdbcDatabricksInit, AdbcDriverInit] { + let mut storage = vec![0xa5_u8; prefix_size + CANARY_SIZE]; + let mut error = adbc_ffi::FFI_AdbcError::default(); + let status = unsafe { + initialize( + AdbcVersion::V100.into(), + storage.as_mut_ptr().cast(), + &mut error, + ) + }; + assert_eq!(status, adbc_core::constants::ADBC_STATUS_OK); + assert!(storage[..prefix_size].iter().any(|byte| *byte != 0xa5)); + assert!(storage[prefix_size..].iter().all(|byte| *byte == 0xa5)); + } + } +} diff --git a/adbc/src/metadata.rs b/adbc/src/metadata.rs new file mode 100644 index 00000000..ccbf7e32 --- /dev/null +++ b/adbc/src/metadata.rs @@ -0,0 +1,1675 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! ADBC metadata adaptation over the kernel's flat metadata surface. + +use std::collections::{BTreeMap, BTreeSet, HashSet}; +use std::sync::{Arc, Mutex}; + +use adbc_core::error::{Result, Status}; +use adbc_core::options::{InfoCode, ObjectDepth}; +use adbc_core::schemas::{ + COLUMN_SCHEMA, GET_INFO_SCHEMA, GET_OBJECTS_SCHEMA, GET_TABLE_TYPES_SCHEMA, + OBJECTS_DB_SCHEMA_SCHEMA, TABLE_SCHEMA, +}; +use arrow_array::cast::AsArray; +use arrow_array::{ + new_null_array, Array, ArrayRef, BooleanArray, Int16Array, Int32Array, Int64Array, ListArray, + RecordBatch, RecordBatchIterator, RecordBatchReader, StringArray, StructArray, UnionArray, +}; +use arrow_buffer::{NullBuffer, OffsetBuffer, ScalarBuffer}; +use arrow_schema::{DataType, Field, Fields, Schema}; +use databricks_sql_kernel as kernel; + +use crate::error::{adbc_error, map_kernel_error}; +use crate::runtime::RuntimeExt as _; + +type Reader = Box; + +#[derive(Clone, Debug)] +struct TableRow { + catalog: String, + schema: String, + name: String, + table_type: String, +} + +#[derive(Clone, Debug)] +struct ColumnRow { + catalog: String, + schema: String, + table: String, + name: String, + ordinal: Option, + remarks: Option, + data_type: Option, + type_name: Option, + column_size: Option, + decimal_digits: Option, + radix: Option, + nullable: Option, + column_default: Option, + sql_data_type: Option, + datetime_sub: Option, + char_octet_length: Option, + is_nullable: Option, + scope_catalog: Option, + scope_schema: Option, + scope_table: Option, + is_auto_increment: Option, +} + +#[derive(Clone, Debug)] +struct TableNode { + row: TableRow, + columns: Option>, +} + +#[derive(Clone, Debug)] +struct SchemaNode { + name: String, + tables: Option>, +} + +#[derive(Clone, Debug)] +struct CatalogNode { + name: String, + schemas: Option>, +} + +fn invalid(message: impl Into) -> adbc_core::error::Error { + adbc_error(message, Status::InvalidData) +} + +fn reader(schema: Arc, batch: RecordBatch) -> Reader { + Box::new(RecordBatchIterator::new( + vec![Ok(batch)].into_iter(), + schema, + )) +} + +fn batches_reader(schema: Arc, batches: Vec) -> Reader { + Box::new(RecordBatchIterator::new( + batches.into_iter().map(Ok), + schema, + )) +} + +fn drain( + runtime: &tokio::runtime::Runtime, + mut stream: kernel::ResultStream, +) -> Result> { + let mut batches = Vec::new(); + loop { + match runtime + .block_on_safe(stream.next_batch()) + .map_err(map_kernel_error)? + { + Some(kernel::ResultBatch::Arrow(batch)) => batches.push(batch.clone()), + Some(_) => return Err(invalid("kernel metadata returned a non-Arrow batch")), + None => return Ok(batches), + } + } +} + +fn column<'a>(batch: &'a RecordBatch, name: &str) -> Result<&'a ArrayRef> { + let index = batch + .schema() + .index_of(name) + .map_err(|_| invalid(format!("kernel metadata omitted required column {name}")))?; + Ok(batch.column(index)) +} + +fn required_string(batch: &RecordBatch, name: &str, row: usize) -> Result { + optional_string(batch, name, row)? + .ok_or_else(|| invalid(format!("kernel metadata returned null {name}"))) +} + +fn optional_string(batch: &RecordBatch, name: &str, row: usize) -> Result> { + let value = column(batch, name)?; + if value.is_null(row) { + return Ok(None); + } + match value.data_type() { + DataType::Utf8 => Ok(Some(value.as_string::().value(row).to_owned())), + DataType::LargeUtf8 => Ok(Some(value.as_string::().value(row).to_owned())), + other => Err(invalid(format!( + "kernel metadata column {name} is {other}, expected UTF-8" + ))), + } +} + +fn optional_i32(batch: &RecordBatch, name: &str, row: usize) -> Result> { + let value = column(batch, name)?; + if value.is_null(row) { + return Ok(None); + } + value + .as_any() + .downcast_ref::() + .map(|array| Some(array.value(row))) + .ok_or_else(|| invalid(format!("kernel metadata column {name} is not Int32"))) +} + +fn optional_i16(batch: &RecordBatch, name: &str, row: usize) -> Result> { + optional_i32(batch, name, row)? + .map(|value| { + i16::try_from(value) + .map_err(|_| invalid(format!("kernel metadata column {name} overflows Int16"))) + }) + .transpose() +} + +fn optional_yes_no(batch: &RecordBatch, name: &str, row: usize) -> Result> { + Ok(optional_string(batch, name, row)?.and_then(|value| { + match value.to_ascii_lowercase().as_str() { + "yes" | "true" => Some(true), + "no" | "false" => Some(false), + _ => None, + } + })) +} + +fn pattern(value: Option<&str>) -> Result>> { + value + .map(kernel::LikePattern::new) + .transpose() + .map_err(map_kernel_error) +} + +fn identifier(value: Option<&str>) -> Result>> { + value + .map(kernel::Identifier::new) + .transpose() + .map_err(map_kernel_error) +} + +fn escaped_pattern(value: Option<&str>, escape_wildcards: bool) -> Option { + value.map(|value| { + if escape_wildcards { + value + .replace('\\', "\\\\") + .replace('_', "\\_") + .replace('%', "\\%") + } else { + value.to_owned() + } + }) +} + +fn escape_catalog_underscores(value: Option<&str>, enabled: bool) -> Option { + value.map(|value| { + if !enabled { + return value.to_owned(); + } + let mut escaped = String::with_capacity(value.len()); + let mut consecutive_backslashes = 0usize; + for character in value.chars() { + if character == '_' && consecutive_backslashes.is_multiple_of(2) { + escaped.push('\\'); + } + escaped.push(character); + if character == '\\' { + consecutive_backslashes += 1; + } else { + consecutive_backslashes = 0; + } + } + escaped + }) +} + +fn metadata_base_type(type_name: &str) -> String { + let normalized = type_name.trim().to_ascii_uppercase(); + if matches!(normalized.as_str(), "INT" | "INTEGER") { + return "INTEGER".into(); + } + if matches!( + normalized.as_str(), + "TIMESTAMP" | "TIMESTAMP_LTZ" | "TIMESTAMP_NTZ" + ) { + return "TIMESTAMP".into(); + } + if normalized.starts_with("INTERVAL ") { + return "INTERVAL".into(); + } + let end = normalized + .char_indices() + .find(|(_, character)| matches!(character, '<' | '(')) + .map_or(normalized.len(), |(index, _)| index); + normalized[..end].trim().to_owned() +} + +fn table_type_filter(value: Option<&str>) -> Option> { + value + .filter(|value| !value.is_empty()) + .map(|value| value.split(',').collect()) +} + +fn append_base_type(batch: RecordBatch, schema: Arc) -> Result { + let mut column_sizes = Vec::with_capacity(batch.num_rows()); + let mut decimal_digits = Vec::with_capacity(batch.num_rows()); + let mut ordinals = Vec::with_capacity(batch.num_rows()); + let mut values = Vec::with_capacity(batch.num_rows()); + for row in 0..batch.num_rows() { + let type_name = required_string(&batch, "TYPE_NAME", row)?; + let original_size = optional_i32(&batch, "COLUMN_SIZE", row)?.unwrap_or_default(); + let original_scale = optional_i32(&batch, "DECIMAL_DIGITS", row)?.unwrap_or_default(); + let (size, scale) = csharp_precision_scale(&type_name, original_size, original_scale); + column_sizes.push(Some(size)); + decimal_digits.push(Some(scale)); + ordinals.push( + optional_i32(&batch, "ORDINAL_POSITION", row)?.map(|ordinal| ordinal.saturating_sub(1)), + ); + values.push(metadata_base_type(&type_name)); + } + let mut columns = batch.columns().to_vec(); + columns[schema.index_of("COLUMN_SIZE")?] = Arc::new(Int32Array::from(column_sizes)); + columns[schema.index_of("DECIMAL_DIGITS")?] = Arc::new(Int32Array::from(decimal_digits)); + columns[schema.index_of("ORDINAL_POSITION")?] = Arc::new(Int32Array::from(ordinals)); + columns.push(Arc::new(StringArray::from(values))); + RecordBatch::try_new(schema, columns).map_err(Into::into) +} + +fn type_arguments(type_name: &str) -> Option> { + let (_, arguments) = type_name.split_once('(')?; + let arguments = arguments + .split_once(')') + .map_or(arguments, |(value, _)| value); + arguments + .split(',') + .map(|value| value.trim().parse::()) + .collect::, _>>() + .ok() +} + +fn csharp_precision_scale(type_name: &str, original_size: i32, original_scale: i32) -> (i32, i32) { + let base_type = metadata_base_type(type_name); + match base_type.as_str() { + "STRING" | "VARCHAR" | "LONGVARCHAR" | "LONGNVARCHAR" | "NVARCHAR" => ( + type_arguments(type_name) + .and_then(|values| values.first().copied()) + .unwrap_or(i32::MAX), + original_scale, + ), + "CHAR" | "NCHAR" => ( + type_arguments(type_name) + .and_then(|values| values.first().copied()) + .unwrap_or(255), + original_scale, + ), + "DECIMAL" | "NUMERIC" => { + let arguments = type_arguments(type_name).unwrap_or_else(|| vec![10, 0]); + ( + arguments.first().copied().unwrap_or(10), + arguments.get(1).copied().unwrap_or_default(), + ) + } + _ => (original_size, original_scale), + } +} + +fn append_global_temp_schema(batches: &mut Vec, schema: &Arc) -> Result<()> { + for batch in batches.iter() { + for row in 0..batch.num_rows() { + if optional_string(batch, "TABLE_SCHEM", row)?.as_deref() == Some("global_temp") { + return Ok(()); + } + } + } + let columns = schema + .fields() + .iter() + .map(|field| match (field.name().as_str(), field.data_type()) { + ("TABLE_SCHEM", DataType::Utf8) => { + Ok(Arc::new(StringArray::from(vec!["global_temp"])) as ArrayRef) + } + ("TABLE_CATALOG", DataType::Utf8) => { + Ok(Arc::new(StringArray::from(vec![""])) as ArrayRef) + } + ("TABLE_SCHEM", DataType::LargeUtf8) => { + Ok(Arc::new(arrow_array::LargeStringArray::from(vec!["global_temp"])) as ArrayRef) + } + ("TABLE_CATALOG", DataType::LargeUtf8) => { + Ok(Arc::new(arrow_array::LargeStringArray::from(vec![""])) as ArrayRef) + } + (name, data_type) => Err(invalid(format!( + "unexpected GetSchemas field {name} with type {data_type}" + ))), + }) + .collect::>>()?; + batches.push(RecordBatch::try_new(Arc::clone(schema), columns)?); + Ok(()) +} + +fn csharp_key_schema(schema: &Arc) -> Arc { + Arc::new(Schema::new_with_metadata( + schema + .fields() + .iter() + .map(|field| { + if field.name() == "KEY_SEQ" { + Arc::new(field.as_ref().clone().with_name("KEQ_SEQ")) + } else { + Arc::clone(field) + } + }) + .collect::>(), + schema.metadata().clone(), + )) +} + +#[allow(clippy::too_many_arguments)] // Mirrors the C# metadata-statement option surface. +pub(crate) fn execute_statement_command( + metadata: &kernel::Metadata, + runtime: &tokio::runtime::Runtime, + command: &str, + catalog: Option<&str>, + schema: Option<&str>, + table: Option<&str>, + column_name: Option<&str>, + table_types: Option<&str>, + foreign_catalog: Option<&str>, + foreign_schema: Option<&str>, + foreign_table: Option<&str>, + escape_wildcards: bool, + escape_catalog_name: bool, +) -> Result { + let exact_catalog = catalog; + let exact_schema = schema; + let exact_table = table; + let catalog = if escape_wildcards { + escaped_pattern(catalog, true) + } else { + escape_catalog_underscores(catalog, escape_catalog_name) + }; + let schema = escaped_pattern(schema, escape_wildcards); + let table = escaped_pattern(table, escape_wildcards); + let column_name = escaped_pattern(column_name, escape_wildcards); + let table_types = table_type_filter(table_types); + let stream = match command.to_ascii_lowercase().as_str() { + "getcatalogs" => runtime + .block_on_safe(metadata.list_catalogs()) + .map_err(map_kernel_error)?, + "getschemas" => runtime + .block_on_safe( + metadata.list_schemas(identifier(catalog.as_deref())?, pattern(schema.as_deref())?), + ) + .map_err(map_kernel_error)?, + "gettables" => runtime + .block_on_safe(metadata.list_tables( + pattern(catalog.as_deref())?, + pattern(schema.as_deref())?, + pattern(table.as_deref())?, + table_types.as_deref(), + )) + .map_err(map_kernel_error)?, + "getcolumns" => runtime + .block_on_safe(metadata.list_columns( + identifier(catalog.as_deref())?, + pattern(schema.as_deref())?, + pattern(table.as_deref())?, + pattern(column_name.as_deref())?, + )) + .map_err(map_kernel_error)?, + "getprimarykeys" => { + let table = exact_table.ok_or_else(|| { + adbc_error( + "GetPrimaryKeys requires target_table", + Status::InvalidArguments, + ) + })?; + runtime + .block_on_safe(metadata.primary_keys( + identifier(exact_catalog)?, + identifier(exact_schema)?, + kernel::Identifier::new(table).map_err(map_kernel_error)?, + )) + .map_err(map_kernel_error)? + } + "getcrossreference" => runtime + .block_on_safe(metadata.foreign_keys( + identifier(exact_catalog)?, + identifier(exact_schema)?, + identifier(exact_table)?, + identifier(foreign_catalog)?, + identifier(foreign_schema)?, + identifier(foreign_table)?, + )) + .map_err(map_kernel_error)?, + "" => { + return Err(adbc_error( + "metadata command is not set", + Status::InvalidState, + )); + } + _ => { + return Err(adbc_error( + format!("unsupported metadata command {command:?}"), + Status::NotImplemented, + )); + } + }; + let source_schema = stream.schema(); + let batches = drain(runtime, stream)?; + if command.eq_ignore_ascii_case("GetPrimaryKeys") + || command.eq_ignore_ascii_case("GetCrossReference") + { + let output_schema = csharp_key_schema(&source_schema); + let batches = batches + .into_iter() + .map(|batch| { + RecordBatch::try_new(Arc::clone(&output_schema), batch.columns().to_vec()) + .map_err(Into::into) + }) + .collect::>>()?; + return Ok(batches_reader(output_schema, batches)); + } + if command.eq_ignore_ascii_case("GetSchemas") { + let mut batches = batches; + if schema + .as_deref() + .is_none_or(|schema| like_match(schema, "global_temp")) + { + append_global_temp_schema(&mut batches, &source_schema)?; + } + return Ok(batches_reader(source_schema, batches)); + } + if !command.eq_ignore_ascii_case("GetColumns") { + return Ok(batches_reader(source_schema, batches)); + } + + let mut fields = source_schema.fields().iter().cloned().collect::>(); + fields.push(Arc::new(Field::new("BASE_TYPE_NAME", DataType::Utf8, true))); + let output_schema = Arc::new(Schema::new_with_metadata( + fields, + source_schema.metadata().clone(), + )); + let batches = batches + .into_iter() + .map(|batch| append_base_type(batch, Arc::clone(&output_schema))) + .collect::>>()?; + Ok(batches_reader(output_schema, batches)) +} + +fn catalog_schema_hierarchy( + metadata: &kernel::Metadata, + runtime: &tokio::runtime::Runtime, + catalog: Option<&str>, + schema: Option<&str>, +) -> Result>> { + let catalog_stream = runtime + .block_on_safe(metadata.list_catalogs()) + .map_err(map_kernel_error)?; + let mut hierarchy = BTreeMap::new(); + for batch in drain(runtime, catalog_stream)? { + for row in 0..batch.num_rows() { + let catalog_name = required_string(&batch, "TABLE_CAT", row)?; + if !catalog.is_none_or(|value| like_match(value, &catalog_name)) { + continue; + } + let schema_stream = runtime + .block_on_safe(metadata.list_schemas( + Some(kernel::Identifier::new(&catalog_name).map_err(map_kernel_error)?), + pattern(schema)?, + )) + .map_err(map_kernel_error)?; + let mut schemas = BTreeSet::new(); + for schema_batch in drain(runtime, schema_stream)? { + for schema_row in 0..schema_batch.num_rows() { + schemas.insert(required_string(&schema_batch, "TABLE_SCHEM", schema_row)?); + } + } + hierarchy.insert(catalog_name, schemas); + } + } + Ok(hierarchy) +} + +fn initialize_table_hierarchy( + hierarchy: BTreeMap>, +) -> BTreeMap>> { + hierarchy + .into_iter() + .map(|(catalog_name, schemas)| { + ( + catalog_name, + schemas + .into_iter() + .map(|schema_name| (schema_name, Vec::new())) + .collect(), + ) + }) + .collect() +} + +fn union_fields() -> arrow_schema::UnionFields { + match GET_INFO_SCHEMA.field(1).data_type() { + DataType::Union(fields, _) => fields.clone(), + _ => unreachable!("ADBC get-info schema must contain a union"), + } +} + +enum InfoValue { + String(Option), + Bool(bool), + Int64(i64), +} + +fn current_vendor_version( + session: &kernel::Session, + runtime: &tokio::runtime::Runtime, +) -> Result { + let mut statement = session.statement(); + statement.spec().sql("SELECT current_version()"); + let mut executed = runtime + .block_on_safe(statement.execute()) + .map_err(map_kernel_error)?; + let value = match runtime + .block_on_safe(executed.next_batch()) + .map_err(map_kernel_error)? + { + Some(kernel::ResultBatch::Arrow(batch)) + if batch.num_rows() > 0 && batch.num_columns() > 0 => + { + let values = batch.column(0); + current_version_value(values.as_ref())? + } + Some(_) => return Err(invalid("current_version() returned an empty result")), + None => return Err(invalid("current_version() returned no result")), + }; + while runtime + .block_on_safe(executed.next_batch()) + .map_err(map_kernel_error)? + .is_some() + {} + // The server returns JSON. Avoid coupling metadata to a JSON dependency for two optional keys. + for key in ["dbsql_version", "dbr_version"] { + let marker = format!("\"{key}\""); + if let Some(after_key) = value.split_once(&marker).map(|(_, rest)| rest) { + if let Some(after_colon) = after_key.split_once(':').map(|(_, rest)| rest.trim_start()) + { + if let Some(quoted) = after_colon.strip_prefix('"') { + if let Some((version, _)) = quoted.split_once('"') { + if !version.is_empty() { + return Ok(version.to_owned()); + } + } + } + } + } + } + Ok("unknown".to_owned()) +} + +fn current_version_value(values: &dyn Array) -> Result { + match values.data_type() { + DataType::Utf8 => Ok(values.as_string::().value(0).to_owned()), + DataType::LargeUtf8 => Ok(values.as_string::().value(0).to_owned()), + DataType::Struct(_) => { + let values = values + .as_any() + .downcast_ref::() + .ok_or_else(|| invalid("current_version() returned an invalid struct"))?; + for name in ["dbsql_version", "dbr_version"] { + let Some(column) = values.column_by_name(name) else { + continue; + }; + let version = match column.data_type() { + DataType::Utf8 if !column.is_null(0) => { + Some(column.as_string::().value(0)) + } + DataType::LargeUtf8 if !column.is_null(0) => { + Some(column.as_string::().value(0)) + } + _ => None, + }; + if let Some(version) = version.filter(|version| !version.is_empty()) { + return Ok(format!("{{\"{name}\":\"{version}\"}}")); + } + } + Ok("unknown".to_owned()) + } + other => Err(invalid(format!( + "current_version() returned {other}, expected UTF-8 or Struct" + ))), + } +} + +pub(crate) fn get_info( + session: &kernel::Session, + runtime: &tokio::runtime::Runtime, + vendor_version_cache: &Mutex>, + codes: Option>, +) -> Result { + let requested = |code: InfoCode| codes.as_ref().is_none_or(|codes| codes.contains(&code)); + let vendor_version = if requested(InfoCode::VendorVersion) { + let cached = vendor_version_cache + .lock() + .map_err(|_| invalid("vendor-version cache lock is poisoned"))? + .clone(); + if let Some(version) = cached { + Some(version) + } else { + let version = current_vendor_version(session, runtime)?; + *vendor_version_cache + .lock() + .map_err(|_| invalid("vendor-version cache lock is poisoned"))? = + Some(version.clone()); + Some(version) + } + } else { + None + }; + let mut rows = Vec::<(u32, InfoValue)>::new(); + let mut add = |code: InfoCode, value: InfoValue| { + if requested(code) { + rows.push((u32::from(&code), value)); + } + }; + add( + InfoCode::VendorName, + InfoValue::String(Some("Databricks".into())), + ); + if let Some(version) = vendor_version { + add(InfoCode::VendorVersion, InfoValue::String(Some(version))); + } + add( + InfoCode::VendorArrowVersion, + InfoValue::String(Some("59".into())), + ); + add(InfoCode::VendorSql, InfoValue::Bool(true)); + add(InfoCode::VendorSubstrait, InfoValue::Bool(false)); + add(InfoCode::VendorSubstraitMinVersion, InfoValue::String(None)); + add(InfoCode::VendorSubstraitMaxVersion, InfoValue::String(None)); + add( + InfoCode::DriverName, + InfoValue::String(Some("Databricks Rust ADBC Driver".into())), + ); + add( + InfoCode::DriverVersion, + InfoValue::String(Some(env!("CARGO_PKG_VERSION").into())), + ); + add( + InfoCode::DriverArrowVersion, + InfoValue::String(Some("59".into())), + ); + add(InfoCode::DriverAdbcVersion, InfoValue::Int64(1_001_000)); + rows.sort_by_key(|(code, _)| *code); + + build_info(rows) +} + +fn build_info(rows: Vec<(u32, InfoValue)>) -> Result { + let mut names = Vec::with_capacity(rows.len()); + let mut type_ids = Vec::with_capacity(rows.len()); + let mut offsets = Vec::with_capacity(rows.len()); + let mut strings = Vec::new(); + let mut bools = Vec::new(); + let mut ints = Vec::new(); + for (name, value) in rows { + names.push(name); + match value { + InfoValue::String(value) => { + type_ids.push(0); + offsets.push(strings.len() as i32); + strings.push(value); + } + InfoValue::Bool(value) => { + type_ids.push(1); + offsets.push(bools.len() as i32); + bools.push(value); + } + InfoValue::Int64(value) => { + type_ids.push(2); + offsets.push(ints.len() as i32); + ints.push(value); + } + } + } + let fields = union_fields(); + let union = UnionArray::try_new( + union_fields(), + ScalarBuffer::from(type_ids), + Some(ScalarBuffer::from(offsets)), + vec![ + Arc::new(StringArray::from(strings)), + Arc::new(BooleanArray::from(bools)), + Arc::new(Int64Array::from(ints)), + Arc::new(Int32Array::from(Vec::::new())), + new_null_array(fields.iter().nth(4).unwrap().1.data_type(), 0), + new_null_array(fields.iter().nth(5).unwrap().1.data_type(), 0), + ], + ) + .map_err(|error| invalid(format!("failed to build get-info union: {error}")))?; + let batch = RecordBatch::try_new( + GET_INFO_SCHEMA.clone(), + vec![ + Arc::new(arrow_array::UInt32Array::from(names)), + Arc::new(union), + ], + )?; + Ok(reader(GET_INFO_SCHEMA.clone(), batch)) +} + +pub(crate) fn get_table_types( + session: &kernel::Session, + runtime: &tokio::runtime::Runtime, +) -> Result { + let stream = runtime + .block_on_safe(session.metadata().table_types()) + .map_err(map_kernel_error)?; + let mut values = Vec::new(); + for batch in drain(runtime, stream)? { + for row in 0..batch.num_rows() { + values.push(required_string(&batch, "TABLE_TYPE", row)?); + } + } + let batch = RecordBatch::try_new( + GET_TABLE_TYPES_SCHEMA.clone(), + vec![Arc::new(StringArray::from(values))], + )?; + Ok(reader(GET_TABLE_TYPES_SCHEMA.clone(), batch)) +} + +pub(crate) fn get_table_schema( + session: &kernel::Session, + runtime: &tokio::runtime::Runtime, + catalog: Option<&str>, + schema: Option<&str>, + table: &str, +) -> Result { + if catalog == Some("") || schema == Some("") { + return Err(adbc_error("table not found", Status::NotFound)); + } + let stream = runtime + .block_on_safe(session.metadata().list_columns( + identifier(catalog)?, + pattern(schema)?, + pattern(Some(table))?, + None, + )) + .map_err(map_kernel_error)?; + let mut fields = Vec::new(); + let mut has_geospatial_type = false; + for batch in drain(runtime, stream)? { + for row in 0..batch.num_rows() { + if optional_string(&batch, "TABLE_CAT", row)?.as_deref() != catalog && catalog.is_some() + { + continue; + } + if optional_string(&batch, "TABLE_SCHEM", row)?.as_deref() != schema && schema.is_some() + { + continue; + } + if required_string(&batch, "TABLE_NAME", row)? != table { + continue; + } + let name = required_string(&batch, "COLUMN_NAME", row)?; + let type_name = required_string(&batch, "TYPE_NAME", row)?; + let normalized_type = type_name.to_ascii_uppercase(); + has_geospatial_type |= + normalized_type.contains("GEOMETRY") || normalized_type.contains("GEOGRAPHY"); + let nullable = !matches!( + optional_string(&batch, "IS_NULLABLE", row)?.as_deref(), + Some("NO") + ); + let field = Field::new( + name, + kernel::metadata::type_mapping::databricks_type_to_arrow(&type_name), + nullable, + ); + fields.push((optional_i32(&batch, "ORDINAL_POSITION", row)?, field)); + } + } + fields.sort_by_key(|(ordinal, _)| *ordinal); + if fields.is_empty() { + return Err(adbc_error( + format!("table not found: {table}"), + Status::NotFound, + )); + } + if has_geospatial_type { + return query_table_schema(session, runtime, catalog, schema, table); + } + Ok(Schema::new( + fields + .into_iter() + .map(|(_, field)| field) + .collect::>(), + )) +} + +fn query_table_schema( + session: &kernel::Session, + runtime: &tokio::runtime::Runtime, + catalog: Option<&str>, + schema: Option<&str>, + table: &str, +) -> Result { + fn quoted(identifier: &str) -> String { + format!("`{}`", identifier.replace('`', "``")) + } + + let qualified = catalog + .into_iter() + .chain(schema) + .chain(std::iter::once(table)) + .map(quoted) + .collect::>() + .join("."); + let mut statement = session.statement(); + statement + .spec() + .sql(format!("SELECT * FROM {qualified} WHERE 1 = 0")); + let mut executed = runtime + .block_on_safe(statement.execute()) + .map_err(map_kernel_error)?; + let result_schema = executed.schema(); + while runtime + .block_on_safe(executed.next_batch()) + .map_err(map_kernel_error)? + .is_some() + {} + Ok(result_schema.as_ref().clone()) +} + +fn parse_tables(batches: Vec) -> Result> { + let mut rows = Vec::new(); + for batch in batches { + for row in 0..batch.num_rows() { + rows.push(TableRow { + catalog: required_string(&batch, "TABLE_CAT", row)?, + schema: required_string(&batch, "TABLE_SCHEM", row)?, + name: required_string(&batch, "TABLE_NAME", row)?, + table_type: required_string(&batch, "TABLE_TYPE", row)?, + }); + } + } + Ok(rows) +} + +fn normalize_objects_column_metadata( + data_type: Option, + type_name: Option, + sql_data_type: Option, +) -> (Option, Option) { + let type_name = type_name.map(|type_name| { + if type_name.eq_ignore_ascii_case("INT") { + "INTEGER".to_owned() + } else { + type_name + } + }); + (type_name, sql_data_type.or(data_type)) +} + +fn parse_columns(batches: Vec) -> Result> { + let mut rows = Vec::new(); + for batch in batches { + for row in 0..batch.num_rows() { + let data_type = optional_i16(&batch, "DATA_TYPE", row)?; + let (type_name, sql_data_type) = normalize_objects_column_metadata( + data_type, + optional_string(&batch, "TYPE_NAME", row)?, + optional_i16(&batch, "SQL_DATA_TYPE", row)?, + ); + rows.push(ColumnRow { + catalog: required_string(&batch, "TABLE_CAT", row)?, + schema: required_string(&batch, "TABLE_SCHEM", row)?, + table: required_string(&batch, "TABLE_NAME", row)?, + name: required_string(&batch, "COLUMN_NAME", row)?, + ordinal: optional_i32(&batch, "ORDINAL_POSITION", row)?, + remarks: optional_string(&batch, "REMARKS", row)?, + data_type, + type_name, + column_size: optional_i32(&batch, "COLUMN_SIZE", row)?, + decimal_digits: optional_i16(&batch, "DECIMAL_DIGITS", row)?, + radix: optional_i16(&batch, "NUM_PREC_RADIX", row)?, + nullable: optional_i16(&batch, "NULLABLE", row)?, + column_default: optional_string(&batch, "COLUMN_DEF", row)?, + sql_data_type, + datetime_sub: optional_i16(&batch, "SQL_DATETIME_SUB", row)?, + char_octet_length: optional_i32(&batch, "CHAR_OCTET_LENGTH", row)?, + is_nullable: optional_string(&batch, "IS_NULLABLE", row)?, + scope_catalog: optional_string(&batch, "SCOPE_CATALOG", row)?, + scope_schema: optional_string(&batch, "SCOPE_SCHEMA", row)?, + scope_table: optional_string(&batch, "SCOPE_TABLE", row)?, + is_auto_increment: optional_yes_no(&batch, "IS_AUTO_INCREMENT", row)?, + }); + } + } + Ok(rows) +} + +fn like_match(pattern: &str, value: &str) -> bool { + fn inner(pattern: &[char], value: &[char]) -> bool { + match pattern { + [] => value.is_empty(), + ['\\', literal, rest @ ..] => { + !value.is_empty() && value[0] == *literal && inner(rest, &value[1..]) + } + ['%', rest @ ..] => { + inner(rest, value) || (!value.is_empty() && inner(pattern, &value[1..])) + } + ['_', rest @ ..] => !value.is_empty() && inner(rest, &value[1..]), + [literal, rest @ ..] => { + !value.is_empty() && value[0] == *literal && inner(rest, &value[1..]) + } + } + } + inner( + &pattern.chars().collect::>(), + &value.chars().collect::>(), + ) +} + +fn struct_fields(data_type: &DataType) -> Fields { + match data_type { + DataType::Struct(fields) => fields.clone(), + _ => unreachable!(), + } +} + +fn build_columns(tables: &[TableNode]) -> Result { + let columns = tables + .iter() + .flat_map(|table| table.columns.iter().flatten()) + .cloned() + .collect::>(); + let optional_strings = |get: fn(&ColumnRow) -> Option| { + Arc::new(StringArray::from( + columns.iter().map(get).collect::>(), + )) as ArrayRef + }; + let values = vec![ + Arc::new(StringArray::from( + columns.iter().map(|c| c.name.as_str()).collect::>(), + )) as ArrayRef, + Arc::new(Int32Array::from( + columns.iter().map(|c| c.ordinal).collect::>(), + )) as ArrayRef, + optional_strings(|c| c.remarks.clone()), + Arc::new(Int16Array::from( + columns.iter().map(|c| c.data_type).collect::>(), + )) as ArrayRef, + optional_strings(|c| c.type_name.clone()), + Arc::new(Int32Array::from( + columns.iter().map(|c| c.column_size).collect::>(), + )) as ArrayRef, + Arc::new(Int16Array::from( + columns.iter().map(|c| c.decimal_digits).collect::>(), + )) as ArrayRef, + Arc::new(Int16Array::from( + columns.iter().map(|c| c.radix).collect::>(), + )) as ArrayRef, + Arc::new(Int16Array::from( + columns.iter().map(|c| c.nullable).collect::>(), + )) as ArrayRef, + optional_strings(|c| c.column_default.clone()), + Arc::new(Int16Array::from( + columns.iter().map(|c| c.sql_data_type).collect::>(), + )) as ArrayRef, + Arc::new(Int16Array::from( + columns.iter().map(|c| c.datetime_sub).collect::>(), + )) as ArrayRef, + Arc::new(Int32Array::from( + columns + .iter() + .map(|c| c.char_octet_length) + .collect::>(), + )) as ArrayRef, + optional_strings(|c| c.is_nullable.clone()), + optional_strings(|c| c.scope_catalog.clone()), + optional_strings(|c| c.scope_schema.clone()), + optional_strings(|c| c.scope_table.clone()), + Arc::new(BooleanArray::from( + columns + .iter() + .map(|c| c.is_auto_increment) + .collect::>(), + )) as ArrayRef, + Arc::new(BooleanArray::from(vec![None; columns.len()])) as ArrayRef, + ]; + Ok(Arc::new(StructArray::new( + struct_fields(&COLUMN_SCHEMA), + values, + None, + ))) +} + +fn build_objects(catalogs: Vec) -> Result { + let catalog_names = Arc::new(StringArray::from( + catalogs.iter().map(|c| c.name.as_str()).collect::>(), + )) as ArrayRef; + let schemas = catalogs + .iter() + .flat_map(|c| c.schemas.iter().flatten()) + .cloned() + .collect::>(); + let schema_names = Arc::new(StringArray::from( + schemas.iter().map(|s| s.name.as_str()).collect::>(), + )) as ArrayRef; + let tables = schemas + .iter() + .flat_map(|s| s.tables.iter().flatten()) + .cloned() + .collect::>(); + let table_names = Arc::new(StringArray::from( + tables + .iter() + .map(|t| t.row.name.as_str()) + .collect::>(), + )) as ArrayRef; + let table_types = Arc::new(StringArray::from( + tables + .iter() + .map(|t| t.row.table_type.as_str()) + .collect::>(), + )) as ArrayRef; + + let column_values = build_columns(&tables)?; + let column_offsets = OffsetBuffer::from_lengths( + tables + .iter() + .map(|t| t.columns.as_ref().map_or(0, Vec::len)), + ); + let column_nulls = NullBuffer::from( + tables + .iter() + .map(|t| t.columns.is_some()) + .collect::>(), + ); + let column_lists = Arc::new( + ListArray::try_new( + Arc::new(Field::new("item", COLUMN_SCHEMA.clone(), true)), + column_offsets, + column_values, + Some(column_nulls), + ) + .map_err(|e| invalid(e.to_string()))?, + ) as ArrayRef; + // Match the established ADBC driver behavior: GetObjects exposes the + // constraint field but leaves it null. Applications retrieve keys through + // the dedicated primary-key and cross-reference metadata operations. + let constraint_lists = + new_null_array(struct_fields(&TABLE_SCHEMA)[3].data_type(), tables.len()); + let table_struct = Arc::new(StructArray::new( + struct_fields(&TABLE_SCHEMA), + vec![table_names, table_types, column_lists, constraint_lists], + None, + )) as ArrayRef; + let table_offsets = OffsetBuffer::from_lengths( + schemas + .iter() + .map(|s| s.tables.as_ref().map_or(0, Vec::len)), + ); + let table_nulls = NullBuffer::from( + schemas + .iter() + .map(|s| s.tables.is_some()) + .collect::>(), + ); + let table_lists = Arc::new( + ListArray::try_new( + Arc::new(Field::new("item", TABLE_SCHEMA.clone(), true)), + table_offsets, + table_struct, + Some(table_nulls), + ) + .map_err(|e| invalid(e.to_string()))?, + ) as ArrayRef; + let schema_struct = Arc::new(StructArray::new( + struct_fields(&OBJECTS_DB_SCHEMA_SCHEMA), + vec![schema_names, table_lists], + None, + )) as ArrayRef; + let schema_offsets = OffsetBuffer::from_lengths( + catalogs + .iter() + .map(|c| c.schemas.as_ref().map_or(0, Vec::len)), + ); + let schema_nulls = NullBuffer::from( + catalogs + .iter() + .map(|c| c.schemas.is_some()) + .collect::>(), + ); + let schema_lists = Arc::new( + ListArray::try_new( + Arc::new(Field::new("item", OBJECTS_DB_SCHEMA_SCHEMA.clone(), true)), + schema_offsets, + schema_struct, + Some(schema_nulls), + ) + .map_err(|e| invalid(e.to_string()))?, + ) as ArrayRef; + let batch = RecordBatch::try_new( + GET_OBJECTS_SCHEMA.clone(), + vec![catalog_names, schema_lists], + )?; + Ok(reader(GET_OBJECTS_SCHEMA.clone(), batch)) +} + +#[allow(clippy::too_many_arguments)] // Mirrors the ADBC GetObjects filter surface plus kernel context. +pub(crate) fn get_objects( + session: &kernel::Session, + runtime: &tokio::runtime::Runtime, + depth: ObjectDepth, + catalog: Option<&str>, + schema: Option<&str>, + table: Option<&str>, + table_types: Option>, + column_name: Option<&str>, + escape_catalog_name: bool, +) -> Result { + // Databricks identifiers are case-insensitive. Lowercasing search patterns + // before sending metadata requests matches the established connector + // contract while preserving SQL-LIKE wildcards and escapes. + let catalog = escape_catalog_underscores(catalog, escape_catalog_name) + .map(|catalog| catalog.to_lowercase()); + let schema = schema.map(str::to_lowercase); + let table = table.map(str::to_lowercase); + let column_name = column_name.map(str::to_lowercase); + let catalog = catalog.as_deref(); + let schema = schema.as_deref(); + let table = table.as_deref(); + let column_name = column_name.as_deref(); + let metadata = session.metadata(); + if depth == ObjectDepth::Catalogs { + let stream = runtime + .block_on_safe(metadata.list_catalogs()) + .map_err(map_kernel_error)?; + let mut catalogs = Vec::new(); + for batch in drain(runtime, stream)? { + for row in 0..batch.num_rows() { + let name = required_string(&batch, "TABLE_CAT", row)?; + if catalog.is_none_or(|pattern| like_match(pattern, &name)) { + catalogs.push(CatalogNode { + name, + schemas: None, + }); + } + } + } + return build_objects(catalogs); + } + + if depth == ObjectDepth::Schemas { + let catalogs = catalog_schema_hierarchy(&metadata, runtime, catalog, schema)? + .into_iter() + .map(|(name, schemas)| CatalogNode { + name, + schemas: Some( + schemas + .into_iter() + .map(|name| SchemaNode { name, tables: None }) + .collect(), + ), + }) + .collect(); + return build_objects(catalogs); + } + + let hierarchy = catalog_schema_hierarchy(&metadata, runtime, catalog, schema)?; + + let table_stream = runtime + .block_on_safe(metadata.list_tables( + pattern(catalog)?, + pattern(schema)?, + pattern(table)?, + table_types.as_deref(), + )) + .map_err(map_kernel_error)?; + let tables = parse_tables(drain(runtime, table_stream)?)?; + let table_keys = tables + .iter() + .map(|t| (t.catalog.clone(), t.schema.clone(), t.name.clone())) + .collect::>(); + let mut columns_by_table: BTreeMap<(String, String, String), Vec> = BTreeMap::new(); + if matches!(depth, ObjectDepth::All | ObjectDepth::Columns) { + for catalog_name in tables + .iter() + .map(|t| t.catalog.clone()) + .collect::>() + { + let stream = runtime + .block_on_safe(metadata.list_columns( + Some(kernel::Identifier::new(&catalog_name).map_err(map_kernel_error)?), + pattern(schema)?, + pattern(table)?, + pattern(column_name)?, + )) + .map_err(map_kernel_error)?; + for column in parse_columns(drain(runtime, stream)?)? { + let key = ( + column.catalog.clone(), + column.schema.clone(), + column.table.clone(), + ); + if table_keys.contains(&key) { + columns_by_table.entry(key).or_default().push(column); + } + } + } + for columns in columns_by_table.values_mut() { + columns.sort_by_key(|c| c.ordinal); + } + } + + let include_children = matches!(depth, ObjectDepth::All | ObjectDepth::Columns); + let mut grouped = initialize_table_hierarchy(hierarchy); + for table_row in tables { + let key = ( + table_row.catalog.clone(), + table_row.schema.clone(), + table_row.name.clone(), + ); + grouped + .entry(table_row.catalog.clone()) + .or_default() + .entry(table_row.schema.clone()) + .or_default() + .push(TableNode { + row: table_row, + columns: include_children + .then(|| columns_by_table.remove(&key).unwrap_or_default()), + }); + } + let catalogs = grouped + .into_iter() + .map(|(name, schemas)| CatalogNode { + name, + schemas: Some( + schemas + .into_iter() + .map(|(name, tables)| SchemaNode { + name, + tables: Some(tables), + }) + .collect(), + ), + }) + .collect(); + build_objects(catalogs) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn info_uses_exact_adbc_schema_and_filters() { + let rows = vec![ + ( + u32::from(&InfoCode::DriverName), + InfoValue::String(Some("driver".into())), + ), + (u32::from(&InfoCode::VendorSql), InfoValue::Bool(true)), + ]; + let mut reader = build_info(rows).unwrap(); + assert_eq!(reader.schema(), GET_INFO_SCHEMA.clone()); + let batch = reader.next().unwrap().unwrap(); + assert_eq!(batch.num_rows(), 2); + } + + #[test] + fn current_version_accepts_string_and_struct_results() { + let json = StringArray::from(vec![Some(r#"{"dbsql_version":"2026.40"}"#)]); + assert_eq!(current_version_value(&json).unwrap(), json.value(0)); + + let fields = Fields::from(vec![ + Field::new("dbr_version", DataType::Utf8, true), + Field::new("dbsql_version", DataType::Utf8, true), + ]); + let values = StructArray::new( + fields, + vec![ + Arc::new(StringArray::from(vec![None::<&str>])) as ArrayRef, + Arc::new(StringArray::from(vec![Some("2026.40")])) as ArrayRef, + ], + None, + ); + assert_eq!( + current_version_value(&values).unwrap(), + r#"{"dbsql_version":"2026.40"}"# + ); + } + + #[test] + fn like_patterns_support_wildcards_and_escapes() { + assert!(like_match("m%", "main")); + assert!(like_match("m_in", "main")); + assert!(like_match(r"a\_b", "a_b")); + assert!(!like_match(r"a\_b", "axb")); + } + + #[test] + fn table_hierarchy_preserves_matching_parents_without_deeper_matches() { + let hierarchy = BTreeMap::from([ + ("catalog_with_no_schema_match".into(), BTreeSet::new()), + ( + "catalog_with_schema_match".into(), + BTreeSet::from(["schema_with_no_table_match".into()]), + ), + ]); + + let grouped = initialize_table_hierarchy(hierarchy); + assert!(grouped["catalog_with_no_schema_match"].is_empty()); + assert!(grouped["catalog_with_schema_match"]["schema_with_no_table_match"].is_empty()); + } + + #[test] + fn metadata_statement_filters_match_csharp_contract() { + for (input, expected) in [ + ("a_b%", r"a\_b\%"), + (r"a\b", r"a\\b"), + (r"a\_b", r"a\\\_b"), + (r"a\\b", r"a\\\\b"), + ] { + assert_eq!(escaped_pattern(Some(input), false).as_deref(), Some(input)); + assert_eq!( + escaped_pattern(Some(input), true).as_deref(), + Some(expected) + ); + assert!(like_match(expected, input)); + } + assert!(!like_match(r"a\_b\%", "axb-suffix")); + assert!(!like_match(r"a\\b", "axb")); + assert_eq!(table_type_filter(None), None); + assert_eq!(table_type_filter(Some("")), None); + assert_eq!( + table_type_filter(Some("TABLE,VIEW")), + Some(vec!["TABLE", "VIEW"]) + ); + } + + #[test] + fn catalog_underscore_escape_preserves_existing_like_intent() { + for (input, expected) in [ + ("catalog_name", r"catalog\_name"), + (r"catalog\_name", r"catalog\_name"), + ("catalog%name", "catalog%name"), + (r"catalog\name", r"catalog\name"), + (r"catalog\\_name", r"catalog\\\_name"), + (r"catalog\\\_name", r"catalog\\\_name"), + ] { + assert_eq!( + escape_catalog_underscores(Some(input), true).as_deref(), + Some(expected), + "input {input:?}" + ); + assert_eq!( + escape_catalog_underscores(Some(input), false).as_deref(), + Some(input), + "disabled input {input:?}" + ); + } + assert_eq!(escape_catalog_underscores(None, true), None); + } + + #[test] + fn csharp_key_metadata_uses_legacy_sequence_spelling() { + let schema = Arc::new(Schema::new(vec![ + Field::new("TABLE_NAME", DataType::Utf8, true), + Field::new("KEY_SEQ", DataType::Int32, true), + ])); + let schema = csharp_key_schema(&schema); + assert_eq!(schema.field(0).name(), "TABLE_NAME"); + assert_eq!(schema.field(1).name(), "KEQ_SEQ"); + assert_eq!(schema.field(1).data_type(), &DataType::Int32); + } + + #[test] + fn objects_columns_match_csharp_type_metadata() { + assert_eq!( + normalize_objects_column_metadata(Some(4), Some("INT".into()), None), + (Some("INTEGER".into()), Some(4)) + ); + assert_eq!( + normalize_objects_column_metadata(Some(12), Some("STRING".into()), None), + (Some("STRING".into()), Some(12)) + ); + assert_eq!( + normalize_objects_column_metadata(Some(3), Some("DECIMAL(10,2)".into()), Some(3)), + (Some("DECIMAL(10,2)".into()), Some(3)) + ); + } + + #[test] + fn get_columns_extension_appends_canonical_base_type_names() { + let source_schema = Arc::new(Schema::new(vec![ + Field::new("TYPE_NAME", DataType::Utf8, false), + Field::new("COLUMN_SIZE", DataType::Int32, true), + Field::new("DECIMAL_DIGITS", DataType::Int32, true), + Field::new("ORDINAL_POSITION", DataType::Int32, true), + ])); + let batch = RecordBatch::try_new( + Arc::clone(&source_schema), + vec![ + Arc::new(StringArray::from(vec![ + "INT", + "STRING", + "DECIMAL(10,2)", + "CHAR", + "VARCHAR(20)", + "TIMESTAMP_NTZ", + ])), + Arc::new(Int32Array::from(vec![ + Some(4), + None, + None, + None, + None, + None, + ])), + Arc::new(Int32Array::from(vec![ + Some(0), + None, + None, + None, + None, + None, + ])), + Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5, 6])), + ], + ) + .unwrap(); + let mut fields = source_schema.fields().iter().cloned().collect::>(); + fields.push(Arc::new(Field::new("BASE_TYPE_NAME", DataType::Utf8, true))); + let output_schema = Arc::new(Schema::new(fields)); + let output = append_base_type(batch, output_schema).unwrap(); + let values = output + .column(4) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!( + (0..values.len()) + .map(|row| values.value(row)) + .collect::>(), + vec![ + "INTEGER", + "STRING", + "DECIMAL", + "CHAR", + "VARCHAR", + "TIMESTAMP", + ] + ); + assert_eq!( + output + .column(1) + .as_primitive::() + .iter() + .collect::>(), + vec![ + Some(4), + Some(i32::MAX), + Some(10), + Some(255), + Some(20), + Some(0) + ] + ); + assert_eq!( + output + .column(2) + .as_primitive::() + .iter() + .collect::>(), + vec![Some(0), Some(0), Some(2), Some(0), Some(0), Some(0)] + ); + assert_eq!( + output + .column(3) + .as_primitive::() + .iter() + .collect::>(), + vec![Some(0), Some(1), Some(2), Some(3), Some(4), Some(5)] + ); + } + + #[test] + fn get_schemas_extension_appends_global_temp_once() { + let schema = Arc::new(Schema::new(vec![ + Field::new("TABLE_SCHEM", DataType::Utf8, false), + Field::new("TABLE_CATALOG", DataType::Utf8, false), + ])); + let mut batches = vec![RecordBatch::try_new( + Arc::clone(&schema), + vec![ + Arc::new(StringArray::from(vec!["default"])), + Arc::new(StringArray::from(vec!["main"])), + ], + ) + .unwrap()]; + append_global_temp_schema(&mut batches, &schema).unwrap(); + append_global_temp_schema(&mut batches, &schema).unwrap(); + assert_eq!(batches.len(), 2); + assert_eq!( + required_string(&batches[1], "TABLE_SCHEM", 0).unwrap(), + "global_temp" + ); + assert_eq!( + required_string(&batches[1], "TABLE_CATALOG", 0).unwrap(), + "" + ); + } + + #[test] + fn every_objects_depth_has_exact_schema() { + for catalogs in [ + vec![CatalogNode { + name: "main".into(), + schemas: None, + }], + vec![CatalogNode { + name: "main".into(), + schemas: Some(vec![SchemaNode { + name: "default".into(), + tables: None, + }]), + }], + ] { + let reader = build_objects(catalogs).unwrap(); + assert_eq!(reader.schema(), GET_OBJECTS_SCHEMA.clone()); + } + } + + #[test] + fn objects_depth_distinguishes_null_from_empty_lists() { + let table = TableNode { + row: TableRow { + catalog: "main".into(), + schema: "default".into(), + name: "t".into(), + table_type: "TABLE".into(), + }, + columns: Some(Vec::new()), + }; + let cases = [ + (None, None), + (Some(None), None), + (Some(Some(None)), None), + (Some(Some(Some(table))), Some(true)), + ]; + for (hierarchy, columns_valid) in cases { + let schemas = hierarchy.clone().map(|tables| { + vec![SchemaNode { + name: "default".into(), + tables: tables.map(|table| table.into_iter().collect()), + }] + }); + let mut output = build_objects(vec![CatalogNode { + name: "main".into(), + schemas, + }]) + .unwrap(); + let batch = output.next().unwrap().unwrap(); + let schema_lists = batch.column(1).as_list::(); + assert_eq!(schema_lists.is_valid(0), hierarchy.is_some()); + if let Some(tables) = hierarchy { + let schema_structs = schema_lists.values().as_struct(); + let table_lists = schema_structs.column(1).as_list::(); + assert_eq!(table_lists.is_valid(0), tables.is_some()); + if tables.flatten().is_some() { + let table_structs = table_lists.values().as_struct(); + assert_eq!(table_structs.column(2).is_valid(0), columns_valid.unwrap()); + assert!(table_structs.column(3).is_null(0)); + } + } + } + } + + #[test] + fn objects_zero_matches_is_an_empty_batch_with_exact_schema() { + let mut output = build_objects(Vec::new()).unwrap(); + let batch = output.next().unwrap().unwrap(); + assert_eq!(batch.schema(), GET_OBJECTS_SCHEMA.clone()); + assert_eq!(batch.num_rows(), 0); + } + + #[test] + fn objects_leave_constraints_null_for_every_table() { + let tables = ["parent", "child"] + .into_iter() + .map(|name| TableNode { + row: TableRow { + catalog: "main".into(), + schema: "default".into(), + name: name.into(), + table_type: "TABLE".into(), + }, + columns: Some(Vec::new()), + }) + .collect(); + let mut output = build_objects(vec![CatalogNode { + name: "main".into(), + schemas: Some(vec![SchemaNode { + name: "default".into(), + tables: Some(tables), + }]), + }]) + .unwrap(); + let batch = output.next().unwrap().unwrap(); + let schema_lists = batch.column(1).as_list::(); + let schema_structs = schema_lists.values().as_struct(); + let table_lists = schema_structs.column(1).as_list::(); + let table_structs = table_lists.values().as_struct(); + let constraints = table_structs.column(3); + assert_eq!(constraints.len(), 2); + assert_eq!(constraints.null_count(), 2); + } +} diff --git a/adbc/src/reader.rs b/adbc/src/reader.rs new file mode 100644 index 00000000..d4288904 --- /dev/null +++ b/adbc/src/reader.rs @@ -0,0 +1,803 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use adbc_core::error::{Result, Status}; +use arrow_array::{RecordBatch, RecordBatchReader}; +use arrow_schema::{ArrowError, DataType, Schema, SchemaRef}; +use databricks_sql_kernel as kernel; +use databricks_sql_kernel::ExecutedStatementHandle as _; + +use crate::cancellation::OperationGuard; +use crate::error::adbc_error; +use crate::runtime::{RuntimeExt as _, RuntimeHandle}; +use crate::statement::{execute_bound_row, ParameterStyle}; + +pub(crate) struct BoundRows { + source: BoundSource, + current: Option, + row: usize, +} + +pub(crate) struct SlicingReader { + inner: Box, + schema: SchemaRef, + max_rows: usize, + current: Option, + offset: usize, +} + +impl SlicingReader { + pub(crate) fn new(inner: Box, max_rows: usize) -> Self { + let schema = inner.schema(); + Self { + inner, + schema, + max_rows, + current: None, + offset: 0, + } + } +} + +impl Iterator for SlicingReader { + type Item = std::result::Result; + + fn next(&mut self) -> Option { + if let Some(batch) = &self.current { + if self.offset < batch.num_rows() { + let length = self.max_rows.min(batch.num_rows() - self.offset); + let slice = batch.slice(self.offset, length); + self.offset += length; + return Some(Ok(slice)); + } + } + self.current = match self.inner.next()? { + Ok(batch) => Some(batch), + Err(error) => return Some(Err(error)), + }; + self.offset = 0; + let batch = self.current.as_ref().expect("batch was just installed"); + if batch.num_rows() == 0 { + let empty = batch.clone(); + self.current = None; + return Some(Ok(empty)); + } + self.next() + } +} + +impl RecordBatchReader for SlicingReader { + fn schema(&self) -> SchemaRef { + Arc::clone(&self.schema) + } +} + +enum BoundSource { + Batch(Option), + Stream(Box), +} + +impl BoundRows { + pub(crate) fn from_batch(batch: RecordBatch) -> Self { + Self { + source: BoundSource::Batch(Some(batch)), + current: None, + row: 0, + } + } + + pub(crate) fn from_stream(reader: Box) -> Self { + Self { + source: BoundSource::Stream(reader), + current: None, + row: 0, + } + } + + pub(crate) fn next_row(&mut self) -> Result> { + loop { + if let Some(batch) = &self.current { + if self.row < batch.num_rows() { + let row = batch.slice(self.row, 1); + self.row += 1; + return Ok(Some(row)); + } + } + self.current = match &mut self.source { + BoundSource::Batch(batch) => batch.take(), + BoundSource::Stream(reader) => reader.next().transpose().map_err(|source| { + adbc_error( + format!("failed to read bound Arrow stream: {source}"), + Status::InvalidData, + ) + })?, + }; + self.row = 0; + if self.current.is_none() { + return Ok(None); + } + } + } +} + +pub(crate) struct KernelReader { + connection_operation: Option, + executed: kernel::ExecutedStatement, + // The executed handle must drop first so it can schedule cleanup while + // the final runtime owner is still alive. + runtime: Arc, + schema: SchemaRef, + lifecycle: ResultLifecycle, +} + +pub(crate) struct AsyncKernelReader { + connection_operation: Option, + executed: kernel::ExecutedAsyncStatement, + stream: kernel::ResultStream, + runtime: Arc, + schema: SchemaRef, + lifecycle: ResultLifecycle, +} + +fn is_native_geospatial_field(field: &arrow_schema::Field) -> bool { + let DataType::Struct(children) = field.data_type() else { + return false; + }; + children.iter().any(|child| { + child.name() == "wkb" + && (child + .metadata() + .get("geometry") + .is_some_and(|value| value == "true") + || child + .metadata() + .get("geography") + .is_some_and(|value| value == "true")) + }) +} + +fn normalize_result_schema(schema: SchemaRef) -> SchemaRef { + let mut changed = false; + let fields = schema + .fields() + .iter() + .map(|field| { + if is_native_geospatial_field(field) && !field.is_nullable() { + changed = true; + Arc::new(field.as_ref().clone().with_nullable(true)) + } else { + Arc::clone(field) + } + }) + .collect::>(); + if changed { + Arc::new(Schema::new_with_metadata(fields, schema.metadata().clone())) + } else { + schema + } +} + +fn normalize_result_batch( + batch: &RecordBatch, + expected_schema: &SchemaRef, +) -> std::result::Result { + let normalized_batch_schema = normalize_result_schema(batch.schema()); + if normalized_batch_schema != *expected_schema { + return Err(ArrowError::SchemaError( + "kernel result batch schema differs from the advertised result schema".into(), + )); + } + if batch.schema() == *expected_schema { + return Ok(batch.clone()); + } + RecordBatch::try_new(Arc::clone(expected_schema), batch.columns().to_vec()) +} + +struct ResultLifecycle { + generation: Arc, + expected_generation: u64, + done: bool, +} + +impl ResultLifecycle { + fn new(generation: Arc, expected_generation: u64) -> Self { + Self { + generation, + expected_generation, + done: false, + } + } + + fn invalidated(&self) -> bool { + self.generation.load(Ordering::Acquire) != self.expected_generation + } + + fn should_cancel_on_drop(&self) -> bool { + !self.done + } + + fn release(&mut self) -> bool { + let should_cancel = self.should_cancel_on_drop(); + self.done = true; + should_cancel + } +} + +impl KernelReader { + pub(crate) fn new( + runtime: Arc, + executed: kernel::ExecutedStatement, + generation: Arc, + expected_generation: u64, + connection_operation: OperationGuard, + ) -> Self { + let schema = normalize_result_schema(executed.schema()); + Self { + connection_operation: Some(connection_operation), + executed, + runtime, + schema, + lifecycle: ResultLifecycle::new(generation, expected_generation), + } + } + + fn close(&mut self) { + // ExecutedStatement::Drop retries a failed close, so the explicit + // close here provides deterministic cleanup without losing the + // kernel's best-effort backstop. + let _ = self.runtime.block_on_safe(self.executed.close()); + } + + fn cancel_and_close(&mut self) { + let _ = self.runtime.block_on_safe(self.executed.cancel()); + self.close(); + } + + fn finish(&mut self) { + self.lifecycle.done = true; + self.connection_operation = None; + } +} + +impl Iterator for KernelReader { + type Item = std::result::Result; + + fn next(&mut self) -> Option { + if self.lifecycle.done { + return None; + } + if self + .connection_operation + .as_ref() + .is_some_and(OperationGuard::is_cancelled) + { + self.finish(); + self.close(); + return Some(Err(ArrowError::ComputeError( + "operation was cancelled".into(), + ))); + } + if self.lifecycle.invalidated() { + self.finish(); + self.cancel_and_close(); + return Some(Err(ArrowError::ComputeError( + "statement was reused while its result was being consumed".into(), + ))); + } + match self.runtime.block_on_safe(self.executed.next_batch()) { + Ok(Some(kernel::ResultBatch::Arrow(batch))) => { + match normalize_result_batch(batch, &self.schema) { + Ok(batch) => Some(Ok(batch)), + Err(error) => { + self.finish(); + self.close(); + Some(Err(error)) + } + } + } + Ok(Some(_)) => { + self.finish(); + self.close(); + Some(Err(ArrowError::NotYetImplemented( + "kernel returned an unsupported result format".to_string(), + ))) + } + Ok(None) => { + self.finish(); + self.close(); + None + } + Err(source) => { + self.finish(); + self.close(); + Some(Err(ArrowError::ExternalError(Box::new(source)))) + } + } + } +} + +impl Drop for KernelReader { + fn drop(&mut self) { + if self.lifecycle.release() { + self.cancel_and_close(); + } + self.connection_operation = None; + } +} + +impl RecordBatchReader for KernelReader { + fn schema(&self) -> SchemaRef { + Arc::clone(&self.schema) + } +} + +impl AsyncKernelReader { + pub(crate) fn new( + runtime: Arc, + executed: kernel::ExecutedAsyncStatement, + stream: kernel::ResultStream, + generation: Arc, + expected_generation: u64, + connection_operation: OperationGuard, + ) -> Self { + let schema = normalize_result_schema(stream.schema()); + Self { + connection_operation: Some(connection_operation), + executed, + stream, + runtime, + schema, + lifecycle: ResultLifecycle::new(generation, expected_generation), + } + } + + fn finish(&mut self) { + self.lifecycle.done = true; + self.connection_operation = None; + } + + fn close(&mut self) { + let _ = self.runtime.block_on_safe(self.executed.close()); + } + + fn cancel_and_close(&mut self) { + let _ = self.runtime.block_on_safe(self.executed.cancel()); + self.close(); + } +} + +impl Iterator for AsyncKernelReader { + type Item = std::result::Result; + + fn next(&mut self) -> Option { + if self.lifecycle.done { + return None; + } + if self + .connection_operation + .as_ref() + .is_some_and(OperationGuard::is_cancelled) + { + self.finish(); + self.close(); + return Some(Err(ArrowError::ComputeError( + "operation was cancelled".into(), + ))); + } + if self.lifecycle.invalidated() { + self.finish(); + self.cancel_and_close(); + return Some(Err(ArrowError::ComputeError( + "statement was reused while its result was being consumed".into(), + ))); + } + match self.runtime.block_on_safe(self.stream.next_batch()) { + Ok(Some(kernel::ResultBatch::Arrow(batch))) => { + match normalize_result_batch(batch, &self.schema) { + Ok(batch) => Some(Ok(batch)), + Err(error) => { + self.finish(); + self.close(); + Some(Err(error)) + } + } + } + Ok(Some(_)) => { + self.finish(); + self.close(); + Some(Err(ArrowError::NotYetImplemented( + "kernel returned an unsupported result format".to_string(), + ))) + } + Ok(None) => { + self.finish(); + self.close(); + None + } + Err(source) => { + self.finish(); + self.close(); + Some(Err(ArrowError::ExternalError(Box::new(source)))) + } + } + } +} + +impl Drop for AsyncKernelReader { + fn drop(&mut self) { + if self.lifecycle.release() { + self.cancel_and_close(); + } + self.connection_operation = None; + } +} + +impl RecordBatchReader for AsyncKernelReader { + fn schema(&self) -> SchemaRef { + Arc::clone(&self.schema) + } +} + +pub(crate) struct SequenceReader { + connection_operation: Option, + inner: Arc>, + runtime: Arc, + lifecycle: ResultLifecycle, + base_spec: kernel::StatementSpec, + parameter_style: ParameterStyle, + client_timeout: Option, + rows: BoundRows, + current: Option, + schema: SchemaRef, +} + +impl SequenceReader { + #[allow(clippy::too_many_arguments)] + pub(crate) fn new( + inner: Arc>, + runtime: Arc, + generation: Arc, + expected_generation: u64, + base_spec: kernel::StatementSpec, + parameter_style: ParameterStyle, + client_timeout: Option, + rows: BoundRows, + executed: kernel::ExecutedStatement, + connection_operation: OperationGuard, + ) -> Self { + let schema = normalize_result_schema(executed.schema()); + Self { + connection_operation: Some(connection_operation), + inner, + runtime, + lifecycle: ResultLifecycle::new(generation, expected_generation), + base_spec, + parameter_style, + client_timeout, + rows, + current: Some(executed), + schema, + } + } + + fn close_current(&mut self) { + if let Some(executed) = &mut self.current { + let _ = self.runtime.block_on_safe(executed.close()); + } + self.current = None; + } + + fn cancel_and_close_current(&mut self) { + if let Some(executed) = &self.current { + let _ = self.runtime.block_on_safe(executed.cancel()); + } + self.close_current(); + } + + fn fail(&mut self, error: ArrowError) -> Option> { + self.lifecycle.done = true; + self.close_current(); + self.connection_operation = None; + Some(Err(error)) + } +} + +impl Iterator for SequenceReader { + type Item = std::result::Result; + + fn next(&mut self) -> Option { + if self.lifecycle.done { + return None; + } + if self + .connection_operation + .as_ref() + .is_some_and(OperationGuard::is_cancelled) + { + self.lifecycle.done = true; + self.cancel_and_close_current(); + self.connection_operation = None; + return Some(Err(ArrowError::ComputeError( + "operation was cancelled".into(), + ))); + } + if self.lifecycle.invalidated() { + self.lifecycle.done = true; + self.cancel_and_close_current(); + self.connection_operation = None; + return Some(Err(ArrowError::ComputeError( + "statement was reused while its result was being consumed".into(), + ))); + } + + loop { + if let Some(executed) = &mut self.current { + match self.runtime.block_on_safe(executed.next_batch()) { + Ok(Some(kernel::ResultBatch::Arrow(batch))) => { + return match normalize_result_batch(batch, &self.schema) { + Ok(batch) => Some(Ok(batch)), + Err(error) => self.fail(error), + }; + } + Ok(Some(_)) => { + return self.fail(ArrowError::NotYetImplemented( + "kernel returned an unsupported result format".into(), + )); + } + Ok(None) => self.close_current(), + Err(source) => { + return self.fail(ArrowError::ExternalError(Box::new(source))); + } + } + } + + let row = match self.rows.next_row() { + Ok(Some(row)) => row, + Ok(None) => { + self.lifecycle.done = true; + self.connection_operation = None; + return None; + } + Err(source) => return self.fail(ArrowError::ExternalError(Box::new(source))), + }; + let executed = match execute_bound_row( + &self.inner, + &self.runtime, + &self.base_spec, + &row, + self.parameter_style, + self.client_timeout, + ) { + Ok(executed) => executed, + Err(source) => return self.fail(ArrowError::ExternalError(Box::new(source))), + }; + if normalize_result_schema(executed.schema()) != self.schema { + let executed = executed; + let _ = self.runtime.block_on_safe(executed.close()); + return self.fail(ArrowError::SchemaError( + "parameter executions returned inconsistent schemas".into(), + )); + } + self.current = Some(executed); + } + } +} + +impl RecordBatchReader for SequenceReader { + fn schema(&self) -> SchemaRef { + Arc::clone(&self.schema) + } +} + +impl Drop for SequenceReader { + fn drop(&mut self) { + if self.lifecycle.release() { + self.cancel_and_close_current(); + } else { + self.close_current(); + } + self.connection_operation = None; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_array::{BinaryArray, Int32Array, Int64Array, StructArray}; + use arrow_schema::{DataType, Field, Schema}; + use std::collections::HashMap; + use std::collections::VecDeque; + + struct SyntheticReader { + schema: SchemaRef, + batches: VecDeque>, + } + + impl Iterator for SyntheticReader { + type Item = std::result::Result; + + fn next(&mut self) -> Option { + self.batches.pop_front() + } + } + + impl RecordBatchReader for SyntheticReader { + fn schema(&self) -> SchemaRef { + Arc::clone(&self.schema) + } + } + + fn int_batch(values: Vec) -> RecordBatch { + let schema = Arc::new(Schema::new(vec![Field::new( + "value", + DataType::Int64, + false, + )])); + RecordBatch::try_new(schema, vec![Arc::new(Int64Array::from(values))]).unwrap() + } + + #[test] + fn slicing_reader_preserves_empty_batches_and_continues() { + let schema = int_batch(vec![]).schema(); + let inner = SyntheticReader { + schema, + batches: VecDeque::from([ + Ok(int_batch(vec![])), + Ok(int_batch(vec![])), + Ok(int_batch(vec![1, 2, 3])), + ]), + }; + let mut reader = SlicingReader::new(Box::new(inner), 2); + assert_eq!(reader.next().unwrap().unwrap().num_rows(), 0); + assert_eq!(reader.next().unwrap().unwrap().num_rows(), 0); + assert_eq!(reader.next().unwrap().unwrap().num_rows(), 2); + assert_eq!(reader.next().unwrap().unwrap().num_rows(), 1); + assert!(reader.next().is_none()); + } + + #[test] + fn slicing_reader_propagates_lazy_fetch_errors() { + let schema = int_batch(vec![]).schema(); + let inner = SyntheticReader { + schema, + batches: VecDeque::from([ + Ok(int_batch(vec![1, 2])), + Err(ArrowError::ComputeError("injected fetch failure".into())), + ]), + }; + let mut reader = SlicingReader::new(Box::new(inner), 1); + assert_eq!(reader.next().unwrap().unwrap().num_rows(), 1); + assert_eq!(reader.next().unwrap().unwrap().num_rows(), 1); + assert!(reader + .next() + .unwrap() + .unwrap_err() + .to_string() + .contains("injected fetch failure")); + } + + #[test] + fn bound_rows_slices_every_row_in_order() { + let schema = Arc::new(Schema::new(vec![Field::new( + "value", + DataType::Int64, + false, + )])); + let batch = + RecordBatch::try_new(schema, vec![Arc::new(Int64Array::from(vec![10, 20, 30]))]) + .unwrap(); + let mut rows = BoundRows::from_batch(batch); + for expected in [10, 20, 30] { + let row = rows.next_row().unwrap().unwrap(); + assert_eq!(row.num_rows(), 1); + let values = row.column(0).as_any().downcast_ref::().unwrap(); + assert_eq!(values.value(0), expected); + } + assert!(rows.next_row().unwrap().is_none()); + } + + #[test] + fn native_geospatial_schema_is_conservatively_nullable_across_delivery_paths() { + let children = vec![ + Arc::new(Field::new("srid", DataType::Int32, false)), + Arc::new( + Field::new("wkb", DataType::Binary, false) + .with_metadata(HashMap::from([("geometry".into(), "true".into())])), + ), + ]; + let schema = Arc::new(Schema::new(vec![Field::new( + "geom", + DataType::Struct(children.clone().into()), + false, + )])); + let values = StructArray::new( + children.into(), + vec![ + Arc::new(Int32Array::from(vec![4326])), + Arc::new(BinaryArray::from(vec![Some(&[1_u8, 2][..])])), + ], + None, + ); + let batch = RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(values)]).unwrap(); + + let normalized_schema = normalize_result_schema(schema); + assert!(normalized_schema.field(0).is_nullable()); + let normalized_batch = normalize_result_batch(&batch, &normalized_schema).unwrap(); + assert_eq!(normalized_batch.schema(), normalized_schema); + assert_eq!(normalized_batch.num_rows(), 1); + } + + #[test] + fn ordinary_result_schema_is_not_rewritten() { + let schema = Arc::new(Schema::new(vec![Field::new( + "value", + DataType::Int64, + false, + )])); + assert!(Arc::ptr_eq( + &schema, + &normalize_result_schema(Arc::clone(&schema)) + )); + } + + #[test] + fn result_batch_with_unexpected_schema_is_rejected() { + let advertised_schema = Arc::new(Schema::new(vec![Field::new( + "value", + DataType::Int64, + false, + )])); + let batch_schema = Arc::new(Schema::new(vec![Field::new( + "different_value", + DataType::Int64, + false, + )])); + let batch = + RecordBatch::try_new(batch_schema, vec![Arc::new(Int64Array::from(vec![1]))]).unwrap(); + + let error = normalize_result_batch(&batch, &advertised_schema).unwrap_err(); + assert!(matches!(error, ArrowError::SchemaError(_))); + } + + #[test] + fn result_lifecycle_observes_statement_reuse() { + let generation = Arc::new(AtomicU64::new(7)); + let lifecycle = ResultLifecycle::new(Arc::clone(&generation), 7); + assert!(!lifecycle.invalidated()); + + generation.fetch_add(1, Ordering::AcqRel); + + assert!(lifecycle.invalidated()); + } + + #[test] + fn result_lifecycle_cancels_incomplete_release_exactly_once() { + let generation = Arc::new(AtomicU64::new(0)); + let mut lifecycle = ResultLifecycle::new(generation, 0); + assert!(lifecycle.release()); + assert!(!lifecycle.release()); + } + + #[test] + fn result_lifecycle_does_not_cancel_fully_consumed_release() { + let generation = Arc::new(AtomicU64::new(0)); + let mut lifecycle = ResultLifecycle::new(generation, 0); + lifecycle.done = true; + assert!(!lifecycle.release()); + } +} diff --git a/adbc/src/runtime.rs b/adbc/src/runtime.rs new file mode 100644 index 00000000..f8f579c5 --- /dev/null +++ b/adbc/src/runtime.rs @@ -0,0 +1,183 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::future::Future; +use std::ops::Deref; +use std::panic::resume_unwind; +use std::sync::Arc; + +use tokio::runtime::{Handle, Runtime, RuntimeFlavor}; + +pub(crate) const DEFAULT_WORKER_THREADS: usize = 2; + +/// A Tokio runtime used by the synchronous ADBC surface. +/// +/// Driver-owned runtimes are shut down in the background so the last ADBC +/// handle can safely be dropped from within an asynchronous context. Injected +/// runtimes remain owned and managed by their caller. +#[derive(Debug)] +pub(crate) enum RuntimeHandle { + Owned(Option), + Injected(Arc), +} + +impl RuntimeHandle { + pub(crate) fn create() -> std::io::Result> { + tokio::runtime::Builder::new_multi_thread() + .worker_threads(DEFAULT_WORKER_THREADS) + .enable_all() + .build() + .map(|runtime| Arc::new(Self::Owned(Some(runtime)))) + } + + pub(crate) fn injected(runtime: Arc) -> Arc { + Arc::new(Self::Injected(runtime)) + } +} + +impl Deref for RuntimeHandle { + type Target = Runtime; + + fn deref(&self) -> &Self::Target { + match self { + Self::Owned(Some(runtime)) => runtime, + Self::Owned(None) => unreachable!("owned runtime is only taken during drop"), + Self::Injected(runtime) => runtime, + } + } +} + +impl Drop for RuntimeHandle { + fn drop(&mut self) { + if let Self::Owned(runtime) = self { + if let Some(runtime) = runtime.take() { + runtime.shutdown_background(); + } + } + } +} + +pub(crate) trait RuntimeExt { + fn block_on_safe(&self, future: F) -> F::Output + where + F: Future + Send, + F::Output: Send; +} + +impl RuntimeExt for Runtime { + fn block_on_safe(&self, future: F) -> F::Output + where + F: Future + Send, + F::Output: Send, + { + match Handle::try_current().map(|handle| handle.runtime_flavor()) { + Ok(RuntimeFlavor::MultiThread) => tokio::task::block_in_place(|| self.block_on(future)), + Ok(RuntimeFlavor::CurrentThread) => { + std::thread::scope(|scope| match scope.spawn(|| self.block_on(future)).join() { + Ok(output) => output, + Err(cause) => resume_unwind(cause), + }) + } + _ => self.block_on(future), + } + } +} + +impl RuntimeExt for RuntimeHandle { + fn block_on_safe(&self, future: F) -> F::Output + where + F: Future + Send, + F::Output: Send, + { + self.deref().block_on_safe(future) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn private_runtime() -> Runtime { + tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .unwrap() + } + + #[test] + fn blocks_outside_tokio() { + assert_eq!(private_runtime().block_on_safe(async { 42 }), 42); + } + + #[test] + fn blocks_inside_multithread_tokio() { + let private = private_runtime(); + let caller = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .unwrap(); + assert_eq!( + caller.block_on(async { private.block_on_safe(async { 42 }) }), + 42 + ); + } + + #[test] + fn blocks_inside_current_thread_tokio() { + let private = private_runtime(); + let caller = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + assert_eq!( + caller.block_on(async { private.block_on_safe(async { 42 }) }), + 42 + ); + } + + #[test] + fn owned_runtime_drops_inside_multithread_tokio() { + let caller = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .unwrap(); + caller.block_on(async { drop(RuntimeHandle::create().unwrap()) }); + } + + #[test] + fn owned_runtime_drops_inside_current_thread_tokio() { + let caller = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + caller.block_on(async { drop(RuntimeHandle::create().unwrap()) }); + } + + #[test] + fn injected_runtime_is_not_shut_down_by_handle() { + let runtime = Arc::new(private_runtime()); + drop(RuntimeHandle::injected(Arc::clone(&runtime))); + assert_eq!(runtime.block_on(async { 42 }), 42); + } + + #[test] + fn injected_runtime_can_be_used_from_within_itself() { + let runtime = Arc::new(private_runtime()); + let handle = RuntimeHandle::injected(Arc::clone(&runtime)); + assert_eq!( + runtime.block_on(async { handle.block_on_safe(async { 42 }) }), + 42 + ); + } +} diff --git a/adbc/src/statement.rs b/adbc/src/statement.rs new file mode 100644 index 00000000..1a6b5899 --- /dev/null +++ b/adbc/src/statement.rs @@ -0,0 +1,1687 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::collections::HashSet; +use std::future::Future; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::Duration; + +use adbc_core::error::{Result, Status}; +use adbc_core::options::{OptionStatement, OptionValue}; +use arrow_array::{RecordBatch, RecordBatchReader}; +use arrow_schema::{DataType, Field, Schema}; +use databricks_sql_kernel as kernel; +use databricks_sql_kernel::ExecutedStatementHandle as _; +use tokio::sync::Notify; + +use crate::cancellation::{CancellationRegistry, OperationGuard}; +use crate::connection::metadata; +use crate::error::{adbc_error, map_kernel_error, option_not_found, unsupported}; +use crate::reader::{AsyncKernelReader, BoundRows, KernelReader, SequenceReader, SlicingReader}; +use crate::runtime::{RuntimeExt as _, RuntimeHandle}; + +const PARAMETER_STYLE_OPTION: &str = "adbc.databricks.statement.parameter_style"; +const QUERY_TAGS_OPTION: &str = "adbc.databricks.statement.query_tags"; +const CLIENT_TIMEOUT_OPTION: &str = "adbc.databricks.statement.client_timeout_ms"; +const QUERY_TIMEOUT_OPTION: &str = "adbc.apache.statement.query_timeout_s"; +const ENABLE_DIRECT_RESULTS_OPTION: &str = "adbc.databricks.enable_direct_results"; +const ROW_LIMIT_OPTION: &str = "adbc.databricks.statement.row_limit"; +const ROWS_FETCHED_PER_BLOCK_OPTION: &str = "adbc.databricks.statement.rows_fetched_per_block"; +const SERVER_TIMEOUT_OPTION: &str = "adbc.databricks.statement.timeout_seconds"; +const STATEMENT_CONF_PREFIX: &str = "adbc.databricks.statement.conf."; +const IS_METADATA_COMMAND_OPTION: &str = "adbc.apache.statement.is_metadata_command"; +const METADATA_CATALOG_OPTION: &str = "adbc.get_metadata.target_catalog"; +const METADATA_SCHEMA_OPTION: &str = "adbc.get_metadata.target_db_schema"; +const METADATA_TABLE_OPTION: &str = "adbc.get_metadata.target_table"; +const METADATA_TABLE_TYPES_OPTION: &str = "adbc.get_metadata.target_table_types"; +const METADATA_COLUMN_OPTION: &str = "adbc.get_metadata.target_column"; +const METADATA_FOREIGN_CATALOG_OPTION: &str = "adbc.get_metadata.foreign_target_catalog"; +const METADATA_FOREIGN_SCHEMA_OPTION: &str = "adbc.get_metadata.foreign_target_db_schema"; +const METADATA_FOREIGN_TABLE_OPTION: &str = "adbc.get_metadata.foreign_target_table"; +const METADATA_ESCAPE_WILDCARDS_OPTION: &str = "adbc.get_metadata.escape_pattern_wildcards"; + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub(crate) enum ParameterStyle { + #[default] + Positional, + Named, +} + +#[derive(Debug, Clone)] +struct BoundParameter { + name: Option, + param_type: String, + value: Option, + binary: bool, +} + +pub struct Statement { + inner: Arc>, + metadata: kernel::Metadata, + canceller: kernel::StatementCanceller, + runtime: Arc, + binding: Option, + parameter_style: ParameterStyle, + prepared: bool, + client_timeout: Option, + enable_direct_results: bool, + rows_fetched_per_block: Option, + generation: Arc, + current_cancellation: Arc, + blocking_execute: Arc, + cancellation_notify: Arc, + connection_cancellation: Arc, + metadata_options: MetadataCommandOptions, +} + +#[derive(Debug, Default)] +struct MetadataCommandOptions { + enabled: bool, + catalog: Option, + schema: Option, + table: Option, + table_types: Option, + column: Option, + foreign_catalog: Option, + foreign_schema: Option, + foreign_table: Option, + escape_wildcards: bool, + escape_catalog_name: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +/// State observed for a non-blocking Databricks statement. +pub enum AsyncStatementStatus { + /// Accepted but not yet executing. + Pending, + /// Currently executing. + Running, + /// Completed with a result available for fetching. + Succeeded, + /// Completed and already closed by the server. + Closed, + /// Completed with a server error. + Failed, + /// Cancelled before completion. + Cancelled, + /// A newer kernel state not known by this driver version. + Unknown, +} + +/// A caller-driven non-blocking statement operation. +/// +/// The handle exclusively borrows its [`Statement`] while the operation is +/// pending, preventing mutation or resubmission until the handle is consumed +/// or dropped. +pub struct SubmittedStatement<'statement> { + statement: &'statement mut Statement, + executed: Option, + connection_operation: Option, + expected_generation: u64, +} + +impl SubmittedStatement<'_> { + /// Poll the current server-side operation state once. + pub fn status(&self) -> Result { + let executed = self + .executed + .as_ref() + .ok_or_else(|| adbc_error("submitted statement was consumed", Status::InvalidState))?; + let status = self + .statement + .runtime + .block_on_safe(executed.status()) + .map_err(map_kernel_error)?; + Ok(match status { + kernel::StatementStatus::Pending => AsyncStatementStatus::Pending, + kernel::StatementStatus::Running => AsyncStatementStatus::Running, + kernel::StatementStatus::Succeeded => AsyncStatementStatus::Succeeded, + kernel::StatementStatus::Closed => AsyncStatementStatus::Closed, + kernel::StatementStatus::Failed(_) => AsyncStatementStatus::Failed, + kernel::StatementStatus::Cancelled => AsyncStatementStatus::Cancelled, + _ => AsyncStatementStatus::Unknown, + }) + } + + /// Poll to terminal state and return its Arrow result reader. + pub fn await_result(mut self) -> Result> { + let executed = self + .executed + .take() + .ok_or_else(|| adbc_error("submitted statement was consumed", Status::InvalidState))?; + let stream = self + .statement + .runtime + .block_on_safe(executed.await_result()) + .map_err(map_kernel_error)?; + let reader: Box = Box::new(AsyncKernelReader::new( + Arc::clone(&self.statement.runtime), + executed, + stream, + Arc::clone(&self.statement.generation), + self.expected_generation, + self.connection_operation + .take() + .expect("submitted statement owns its connection operation"), + )); + Ok(match self.statement.rows_fetched_per_block { + Some(max_rows) => Box::new(SlicingReader::new(reader, max_rows)), + None => reader, + }) + } + + /// Fetch a result after [`Self::status`] reported terminal success. + pub fn fetch_result(mut self) -> Result> { + let executed = self + .executed + .take() + .ok_or_else(|| adbc_error("submitted statement was consumed", Status::InvalidState))?; + let stream = self + .statement + .runtime + .block_on_safe(executed.fetch_result()) + .map_err(map_kernel_error)?; + let reader: Box = Box::new(AsyncKernelReader::new( + Arc::clone(&self.statement.runtime), + executed, + stream, + Arc::clone(&self.statement.generation), + self.expected_generation, + self.connection_operation + .take() + .expect("submitted statement owns its connection operation"), + )); + Ok(match self.statement.rows_fetched_per_block { + Some(max_rows) => Box::new(SlicingReader::new(reader, max_rows)), + None => reader, + }) + } + + /// Cancel the pending server-side operation. + pub fn cancel(&self) -> Result<()> { + let executed = self + .executed + .as_ref() + .ok_or_else(|| adbc_error("submitted statement was consumed", Status::InvalidState))?; + self.statement + .runtime + .block_on_safe(executed.cancel()) + .map_err(map_kernel_error) + } +} + +/// A thread-safe handle for cancelling the statement's current server operation. +#[derive(Clone)] +pub struct StatementCancellationHandle { + canceller: kernel::StatementCanceller, + runtime: Arc, + current_cancellation: Arc, + blocking_execute: Arc, + cancellation_notify: Arc, +} + +impl StatementCancellationHandle { + pub fn cancel(&self) -> Result<()> { + if self.current_cancellation.load(Ordering::Acquire) { + return Ok(()); + } + if self.canceller.statement_id().is_none() { + return Err(adbc_error( + "statement has no cancellable server operation", + Status::InvalidState, + )); + } + if self.current_cancellation.swap(true, Ordering::AcqRel) { + return Ok(()); + } + if self.blocking_execute.load(Ordering::Acquire) { + self.cancellation_notify.notify_waiters(); + return Ok(()); + } + let dispatched = self + .runtime + .block_on_safe(self.canceller.cancel()) + .map_err(map_kernel_error)?; + if dispatched { + Ok(()) + } else { + Err(adbc_error( + "statement has no cancellable server operation", + Status::InvalidState, + )) + } + } +} + +enum Binding { + Batch(RecordBatch), + Stream(Box), +} + +async fn cancel_blocking_execution( + execution: F, + cancelled: Arc, + notify: Arc, +) -> Option +where + F: Future, +{ + let notified = notify.notified(); + tokio::pin!(notified); + if cancelled.load(Ordering::Acquire) { + return None; + } + tokio::select! { + biased; + _ = &mut notified => None, + result = execution => Some(result), + } +} + +impl Statement { + /// Submit the SQL text without waiting for terminal state. + /// + /// This uses the kernel's `wait_timeout=0s` path. Call [`SubmittedStatement::status`] + /// to poll explicitly or [`SubmittedStatement::await_result`] to poll and fetch. + pub fn submit(&mut self) -> Result> { + if self.binding.is_some() { + return Err(unsupported( + "non-blocking execution with parameter bindings", + )); + } + self.invalidate_results(); + let connection_operation = self.register_connection_operation()?; + let runtime = Arc::clone(&self.runtime); + let executed = { + let mut inner = self.inner()?; + match self.client_timeout { + Some(timeout) => runtime.block_on_safe(inner.submit_with_timeout(timeout)), + None => runtime.block_on_safe(inner.submit()), + } + .map_err(map_kernel_error)? + }; + let expected_generation = self.generation.load(Ordering::Acquire); + Ok(SubmittedStatement { + statement: self, + executed: Some(executed), + connection_operation: Some(connection_operation), + expected_generation, + }) + } + + pub(crate) fn new( + inner: kernel::Statement, + metadata: kernel::Metadata, + runtime: Arc, + connection_cancellation: Arc, + escape_catalog_name: bool, + ) -> Self { + let canceller = inner.canceller(); + Self { + inner: Arc::new(Mutex::new(inner)), + metadata, + canceller, + runtime, + binding: None, + parameter_style: ParameterStyle::default(), + prepared: false, + client_timeout: None, + enable_direct_results: true, + rows_fetched_per_block: None, + generation: Arc::new(AtomicU64::new(0)), + current_cancellation: Arc::new(AtomicBool::new(false)), + blocking_execute: Arc::new(AtomicBool::new(false)), + cancellation_notify: Arc::new(Notify::new()), + connection_cancellation, + metadata_options: MetadataCommandOptions { + escape_catalog_name, + ..MetadataCommandOptions::default() + }, + } + } + + /// Return a cloneable handle that can cancel an execution from another thread. + pub fn cancellation_handle(&self) -> StatementCancellationHandle { + StatementCancellationHandle { + canceller: self.canceller.clone(), + runtime: Arc::clone(&self.runtime), + current_cancellation: Arc::clone(&self.current_cancellation), + blocking_execute: Arc::clone(&self.blocking_execute), + cancellation_notify: Arc::clone(&self.cancellation_notify), + } + } + + fn inner(&self) -> Result> { + self.inner + .lock() + .map_err(|_| adbc_error("kernel statement lock is poisoned", Status::Internal)) + } + + fn execute_inner(&self) -> Result { + let mut inner = self.inner()?; + if let Some(sql) = inner.spec_ref().sql.clone() { + // A previous bound execution leaves raw parameters in the kernel + // spec. An unbound execution must not accidentally reuse them. + inner.spec().sql(sql); + } + self.blocking_execute.store(true, Ordering::Release); + let cancelled = Arc::clone(&self.current_cancellation); + let notify = Arc::clone(&self.cancellation_notify); + let result = match self.client_timeout { + Some(timeout) => self.runtime.block_on_safe(cancel_blocking_execution( + inner.execute_with_timeout(timeout), + cancelled, + notify, + )), + None => self.runtime.block_on_safe(cancel_blocking_execution( + inner.execute(), + cancelled, + notify, + )), + }; + self.blocking_execute.store(false, Ordering::Release); + match result { + Some(result) => result.map_err(map_kernel_error), + None => Err(adbc_error("operation was cancelled", Status::Cancelled)), + } + } + + fn execute_async_inner( + &self, + ) -> Result<(kernel::ExecutedAsyncStatement, kernel::ResultStream)> { + let runtime = Arc::clone(&self.runtime); + let mut inner = self.inner()?; + if let Some(sql) = inner.spec_ref().sql.clone() { + // A previous bound execution leaves raw parameters in the kernel + // spec. An unbound execution must not accidentally reuse them. + inner.spec().sql(sql); + } + self.blocking_execute.store(true, Ordering::Release); + let cancelled = Arc::clone(&self.current_cancellation); + let notify = Arc::clone(&self.cancellation_notify); + let submitted = match self.client_timeout { + Some(timeout) => runtime.block_on_safe(cancel_blocking_execution( + inner.submit_with_timeout(timeout), + Arc::clone(&cancelled), + Arc::clone(¬ify), + )), + None => runtime.block_on_safe(cancel_blocking_execution( + inner.submit_with_timeout(Duration::MAX), + Arc::clone(&cancelled), + Arc::clone(¬ify), + )), + }; + drop(inner); + let result = match submitted { + Some(result) => match result.map_err(map_kernel_error) { + Ok(executed) => { + let stream = runtime.block_on_safe(cancel_blocking_execution( + executed.await_result(), + cancelled, + notify, + )); + match stream { + Some(stream) => stream + .map(|stream| (executed, stream)) + .map_err(map_kernel_error), + None => Err(adbc_error("operation was cancelled", Status::Cancelled)), + } + } + Err(error) => Err(error), + }, + None => Err(adbc_error("operation was cancelled", Status::Cancelled)), + }; + self.blocking_execute.store(false, Ordering::Release); + result + } + + fn invalidate_results(&self) { + self.generation.fetch_add(1, Ordering::AcqRel); + } + + fn register_connection_operation(&mut self) -> Result { + self.current_cancellation.store(false, Ordering::Release); + let cancelled = Arc::clone(&self.current_cancellation); + let cancellation = self.cancellation_handle(); + let generation = Arc::clone(&self.generation); + let expected_generation = generation.load(Ordering::Acquire); + self.connection_cancellation.register_while_with_signal( + Arc::new(move || cancellation.cancel()), + Arc::new(move || generation.load(Ordering::Acquire) == expected_generation), + cancelled, + ) + } + + fn set_other_option(&mut self, key: &str, value: OptionValue) -> Result<()> { + if let Some(timeout) = parse_client_timeout_option(key, value.clone()) { + self.client_timeout = timeout?; + return Ok(()); + } + match key { + ENABLE_DIRECT_RESULTS_OPTION => { + self.enable_direct_results = expect_bool_string(value, key)?; + Ok(()) + } + IS_METADATA_COMMAND_OPTION => { + self.metadata_options.enabled = expect_bool_string(value, key)?; + Ok(()) + } + METADATA_CATALOG_OPTION => { + self.metadata_options.catalog = Some(expect_string(value, key)?); + Ok(()) + } + METADATA_SCHEMA_OPTION => { + self.metadata_options.schema = Some(expect_string(value, key)?); + Ok(()) + } + METADATA_TABLE_OPTION => { + self.metadata_options.table = Some(expect_string(value, key)?); + Ok(()) + } + METADATA_TABLE_TYPES_OPTION => { + self.metadata_options.table_types = Some(expect_string(value, key)?); + Ok(()) + } + METADATA_COLUMN_OPTION => { + self.metadata_options.column = Some(expect_string(value, key)?); + Ok(()) + } + METADATA_FOREIGN_CATALOG_OPTION => { + self.metadata_options.foreign_catalog = Some(expect_string(value, key)?); + Ok(()) + } + METADATA_FOREIGN_SCHEMA_OPTION => { + self.metadata_options.foreign_schema = Some(expect_string(value, key)?); + Ok(()) + } + METADATA_FOREIGN_TABLE_OPTION => { + self.metadata_options.foreign_table = Some(expect_string(value, key)?); + Ok(()) + } + METADATA_ESCAPE_WILDCARDS_OPTION => { + self.metadata_options.escape_wildcards = expect_bool_string(value, key)?; + Ok(()) + } + PARAMETER_STYLE_OPTION => { + self.parameter_style = match expect_string(value, key)?.as_str() { + "positional" => ParameterStyle::Positional, + "named" => ParameterStyle::Named, + other => { + return Err(adbc_error( + format!("{key} expects positional or named, got {other:?}"), + Status::InvalidArguments, + )); + } + }; + Ok(()) + } + QUERY_TAGS_OPTION => { + self.inner()? + .spec() + .statement_conf + .insert("query_tags".into(), expect_string(value, key)?); + Ok(()) + } + ROW_LIMIT_OPTION => { + self.inner()? + .spec() + .row_limit(Some(expect_nonnegative_int(value, key)?)); + Ok(()) + } + ROWS_FETCHED_PER_BLOCK_OPTION | "adbc.databricks.rows_fetched_per_block" => { + let rows = expect_nonnegative_int(value, key)?; + if rows == 0 { + return Err(adbc_error( + format!("{key} must be greater than zero"), + Status::InvalidArguments, + )); + } + self.rows_fetched_per_block = Some(usize::try_from(rows).map_err(|_| { + adbc_error( + format!("{key} exceeds the platform row-count limit"), + Status::InvalidArguments, + ) + })?); + Ok(()) + } + SERVER_TIMEOUT_OPTION => { + let seconds = expect_nonnegative_int(value, key)?; + self.inner()? + .spec() + .statement_conf + .insert("STATEMENT_TIMEOUT".into(), seconds.to_string()); + Ok(()) + } + _ if key.starts_with(STATEMENT_CONF_PREFIX) => { + let name = &key[STATEMENT_CONF_PREFIX.len()..]; + if name.is_empty() { + return Err(adbc_error( + "statement conf option has an empty key", + Status::InvalidArguments, + )); + } + self.inner()? + .spec() + .statement_conf + .insert(name.into(), expect_string(value, key)?); + Ok(()) + } + _ => Err(unsupported(&format!("statement option {key}"))), + } + } + + fn get_other_string(&self, key: &str) -> Result { + match key { + ENABLE_DIRECT_RESULTS_OPTION => Ok(self.enable_direct_results.to_string()), + IS_METADATA_COMMAND_OPTION => Ok(self.metadata_options.enabled.to_string()), + METADATA_CATALOG_OPTION => metadata_string_option( + self.metadata_options.catalog.as_ref(), + METADATA_CATALOG_OPTION, + ), + METADATA_SCHEMA_OPTION => metadata_string_option( + self.metadata_options.schema.as_ref(), + METADATA_SCHEMA_OPTION, + ), + METADATA_TABLE_OPTION => { + metadata_string_option(self.metadata_options.table.as_ref(), METADATA_TABLE_OPTION) + } + METADATA_TABLE_TYPES_OPTION => metadata_string_option( + self.metadata_options.table_types.as_ref(), + METADATA_TABLE_TYPES_OPTION, + ), + METADATA_COLUMN_OPTION => metadata_string_option( + self.metadata_options.column.as_ref(), + METADATA_COLUMN_OPTION, + ), + METADATA_FOREIGN_CATALOG_OPTION => metadata_string_option( + self.metadata_options.foreign_catalog.as_ref(), + METADATA_FOREIGN_CATALOG_OPTION, + ), + METADATA_FOREIGN_SCHEMA_OPTION => metadata_string_option( + self.metadata_options.foreign_schema.as_ref(), + METADATA_FOREIGN_SCHEMA_OPTION, + ), + METADATA_FOREIGN_TABLE_OPTION => metadata_string_option( + self.metadata_options.foreign_table.as_ref(), + METADATA_FOREIGN_TABLE_OPTION, + ), + METADATA_ESCAPE_WILDCARDS_OPTION => { + Ok(self.metadata_options.escape_wildcards.to_string()) + } + PARAMETER_STYLE_OPTION => Ok(match self.parameter_style { + ParameterStyle::Positional => "positional", + ParameterStyle::Named => "named", + } + .into()), + QUERY_TAGS_OPTION => self + .inner()? + .spec_ref() + .statement_conf + .get("query_tags") + .cloned() + .ok_or_else(|| adbc_error("query tags are not set", Status::NotFound)), + _ if key.starts_with(STATEMENT_CONF_PREFIX) => self + .inner()? + .spec_ref() + .statement_conf + .get(&key[STATEMENT_CONF_PREFIX.len()..]) + .cloned() + .ok_or_else(|| adbc_error("statement conf is not set", Status::NotFound)), + _ => Err(option_not_found("statement string", key)), + } + } + + fn get_other_int(&self, key: &str) -> Result { + match key { + CLIENT_TIMEOUT_OPTION => Ok(self + .client_timeout + .map(|d| d.as_millis() as i64) + .unwrap_or(0)), + QUERY_TIMEOUT_OPTION => Ok(self + .client_timeout + .map(|duration| duration.as_secs() as i64) + .unwrap_or(0)), + ROW_LIMIT_OPTION => self + .inner()? + .spec_ref() + .row_limit + .ok_or_else(|| adbc_error("row limit is not set", Status::NotFound)), + ROWS_FETCHED_PER_BLOCK_OPTION | "adbc.databricks.rows_fetched_per_block" => self + .rows_fetched_per_block + .map(|rows| rows as i64) + .ok_or_else(|| adbc_error("rows fetched per block is not set", Status::NotFound)), + SERVER_TIMEOUT_OPTION => self + .inner()? + .spec_ref() + .statement_conf + .get("STATEMENT_TIMEOUT") + .ok_or_else(|| adbc_error("statement timeout is not set", Status::NotFound))? + .parse() + .map_err(|_| adbc_error("invalid stored statement timeout", Status::Internal)), + _ => Err(option_not_found("statement integer", key)), + } + } +} + +impl adbc_core::Optionable for Statement { + type Option = OptionStatement; + + fn set_option(&mut self, key: OptionStatement, value: OptionValue) -> Result<()> { + match key { + OptionStatement::Incremental => { + if bool::try_from(value)? { + Err(unsupported("incremental partitioned execution")) + } else { + self.invalidate_results(); + Ok(()) + } + } + OptionStatement::Progress | OptionStatement::MaxProgress => Err(adbc_error( + "statement progress options are read-only", + Status::InvalidArguments, + )), + OptionStatement::Other(key) => { + let result = self.set_other_option(&key, value); + if result.is_ok() { + self.invalidate_results(); + } + result + } + key => Err(unsupported(&format!("statement option {key:?}"))), + } + } + + fn get_option_string(&self, key: OptionStatement) -> Result { + match key { + OptionStatement::Other(key) => self.get_other_string(&key), + key => Err(option_not_found("statement string", key.as_ref())), + } + } + fn get_option_bytes(&self, key: OptionStatement) -> Result> { + Err(option_not_found("statement bytes", key.as_ref())) + } + fn get_option_int(&self, key: OptionStatement) -> Result { + match key { + OptionStatement::Other(key) => self.get_other_int(&key), + key => Err(option_not_found("statement integer", key.as_ref())), + } + } + fn get_option_double(&self, key: OptionStatement) -> Result { + match key { + OptionStatement::Progress | OptionStatement::MaxProgress => { + Err(unsupported("statement progress")) + } + key => Err(option_not_found("statement double", key.as_ref())), + } + } +} + +impl adbc_core::Statement for Statement { + fn bind(&mut self, batch: RecordBatch) -> Result<()> { + validate_binding_schema(&batch.schema(), self.parameter_style)?; + self.invalidate_results(); + self.binding = Some(Binding::Batch(batch)); + Ok(()) + } + + fn bind_stream(&mut self, reader: Box) -> Result<()> { + validate_binding_schema(&reader.schema(), self.parameter_style)?; + self.invalidate_results(); + self.binding = Some(Binding::Stream(reader)); + Ok(()) + } + + fn execute(&mut self) -> Result> { + self.invalidate_results(); + if self.metadata_options.enabled { + if self.binding.is_some() { + return Err(unsupported("parameter binding for metadata commands")); + } + let command = + self.inner()?.spec_ref().sql.clone().ok_or_else(|| { + adbc_error("metadata command is not set", Status::InvalidState) + })?; + let reader = metadata::execute_statement_command( + &self.metadata, + &self.runtime, + &command, + self.metadata_options.catalog.as_deref(), + self.metadata_options.schema.as_deref(), + self.metadata_options.table.as_deref(), + self.metadata_options.column.as_deref(), + self.metadata_options.table_types.as_deref(), + self.metadata_options.foreign_catalog.as_deref(), + self.metadata_options.foreign_schema.as_deref(), + self.metadata_options.foreign_table.as_deref(), + self.metadata_options.escape_wildcards, + self.metadata_options.escape_catalog_name, + )?; + return Ok(match self.rows_fetched_per_block { + Some(max_rows) => Box::new(SlicingReader::new(reader, max_rows)), + None => reader, + }); + } + let connection_operation = self.register_connection_operation()?; + let Some(binding) = self.binding.take() else { + if !self.enable_direct_results { + let (executed, stream) = self.execute_async_inner()?; + let reader: Box = Box::new(AsyncKernelReader::new( + Arc::clone(&self.runtime), + executed, + stream, + Arc::clone(&self.generation), + self.generation.load(Ordering::Acquire), + connection_operation, + )); + return Ok(match self.rows_fetched_per_block { + Some(max_rows) => Box::new(SlicingReader::new(reader, max_rows)), + None => reader, + }); + } + let executed = self.execute_inner()?; + let reader: Box = Box::new(KernelReader::new( + Arc::clone(&self.runtime), + executed, + Arc::clone(&self.generation), + self.generation.load(Ordering::Acquire), + connection_operation, + )); + return Ok(match self.rows_fetched_per_block { + Some(max_rows) => Box::new(SlicingReader::new(reader, max_rows)), + None => reader, + }); + }; + + if !self.enable_direct_results { + return Err(unsupported( + "parameter binding when direct results are disabled", + )); + } + + let mut rows = match binding { + Binding::Batch(batch) => BoundRows::from_batch(batch), + Binding::Stream(reader) => BoundRows::from_stream(reader), + }; + let row = rows + .next_row()? + .ok_or_else(|| unsupported("executing a query with an empty parameter binding"))?; + let base_spec = self.inner()?.spec_ref().clone(); + let executed = execute_bound_row( + &self.inner, + &self.runtime, + &base_spec, + &row, + self.parameter_style, + self.client_timeout, + )?; + let expected_generation = self.generation.load(Ordering::Acquire); + let reader: Box = Box::new(SequenceReader::new( + Arc::clone(&self.inner), + Arc::clone(&self.runtime), + Arc::clone(&self.generation), + expected_generation, + base_spec, + self.parameter_style, + self.client_timeout, + rows, + executed, + connection_operation, + )); + Ok(match self.rows_fetched_per_block { + Some(max_rows) => Box::new(SlicingReader::new(reader, max_rows)), + None => reader, + }) + } + + fn execute_update(&mut self) -> Result> { + self.invalidate_results(); + let _connection_operation = self.register_connection_operation()?; + let Some(binding) = self.binding.take() else { + if !self.enable_direct_results { + let (executed, stream) = self.execute_async_inner()?; + let count = executed.num_modified_rows(); + drop(stream); + self.runtime + .block_on_safe(executed.close()) + .map_err(map_kernel_error)?; + return Ok(count); + } + let executed = self.execute_inner()?; + let count = executed.num_modified_rows(); + self.runtime + .block_on_safe(executed.close()) + .map_err(map_kernel_error)?; + return Ok(count); + }; + + if !self.enable_direct_results { + return Err(unsupported( + "parameter binding when direct results are disabled", + )); + } + + let mut rows = match binding { + Binding::Batch(batch) => BoundRows::from_batch(batch), + Binding::Stream(reader) => BoundRows::from_stream(reader), + }; + let base_spec = self.inner()?.spec_ref().clone(); + let mut total = Some(0_i64); + let mut first_error = None; + let mut row_index = 0_usize; + while let Some(row) = rows.next_row()? { + let executed = match execute_bound_row( + &self.inner, + &self.runtime, + &base_spec, + &row, + self.parameter_style, + self.client_timeout, + ) { + Ok(executed) => executed, + Err(mut error) => { + row_index += 1; + error.message = format!("batch row {row_index} failed: {}", error.message); + first_error.get_or_insert(error); + total = None; + continue; + } + }; + total = match (total, executed.num_modified_rows()) { + (Some(total), Some(count)) => { + Some(total.checked_add(count).ok_or_else(|| { + adbc_error("affected row count overflow", Status::Internal) + })?) + } + _ => None, + }; + // The kernel closes dropped executed handles asynchronously. Waiting + // for every close would serialize an extra network round trip per row. + drop(executed); + row_index += 1; + } + match first_error { + Some(error) => Err(error), + None => Ok(total), + } + } + + fn execute_schema(&mut self) -> Result { + self.invalidate_results(); + let connection_operation = self.register_connection_operation()?; + let original_spec = self.inner()?.spec_ref().clone(); + let sql = original_spec + .sql + .clone() + .ok_or_else(|| adbc_error("SQL query is not set", Status::InvalidState))?; + if !is_describable_query(&sql) { + return Err(unsupported("execute_schema for this SQL statement type")); + } + let describe_sql = format!( + "DESCRIBE QUERY {}", + kernel::statement::params::replace_parameter_markers_with_literals(&sql) + ); + let result = (|| { + { + let mut inner = self.inner()?; + *inner.spec() = original_spec.clone(); + inner.spec().sql(describe_sql); + } + let executed = self.execute_inner()?; + let reader = KernelReader::new( + Arc::clone(&self.runtime), + executed, + Arc::clone(&self.generation), + self.generation.load(Ordering::Acquire), + connection_operation, + ); + kernel::statement::params::describe_result_to_schema(reader).map_err(map_kernel_error) + })(); + let restore = self.inner().map(|mut inner| { + *inner.spec() = original_spec; + }); + match (result, restore) { + (Err(error), _) => Err(error), + (Ok(_), Err(error)) => Err(error), + (Ok(schema), Ok(())) => Ok(schema), + } + } + fn execute_partitions(&mut self) -> Result { + Err(unsupported("execute_partitions")) + } + fn get_parameter_schema(&self) -> Result { + if !self.prepared { + return Err(adbc_error( + "get_parameter_schema requires prepare", + Status::InvalidState, + )); + } + if self.parameter_style == ParameterStyle::Named { + return Err(unsupported( + "get_parameter_schema for named parameter markers", + )); + } + let sql = self + .inner()? + .spec_ref() + .sql + .clone() + .ok_or_else(|| adbc_error("SQL query is not set", Status::InvalidState))?; + let count = kernel::statement::params::count_parameter_markers(&sql); + Ok(parameter_schema_from_binding( + self.binding.as_ref(), + count, + self.parameter_style, + )) + } + + fn prepare(&mut self) -> Result<()> { + if self.inner()?.spec_ref().sql.is_none() { + return Err(adbc_error( + "cannot prepare before setting SQL", + Status::InvalidState, + )); + } + self.invalidate_results(); + // SEA has no server prepare. Retaining SQL and reapplying binds on every + // execution is the spec-correct client-side preparation available today. + self.prepared = true; + Ok(()) + } + + fn set_sql_query(&mut self, query: impl AsRef) -> Result<()> { + self.invalidate_results(); + self.inner()?.spec().sql(query.as_ref()); + self.binding = None; + self.prepared = false; + Ok(()) + } + fn set_substrait_plan(&mut self, _plan: impl AsRef<[u8]>) -> Result<()> { + Err(unsupported("Substrait plans")) + } + fn cancel(&mut self) -> Result<()> { + self.cancellation_handle().cancel()?; + self.current_cancellation.store(true, Ordering::Release); + Ok(()) + } +} + +fn parameter_schema_from_binding( + binding: Option<&Binding>, + count: usize, + style: ParameterStyle, +) -> Schema { + if let Some(binding) = binding { + let schema = match binding { + Binding::Batch(batch) => batch.schema(), + Binding::Stream(reader) => reader.schema(), + }; + if schema.fields().len() == count { + if style == ParameterStyle::Named { + return schema.as_ref().clone(); + } + let fields = schema + .fields() + .iter() + .map(|field| { + Field::new("", field.data_type().clone(), field.is_nullable()) + .with_metadata(field.metadata().clone()) + }) + .collect::>(); + return Schema::new_with_metadata(fields, schema.metadata().clone()); + } + } + Schema::new( + (0..count) + .map(|_| Field::new("", DataType::Null, true)) + .collect::>(), + ) +} + +fn convert_binding(batch: &RecordBatch, style: ParameterStyle) -> Result> { + if batch.num_rows() != 1 { + return Err(adbc_error( + format!("expected one parameter row, got {}", batch.num_rows()), + Status::InvalidArguments, + )); + } + let parameters = kernel::statement::params::record_batch_to_sea_parameters(batch) + .map_err(map_kernel_error)?; + parameters + .into_iter() + .enumerate() + .map(|(index, parameter)| { + let binary = matches!( + batch.schema().field(index).data_type(), + DataType::Binary | DataType::LargeBinary + ); + Ok(BoundParameter { + name: match style { + ParameterStyle::Positional => None, + ParameterStyle::Named => Some(batch.schema().field(index).name().clone()), + }, + // SEA currently interprets BINARY parameter text as literal + // UTF-8 bytes. Send the kernel-produced hex as STRING and + // reconstruct bytes in SQL with unhex(?). + param_type: if binary { + "STRING".into() + } else { + parameter.param_type + }, + value: parameter.value, + binary, + }) + }) + .collect() +} + +fn validate_binding_schema(schema: &arrow_schema::SchemaRef, style: ParameterStyle) -> Result<()> { + if style == ParameterStyle::Named { + let mut names = HashSet::with_capacity(schema.fields().len()); + for field in schema.fields() { + if !is_valid_named_parameter(field.name()) { + return Err(adbc_error( + format!( + "named parameter field {:?} must match [A-Za-z_][A-Za-z0-9_]*", + field.name() + ), + Status::InvalidArguments, + )); + } + if !names.insert(field.name()) { + return Err(adbc_error( + format!("duplicate named parameter field {:?}", field.name()), + Status::InvalidArguments, + )); + } + } + } + Ok(()) +} + +fn is_valid_named_parameter(name: &str) -> bool { + let mut bytes = name.bytes(); + matches!(bytes.next(), Some(first) if first.is_ascii_alphabetic() || first == b'_') + && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') +} + +pub(crate) fn execute_bound_row( + inner: &Arc>, + runtime: &Arc, + base_spec: &kernel::StatementSpec, + row: &RecordBatch, + style: ParameterStyle, + client_timeout: Option, +) -> Result { + let parameters = convert_binding(row, style)?; + let mut inner = inner + .lock() + .map_err(|_| adbc_error("kernel statement lock is poisoned", Status::Internal))?; + *inner.spec() = base_spec.clone(); + let base_sql = inner + .spec_ref() + .sql + .clone() + .ok_or_else(|| adbc_error("SQL query is not set", Status::InvalidState))?; + let sql = match style { + ParameterStyle::Positional => { + let binary_parameters = parameters + .iter() + .enumerate() + .filter_map(|(index, parameter)| parameter.binary.then_some(index)) + .collect::>(); + rewrite_binary_parameter_markers(&base_sql, &binary_parameters)? + } + ParameterStyle::Named => { + let binary_names = parameters + .iter() + .filter(|parameter| parameter.binary) + .map(|parameter| { + parameter + .name + .as_deref() + .expect("named style always supplies parameter names") + }) + .collect::>(); + rewrite_named_binary_parameter_markers(&base_sql, &binary_names)? + } + }; + // sql() is the public reset point for every parameter representation. + inner.spec().sql(sql); + for parameter in parameters { + inner + .spec() + .param_raw(parameter.name, parameter.param_type, parameter.value); + } + match client_timeout { + Some(timeout) => runtime.block_on_safe(inner.execute_with_timeout(timeout)), + None => runtime.block_on_safe(inner.execute()), + } + .map_err(map_kernel_error) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum SqlMarkerState { + Normal, + SingleQuote, + DoubleQuote, + BacktickQuote, + LineComment, + BlockComment, +} + +fn rewrite_binary_parameter_markers(sql: &str, binary_parameters: &[usize]) -> Result { + rewrite_parameter_markers(sql, binary_parameters, &HashSet::new()) +} + +fn rewrite_named_binary_parameter_markers( + sql: &str, + binary_names: &HashSet<&str>, +) -> Result { + rewrite_parameter_markers(sql, &[], binary_names) +} + +fn rewrite_parameter_markers( + sql: &str, + binary_parameters: &[usize], + binary_names: &HashSet<&str>, +) -> Result { + if binary_parameters.is_empty() && binary_names.is_empty() { + return Ok(sql.to_owned()); + } + let mut rewritten = + Vec::with_capacity(sql.len() + (binary_parameters.len() + binary_names.len()) * 7); + let bytes = sql.as_bytes(); + let mut state = SqlMarkerState::Normal; + let mut index = 0; + let mut marker = 0; + let mut rewritten_count = 0; + let mut rewritten_names = HashSet::with_capacity(binary_names.len()); + while index < bytes.len() { + match state { + SqlMarkerState::Normal => { + if bytes[index] == b'?' { + if binary_parameters.contains(&marker) { + rewritten.extend_from_slice(b"unhex(?)"); + rewritten_count += 1; + } else { + rewritten.push(b'?'); + } + marker += 1; + index += 1; + } else if bytes[index] == b':' + && (index == 0 + || (bytes[index - 1] != b':' + && !is_named_parameter_continue(bytes[index - 1]))) + && bytes + .get(index + 1) + .is_some_and(|byte| is_named_parameter_start(*byte)) + { + let mut end = index + 2; + while bytes + .get(end) + .is_some_and(|byte| is_named_parameter_continue(*byte)) + { + end += 1; + } + let name = std::str::from_utf8(&bytes[index + 1..end]) + .expect("named parameter identifiers are ASCII"); + if binary_names.contains(name) { + rewritten.extend_from_slice(b"unhex("); + rewritten.extend_from_slice(&bytes[index..end]); + rewritten.push(b')'); + rewritten_names.insert(name); + } else { + rewritten.extend_from_slice(&bytes[index..end]); + } + index = end; + } else if bytes[index] == b'\'' { + state = SqlMarkerState::SingleQuote; + rewritten.push(b'\''); + index += 1; + } else if bytes[index] == b'"' { + state = SqlMarkerState::DoubleQuote; + rewritten.push(b'"'); + index += 1; + } else if bytes[index] == b'`' { + state = SqlMarkerState::BacktickQuote; + rewritten.push(b'`'); + index += 1; + } else if bytes.get(index..index + 2) == Some(b"--") { + state = SqlMarkerState::LineComment; + rewritten.extend_from_slice(b"--"); + index += 2; + } else if bytes.get(index..index + 2) == Some(b"/*") { + state = SqlMarkerState::BlockComment; + rewritten.extend_from_slice(b"/*"); + index += 2; + } else { + rewritten.push(bytes[index]); + index += 1; + } + } + SqlMarkerState::SingleQuote => { + rewritten.push(bytes[index]); + if bytes[index] == b'\'' { + if bytes.get(index + 1) == Some(&b'\'') { + rewritten.push(b'\''); + index += 2; + } else { + state = SqlMarkerState::Normal; + index += 1; + } + } else { + index += 1; + } + } + SqlMarkerState::DoubleQuote => { + rewritten.push(bytes[index]); + if bytes[index] == b'"' { + if bytes.get(index + 1) == Some(&b'"') { + rewritten.push(b'"'); + index += 2; + } else { + state = SqlMarkerState::Normal; + index += 1; + } + } else { + index += 1; + } + } + SqlMarkerState::BacktickQuote => { + rewritten.push(bytes[index]); + if bytes[index] == b'`' { + if bytes.get(index + 1) == Some(&b'`') { + rewritten.push(b'`'); + index += 2; + } else { + state = SqlMarkerState::Normal; + index += 1; + } + } else { + index += 1; + } + } + SqlMarkerState::LineComment => { + rewritten.push(bytes[index]); + if bytes[index] == b'\n' { + state = SqlMarkerState::Normal; + } + index += 1; + } + SqlMarkerState::BlockComment => { + if bytes.get(index..index + 2) == Some(b"*/") { + rewritten.extend_from_slice(b"*/"); + state = SqlMarkerState::Normal; + index += 2; + } else { + rewritten.push(bytes[index]); + index += 1; + } + } + } + } + if rewritten_count != binary_parameters.len() { + return Err(adbc_error( + "binary parameter has no corresponding positional SQL marker", + Status::InvalidArguments, + )); + } + if rewritten_names.len() != binary_names.len() { + return Err(adbc_error( + "binary named parameter has no corresponding SQL marker", + Status::InvalidArguments, + )); + } + Ok(String::from_utf8(rewritten).expect("rewriting preserves UTF-8")) +} + +fn is_named_parameter_start(byte: u8) -> bool { + byte.is_ascii_alphabetic() || byte == b'_' +} + +fn is_named_parameter_continue(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || byte == b'_' +} + +fn is_describable_query(sql: &str) -> bool { + let bytes = sql.as_bytes(); + let mut index = 0; + loop { + while index < bytes.len() && (bytes[index].is_ascii_whitespace() || bytes[index] == b'(') { + index += 1; + } + if bytes.get(index..index + 2) == Some(b"--") { + index += 2; + while index < bytes.len() && bytes[index] != b'\n' { + index += 1; + } + continue; + } + if bytes.get(index..index + 2) == Some(b"/*") { + index += 2; + while index + 1 < bytes.len() && &bytes[index..index + 2] != b"*/" { + index += 1; + } + index = (index + 2).min(bytes.len()); + continue; + } + break; + } + let end = bytes[index..] + .iter() + .position(|byte| !byte.is_ascii_alphabetic()) + .map(|offset| index + offset) + .unwrap_or(bytes.len()); + matches!( + sql[index..end].to_ascii_uppercase().as_str(), + "SELECT" | "WITH" | "VALUES" | "FROM" + ) +} + +fn expect_string(value: OptionValue, key: &str) -> Result { + match value { + OptionValue::String(value) => Ok(value), + _ => Err(adbc_error( + format!("{key} expects a string value"), + Status::InvalidArguments, + )), + } +} + +fn expect_bool_string(value: OptionValue, key: &str) -> Result { + let value = expect_string(value, key)?; + match value.to_ascii_lowercase().as_str() { + "true" => Ok(true), + "false" => Ok(false), + _ => Err(adbc_error( + format!("{key} expects true or false"), + Status::InvalidArguments, + )), + } +} + +fn metadata_string_option(value: Option<&String>, key: &str) -> Result { + value + .cloned() + .ok_or_else(|| adbc_error(format!("{key} is not set"), Status::NotFound)) +} + +fn expect_nonnegative_int(value: OptionValue, key: &str) -> Result { + let value = match value { + OptionValue::Int(value) => value, + OptionValue::String(value) => value.parse().map_err(|_| { + adbc_error( + format!("{key} expects a nonnegative integer"), + Status::InvalidArguments, + ) + })?, + _ => { + return Err(adbc_error( + format!("{key} expects a nonnegative integer"), + Status::InvalidArguments, + )); + } + }; + if value < 0 { + return Err(adbc_error( + format!("{key} expects a nonnegative integer"), + Status::InvalidArguments, + )); + } + Ok(value) +} + +fn nonzero_duration(value: i64, convert: impl FnOnce(u64) -> Duration) -> Option { + (value != 0).then(|| convert(value as u64)) +} + +fn parse_client_timeout_option(key: &str, value: OptionValue) -> Option>> { + let convert: fn(u64) -> Duration = match key { + CLIENT_TIMEOUT_OPTION => Duration::from_millis, + QUERY_TIMEOUT_OPTION => Duration::from_secs, + _ => return None, + }; + Some(expect_nonnegative_int(value, key).map(|value| nonzero_duration(value, convert))) +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_array::{BinaryArray, Int64Array, LargeBinaryArray, StringArray}; + use arrow_schema::{DataType, Field}; + + fn batch(rows: usize) -> RecordBatch { + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("label", DataType::Utf8, true), + ])); + let ids = Int64Array::from_iter_values((0..rows).map(|value| value as i64)); + let labels = StringArray::from_iter((0..rows).map(|_| Some("value"))); + RecordBatch::try_new(schema, vec![Arc::new(ids), Arc::new(labels)]).unwrap() + } + + #[test] + fn parameter_schema_uses_matching_bound_arrow_types() { + let batch = batch(1); + let expected = batch.schema().as_ref().clone(); + let binding = Binding::Batch(batch); + let actual = parameter_schema_from_binding(Some(&binding), 2, ParameterStyle::Positional); + assert_eq!( + actual + .fields() + .iter() + .map(|field| field.name()) + .collect::>(), + vec!["", ""] + ); + assert_eq!(actual.field(0).data_type(), expected.field(0).data_type()); + assert_eq!(actual.field(1).data_type(), expected.field(1).data_type()); + assert_eq!( + actual.field(0).is_nullable(), + expected.field(0).is_nullable() + ); + assert_eq!( + actual.field(1).is_nullable(), + expected.field(1).is_nullable() + ); + + let unknown = parameter_schema_from_binding(Some(&binding), 1, ParameterStyle::Positional); + assert_eq!(unknown.fields().len(), 1); + assert_eq!(unknown.field(0).data_type(), &DataType::Null); + assert!(unknown.field(0).is_nullable()); + } + + #[test] + fn positional_binding_preserves_types_and_values() { + let params = convert_binding(&batch(1), ParameterStyle::Positional).unwrap(); + assert_eq!(params.len(), 2); + assert_eq!(params[0].name, None); + assert_eq!(params[0].param_type, "BIGINT"); + assert_eq!(params[0].value.as_deref(), Some("0")); + assert_eq!(params[1].param_type, "STRING"); + } + + #[test] + fn named_binding_uses_arrow_field_names() { + let params = convert_binding(&batch(1), ParameterStyle::Named).unwrap(); + assert_eq!(params[0].name.as_deref(), Some("id")); + assert_eq!(params[1].name.as_deref(), Some("label")); + } + + #[test] + fn binary_binding_sends_hex_as_string() { + let schema = Arc::new(Schema::new(vec![Field::new( + "payload", + DataType::Binary, + true, + )])); + let values = BinaryArray::from(vec![Some(&[0x01, 0x02, 0x03, 0xff][..])]); + let batch = RecordBatch::try_new(schema, vec![Arc::new(values)]).unwrap(); + let params = convert_binding(&batch, ParameterStyle::Positional).unwrap(); + assert!(params[0].binary); + assert_eq!(params[0].param_type, "STRING"); + assert_eq!(params[0].value.as_deref(), Some("010203ff")); + } + + #[test] + fn large_binary_and_null_binary_preserve_semantics() { + let schema = Arc::new(Schema::new(vec![ + Field::new("large", DataType::LargeBinary, true), + Field::new("null", DataType::Binary, true), + ])); + let large = LargeBinaryArray::from(vec![Some(&[0x80, 0xff][..])]); + let null = BinaryArray::from(vec![None::<&[u8]>]); + let batch = RecordBatch::try_new(schema, vec![Arc::new(large), Arc::new(null)]).unwrap(); + let params = convert_binding(&batch, ParameterStyle::Positional).unwrap(); + assert_eq!(params[0].value.as_deref(), Some("80ff")); + assert_eq!(params[1].value, None); + assert!(params.iter().all(|parameter| parameter.binary)); + assert!(params + .iter() + .all(|parameter| parameter.param_type == "STRING")); + assert_eq!( + rewrite_binary_parameter_markers("SELECT ?, ?", &[0, 1]).unwrap(), + "SELECT unhex(?), unhex(?)" + ); + } + + #[test] + fn binary_rewrite_targets_only_real_selected_markers() { + let sql = "SELECT '?' AS literal, ? AS number, ? AS bytes -- ?\n/* ? */ WHERE `?` = \"?\""; + assert_eq!( + rewrite_binary_parameter_markers(sql, &[1]).unwrap(), + "SELECT '?' AS literal, ? AS number, unhex(?) AS bytes -- ?\n/* ? */ WHERE `?` = \"?\"" + ); + } + + #[test] + fn binary_rewrite_is_stable_across_repeated_rows() { + let base_sql = "SELECT ? AS payload"; + let first = rewrite_binary_parameter_markers(base_sql, &[0]).unwrap(); + let second = rewrite_binary_parameter_markers(base_sql, &[0]).unwrap(); + assert_eq!(first, "SELECT unhex(?) AS payload"); + assert_eq!(second, first); + assert!(!second.contains("unhex(unhex")); + } + + #[test] + fn named_binary_binding_uses_string_hex_payload() { + let schema = Arc::new(Schema::new(vec![Field::new( + "payload", + DataType::Binary, + true, + )])); + let values = BinaryArray::from(vec![Some(&[0x01][..])]); + let batch = RecordBatch::try_new(schema, vec![Arc::new(values)]).unwrap(); + let params = convert_binding(&batch, ParameterStyle::Named).unwrap(); + assert_eq!(params[0].name.as_deref(), Some("payload")); + assert_eq!(params[0].param_type, "STRING"); + assert_eq!(params[0].value.as_deref(), Some("01")); + } + + #[test] + fn named_binary_rewrite_wraps_repeated_markers_only() { + let names = HashSet::from(["payload"]); + let sql = "SELECT :plain, :payload, :payload, ':payload', \" :payload \", `:payload` -- :payload\n/* :payload */"; + assert_eq!( + rewrite_named_binary_parameter_markers(sql, &names).unwrap(), + "SELECT :plain, unhex(:payload), unhex(:payload), ':payload', \" :payload \", `:payload` -- :payload\n/* :payload */" + ); + } + + #[test] + fn named_binary_rewrite_respects_identifier_boundaries() { + let names = HashSet::from(["payload"]); + assert!(rewrite_named_binary_parameter_markers("SELECT x:payload", &names).is_err()); + assert_eq!( + rewrite_named_binary_parameter_markers( + "SELECT :payload_suffix, value::payload, :payload", + &names + ) + .unwrap(), + "SELECT :payload_suffix, value::payload, unhex(:payload)" + ); + } + + #[test] + fn named_binding_rejects_invalid_or_ambiguous_field_names() { + for invalid in ["", "1payload", "payload-name", "payload.name"] { + let schema = Arc::new(Schema::new(vec![Field::new( + invalid, + DataType::Binary, + true, + )])); + let error = validate_binding_schema(&schema, ParameterStyle::Named).unwrap_err(); + assert_eq!(error.status, Status::InvalidArguments); + assert!(error.message.contains("must match")); + } + + let schema = Arc::new(Schema::new(vec![ + Field::new("payload", DataType::Binary, true), + Field::new("payload", DataType::Utf8, true), + ])); + let error = validate_binding_schema(&schema, ParameterStyle::Named).unwrap_err(); + assert_eq!(error.status, Status::InvalidArguments); + assert!(error.message.contains("duplicate")); + } + + #[test] + fn single_row_conversion_rejects_unsliced_batches() { + let error = convert_binding(&batch(2), ParameterStyle::Positional).unwrap_err(); + assert_eq!(error.status, Status::InvalidArguments); + assert!(error.message.contains("expected one parameter row")); + } + + #[test] + fn option_parsers_reject_wrong_types_and_negative_values() { + assert!(expect_string(OptionValue::Int(1), "x").is_err()); + assert!(expect_nonnegative_int(OptionValue::Int(-1), "x").is_err()); + assert_eq!( + expect_nonnegative_int(OptionValue::String("42".into()), "x").unwrap(), + 42 + ); + assert_eq!(nonzero_duration(0, Duration::from_secs), None); + assert_eq!( + nonzero_duration(42, Duration::from_secs), + Some(Duration::from_secs(42)) + ); + assert_eq!( + parse_client_timeout_option(QUERY_TIMEOUT_OPTION, OptionValue::String("42".into())) + .unwrap() + .unwrap(), + Some(Duration::from_secs(42)) + ); + assert_eq!( + parse_client_timeout_option(CLIENT_TIMEOUT_OPTION, OptionValue::Int(42)) + .unwrap() + .unwrap(), + Some(Duration::from_millis(42)) + ); + assert!(parse_client_timeout_option("not-a-timeout", OptionValue::Int(42)).is_none()); + assert!(expect_bool_string(OptionValue::String("TRUE".into()), "x").unwrap()); + assert!(!expect_bool_string(OptionValue::String("false".into()), "x").unwrap()); + assert!(expect_bool_string(OptionValue::String("yes".into()), "x").is_err()); + } + + #[test] + fn describe_query_classifier_accepts_queries_but_not_commands() { + assert!(is_describable_query( + "/* comment */ WITH t AS (SELECT 1) SELECT * FROM t" + )); + assert!(is_describable_query("(SELECT 1)")); + assert!(!is_describable_query("INSERT INTO t VALUES (1)")); + assert!(!is_describable_query("DESCRIBE TABLE t")); + } +} diff --git a/adbc/tests/README.md b/adbc/tests/README.md new file mode 100644 index 00000000..7169b79f --- /dev/null +++ b/adbc/tests/README.md @@ -0,0 +1,31 @@ +# Live and cross-driver validation + +Offline tests run from the repository root with: + +```text +cargo test -p databricks-adbc --features ffi +``` + +The ignored live smoke test reads credentials only at runtime: + +```text +DATABRICKS_HOST= +DATABRICKS_HTTP_PATH=/sql/1.0/warehouses/ +DATABRICKS_TOKEN_FILE= +DATABRICKS_TEST_CATALOG= +cargo test -p databricks-adbc --test live -- --ignored --exact select_one_fetches_the_complete_result +``` + +The test never prints or persists the token. Keep the credential file outside this repository. + +Cross-driver CI integration is maintained in `databricks-driver-test`. It should +check out this repository and build the `adbc/` workspace member rather than +copying driver source into the test repository: + +1. Point a temporary harness dependency at this crate; do not copy the driver into the test repository. +2. Keep the live-only mitmproxy runner and serial execution contract. +3. Run test groups classified as required or applicable for Rust ADBC. +4. Treat historical Rust statuses as evidence only. +5. Record semantic incompatibilities in the applicability ledger instead of modifying driver behavior to satisfy language- or transport-specific assertions. + +Kernel-gap cases remain isolated until approved. diff --git a/adbc/tests/live.rs b/adbc/tests/live.rs new file mode 100644 index 00000000..54f8deec --- /dev/null +++ b/adbc/tests/live.rs @@ -0,0 +1,368 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::{env, fs}; + +use adbc_core::options::{OptionConnection, OptionDatabase, OptionStatement, OptionValue}; +use adbc_core::{Connection as _, Database as _, Driver as _, Optionable as _, Statement as _}; +use arrow_array::{Array as _, Int8Array, ListArray, StringArray}; +use databricks_adbc::{Connection, Driver}; + +fn required_env(name: &str) -> String { + env::var(name).unwrap_or_else(|_| panic!("{name} must be set for ignored live tests")) +} + +fn live_connection() -> Connection { + live_connection_with_options([]) +} + +fn live_connection_with_options( + options: impl IntoIterator, +) -> Connection { + let host = required_env("DATABRICKS_HOST"); + let http_path = required_env("DATABRICKS_HTTP_PATH"); + let token_file = required_env("DATABRICKS_TOKEN_FILE"); + let token = fs::read_to_string(token_file) + .expect("DATABRICKS_TOKEN_FILE must be readable") + .trim() + .to_owned(); + assert!(!token.is_empty(), "DATABRICKS_TOKEN_FILE must not be empty"); + + let mut driver = Driver; + let database = driver + .new_database_with_opts( + [ + (OptionDatabase::Uri, OptionValue::String(host)), + ( + OptionDatabase::Other("adbc.databricks.http_path".to_owned()), + OptionValue::String(http_path), + ), + ( + OptionDatabase::Other("adbc.databricks.auth.token".to_owned()), + OptionValue::String(token), + ), + ] + .into_iter() + .chain(options), + ) + .expect("database configuration should be valid"); + database + .new_connection() + .expect("live connection should open") +} + +#[test] +#[ignore = "requires an explicitly configured live Databricks warehouse"] +fn database_session_aliases_and_complex_types_apply_end_to_end() { + let mut connection = live_connection_with_options([ + ( + OptionDatabase::Other("adbc.databricks.enable_complex_datatype_support".into()), + OptionValue::String("true".into()), + ), + ( + OptionDatabase::Other("adbc.databricks.ssp_ansi_mode".into()), + OptionValue::String("false".into()), + ), + ( + OptionDatabase::Other("adbc.databricks.ssp_timezone".into()), + OptionValue::String("America/Los_Angeles".into()), + ), + ]); + let mut statement = connection.new_statement().expect("create statement"); + statement + .set_sql_query( + "SELECT current_timezone() AS timezone, CAST(128 AS TINYINT) AS wrapped, array(1, 2) AS nested", + ) + .expect("set SQL"); + + let batches = statement + .execute() + .expect("execute option validation query") + .collect::, _>>() + .expect("fetch option validation result"); + assert_eq!(batches.len(), 1); + let batch = &batches[0]; + assert_eq!(batch.num_rows(), 1); + let timezone = batch + .column(0) + .as_any() + .downcast_ref::() + .expect("timezone must be UTF-8"); + assert_eq!(timezone.value(0), "America/Los_Angeles"); + let wrapped = batch + .column(1) + .as_any() + .downcast_ref::() + .expect("non-ANSI TINYINT must retain its numeric Arrow type"); + assert_eq!(wrapped.value(0), -128); + let nested = batch + .column(2) + .as_any() + .downcast_ref::() + .expect("enabled complex datatype support must return a native Arrow list"); + assert_eq!(nested.value_length(0), 2); +} + +#[test] +#[ignore = "requires an explicitly configured live Databricks warehouse"] +fn select_one_fetches_the_complete_result() { + let mut connection = live_connection(); + let mut statement = connection + .new_statement() + .expect("statement should be created"); + statement + .set_sql_query("SELECT 1 AS value") + .expect("query should be accepted"); + + let reader = statement.execute().expect("query should execute"); + let mut batches = 0; + let mut rows = 0; + for batch in reader { + let batch = batch.expect("every result batch should decode"); + assert_eq!(batch.num_columns(), 1); + batches += 1; + rows += batch.num_rows(); + } + assert!(batches >= 1, "SELECT 1 should return a batch"); + assert_eq!(rows, 1, "SELECT 1 should return exactly one row"); +} + +#[test] +#[ignore = "requires an explicitly configured live Databricks warehouse"] +fn namespace_getters_reflect_direct_use_statements() { + let catalog = env::var("DATABRICKS_TEST_CATALOG").unwrap_or_else(|_| "samples".to_owned()); + let schema = env::var("DATABRICKS_TEST_SCHEMA").unwrap_or_else(|_| "tpch".to_owned()); + let mut connection = live_connection(); + let mut statement = connection.new_statement().expect("create statement"); + statement + .set_sql_query(format!("USE CATALOG `{}`", catalog.replace('`', "``"))) + .expect("set catalog SQL"); + statement.execute_update().expect("change catalog"); + statement + .set_sql_query(format!("USE SCHEMA `{}`", schema.replace('`', "``"))) + .expect("set schema SQL"); + statement.execute_update().expect("change schema"); + drop(statement); + + assert_eq!( + connection + .get_option_string(OptionConnection::CurrentCatalog) + .expect("read current catalog"), + catalog + ); + assert_eq!( + connection + .get_option_string(OptionConnection::CurrentSchema) + .expect("read current schema"), + schema + ); +} + +#[test] +#[ignore = "requires an explicitly configured live Databricks warehouse"] +fn direct_results_option_round_trips_and_fetches_synchronously() { + let mut connection = live_connection(); + let mut statement = connection.new_statement().expect("create statement"); + let option = OptionStatement::Other("adbc.databricks.enable_direct_results".into()); + assert_eq!( + statement + .get_option_string(option.clone()) + .expect("read default option"), + "true" + ); + statement + .set_option(option.clone(), OptionValue::String("false".into())) + .expect("disable direct results"); + assert_eq!( + statement + .get_option_string(option.clone()) + .expect("read disabled option"), + "false" + ); + let invalid = statement + .set_option(option.clone(), OptionValue::String("invalid".into())) + .expect_err("reject invalid boolean"); + assert_eq!(invalid.status, adbc_core::error::Status::InvalidArguments); + assert_eq!( + statement + .get_option_string(option) + .expect("invalid update must preserve the prior value"), + "false" + ); + statement.set_sql_query("SELECT 1").expect("set SQL"); + let rows = statement + .execute() + .expect("execute through async kernel path") + .map(|batch| batch.expect("decode result").num_rows()) + .sum::(); + assert_eq!(rows, 1); + + statement + .set_sql_query("SELECT * FROM range(10)") + .expect("set partial-fetch SQL"); + let mut partial = statement.execute().expect("execute partial-fetch query"); + assert!(partial.next().is_some(), "partial result has a first batch"); + drop(partial); + statement + .set_sql_query("SELECT 2") + .expect("reuse statement"); + let reused_rows = statement + .execute() + .expect("execute reused statement") + .map(|batch| batch.expect("decode reused result").num_rows()) + .sum::(); + assert_eq!(reused_rows, 1); +} + +#[test] +#[ignore = "requires an explicitly configured live Databricks warehouse"] +fn metadata_statement_commands_return_canonical_jdbc_shapes() { + let mut connection = live_connection(); + let metadata_catalog = + env::var("DATABRICKS_TEST_CATALOG").unwrap_or_else(|_| "samples".to_owned()); + let cases = [ + ("GetCatalogs", vec!["TABLE_CAT"]), + ("GetSchemas", vec!["TABLE_SCHEM", "TABLE_CATALOG"]), + ( + "GetTables", + vec![ + "TABLE_CAT", + "TABLE_SCHEM", + "TABLE_NAME", + "TABLE_TYPE", + "REMARKS", + "TYPE_CAT", + "TYPE_SCHEM", + "TYPE_NAME", + "SELF_REFERENCING_COL_NAME", + "REF_GENERATION", + ], + ), + ( + "GetColumns", + vec![ + "TABLE_CAT", + "TABLE_SCHEM", + "TABLE_NAME", + "COLUMN_NAME", + "DATA_TYPE", + "TYPE_NAME", + "COLUMN_SIZE", + "BUFFER_LENGTH", + "DECIMAL_DIGITS", + "NUM_PREC_RADIX", + "NULLABLE", + "REMARKS", + "COLUMN_DEF", + "SQL_DATA_TYPE", + "SQL_DATETIME_SUB", + "CHAR_OCTET_LENGTH", + "ORDINAL_POSITION", + "IS_NULLABLE", + "SCOPE_CATALOG", + "SCOPE_SCHEMA", + "SCOPE_TABLE", + "SOURCE_DATA_TYPE", + "IS_AUTO_INCREMENT", + "BASE_TYPE_NAME", + ], + ), + ]; + + for (command, expected_fields) in cases { + let mut statement = connection.new_statement().expect("create statement"); + statement + .set_option( + OptionStatement::Other("adbc.apache.statement.is_metadata_command".into()), + OptionValue::String("true".into()), + ) + .expect("enable metadata command"); + if command != "GetCatalogs" { + statement + .set_option( + OptionStatement::Other("adbc.get_metadata.target_catalog".into()), + OptionValue::String(metadata_catalog.clone()), + ) + .expect("set metadata catalog"); + } + statement.set_sql_query(command).expect("set command"); + let reader = statement.execute().expect("execute metadata command"); + assert_eq!( + reader + .schema() + .fields() + .iter() + .map(|field| field.name().as_str()) + .collect::>(), + expected_fields, + "{command} schema" + ); + } +} + +#[test] +#[ignore = "requires an explicitly configured live Databricks warehouse"] +fn metadata_statement_catalog_underscore_escaping_is_configurable() { + let catalog = required_env("DATABRICKS_TEST_CATALOG"); + assert!( + catalog.contains('_'), + "DATABRICKS_TEST_CATALOG must contain an underscore" + ); + + for (escape_catalog_name, expected_catalogs) in [ + (true, vec![catalog.as_str()]), + (false, vec!["comparator-tests", catalog.as_str()]), + ] { + let mut connection = live_connection_with_options([( + OptionDatabase::Other("adbc.databricks.metadata.escape_catalog_name".into()), + OptionValue::String(escape_catalog_name.to_string()), + )]); + let mut statement = connection.new_statement().expect("create statement"); + statement + .set_option( + OptionStatement::Other("adbc.apache.statement.is_metadata_command".into()), + OptionValue::String("true".into()), + ) + .expect("enable metadata command"); + statement + .set_option( + OptionStatement::Other("adbc.get_metadata.target_catalog".into()), + OptionValue::String(catalog.clone()), + ) + .expect("set metadata catalog"); + statement.set_sql_query("GetTables").expect("set command"); + + let batches = statement + .execute() + .expect("execute metadata command") + .collect::, _>>() + .expect("fetch metadata result"); + let mut actual_catalogs = batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::() + .expect("TABLE_CAT must be UTF-8") + .iter() + .flatten() + .filter(|value| !value.is_empty()) + }) + .collect::>(); + actual_catalogs.sort_unstable(); + actual_catalogs.dedup(); + assert_eq!(actual_catalogs, expected_catalogs); + } +}