From ee9c979795c7016e7843a644b6edf25458eb4221 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Tue, 21 Jul 2026 06:16:13 +0000 Subject: [PATCH] [PECOBLR-2089] Add generic transaction control to Session + C ABI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Transaction control (autocommit / commit / rollback) belongs in the kernel, not in each driver: it is pure engine behavior expressed as session-scoped SQL, identical for every consumer. Centralizing it here means ODBC, Python, Go, and Node all get the same transaction semantics from one implementation (the same rationale as the shared kernel_metadata_* surface). Rust (`Session`): - set_autocommit(bool) / autocommit() / commit() / rollback(). The mutating calls run session-scoped SQL — `SET AUTOCOMMIT = TRUE|FALSE`, `COMMIT`, `ROLLBACK` — via the existing statement path (no result set to drain), mirroring the reference and JDBC drivers. Autocommit is client-tracked in SessionInner (cached, not round-tripped), like JDBC's DatabricksSession. - Gated by DefaultOpts::ignore_transactions (default true = mirror IgnoreTransactions=1): when set, the control methods are silent no-ops; when false, real multi-statement transactions run. Builder shortcut SessionBuilder::ignore_transactions (needed because DefaultOpts is #[non_exhaustive], so external callers can't struct-literal it). C ABI (mirrors the Rust API for all wrappers): - kernel_session_set_autocommit / _get_autocommit / _commit / _rollback. - kernel_session_config_set_ignore_transactions on the config builder. - Header declarations in databricks_kernel.h. Tests: - Unit (wiremock): with ignore_transactions=true the control methods no-op and succeed without issuing any statement (the mock exposes no statement endpoint, so a stray SQL call would fail); DefaultOpts default is true. - e2e (tests/v0_transactions_e2e.rs, #[ignore]): on a catalog-managed table, ignore_transactions=false → autocommit-off + INSERT + ROLLBACK removes the row and COMMIT persists; ignore_transactions=true → calls are no-ops and the auto-committed row survives a ROLLBACK. 703 unit tests pass; cargo fmt + clippy --all-targets clean. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- CHANGELOG.md | 18 ++++ include/databricks_kernel.h | 32 ++++++ src/c_abi/session.rs | 148 ++++++++++++++++++++++++-- src/config.rs | 24 ++++- src/session.rs | 198 +++++++++++++++++++++++++++++++++-- tests/v0_transactions_e2e.rs | 173 ++++++++++++++++++++++++++++++ 6 files changed, 578 insertions(+), 15 deletions(-) create mode 100644 tests/v0_transactions_e2e.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index dedbd5b3..64d4f998 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,24 @@ under [`pyo3/CHANGELOG.md`](pyo3/CHANGELOG.md) and [`napi/CHANGELOG.md`](napi/CHANGELOG.md); they ship on independent cadences and may not move in lockstep with the crate. +## [Unreleased] + +### Added +- **Transaction control on `Session`** — `set_autocommit(bool)` / + `autocommit()` / `commit()` / `rollback()`, exposed over the C ABI as + `kernel_session_set_autocommit` / `_get_autocommit` / `_commit` / + `_rollback`. Implemented as session-scoped SQL (`SET AUTOCOMMIT`, + `COMMIT`, `ROLLBACK`), mirroring the reference/JDBC drivers, so every + wrapper (ODBC / Python / Go / Node) gets identical transaction + semantics from one implementation. Gated by the new + `DefaultOpts::ignore_transactions` (builder shortcut + `SessionBuilder::ignore_transactions`; C ABI + `kernel_session_config_set_ignore_transactions`), which defaults to + `true` — matching the reference/JDBC `IgnoreTransactions=1`: when set, + the control methods are silent no-ops. Set `false` to opt into real + multi-statement transactions (Private Preview; requires catalog-managed + tables server-side). + ## [v0.2.0] - 2026-06-08 **Beta release of the Databricks SQL Kernel.** Bumps the crate out diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index c235cd14..3fe7fde4 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -338,6 +338,14 @@ KernelStatusCode kernel_session_config_set_retry_config(KernelSessionConfig* con uint32_t max_retries, uint64_t overall_timeout_ms); +/* Whether transaction control is ignored (no-oped). `ignore = true` (the + * default) gives IgnoreTransactions=1 semantics: commit / rollback / + * autocommit-off become silent no-ops. `ignore = false` enables real + * multi-statement transactions (Private Preview; requires catalog-managed + * tables server-side). Shared by all drivers (ODBC / Python / Go / Node). */ +KernelStatusCode kernel_session_config_set_ignore_transactions(KernelSessionConfig* config, + bool ignore); + /* ─── Session lifecycle ───────────────────────────────────────────────*/ /* @@ -360,6 +368,30 @@ KernelStatusCode kernel_session_is_open(const kernel_session_t* session, bool* o KernelStatusCode kernel_session_new_statement(kernel_session_t* session, kernel_statement_t** out); +/* ─── Transaction control ───────────────────────────────────────────── + * + * Transaction control is expressed as session-scoped SQL and shared by all + * drivers. When the session was opened with ignore_transactions = true (the + * default), these are silent no-ops returning Success. When false (opt-in), + * they issue SET AUTOCOMMIT / COMMIT / ROLLBACK on the session; real + * multi-statement transactions require catalog-managed tables server-side. + * The three mutating calls run SQL and MUST be invoked from a native + * (non-async-runtime) thread. */ + +/* Set autocommit mode. false begins an explicit transaction; true returns to + * auto-commit. Issues `SET AUTOCOMMIT = TRUE|FALSE`. No-op when transactions + * are ignored. */ +KernelStatusCode kernel_session_set_autocommit(kernel_session_t* session, bool enabled); + +/* Read the current autocommit mode into `*out`. Local read — no round-trip. */ +KernelStatusCode kernel_session_get_autocommit(const kernel_session_t* session, bool* out); + +/* Commit the current transaction (issues `COMMIT`). No-op when ignored. */ +KernelStatusCode kernel_session_commit(kernel_session_t* session); + +/* Roll back the current transaction (issues `ROLLBACK`). No-op when ignored. */ +KernelStatusCode kernel_session_rollback(kernel_session_t* session); + /* ─── Statement ───────────────────────────────────────────────────────*/ /* Set the statement's SQL text, replacing any previously set SQL. Also clears diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 573bbf29..a46b02fd 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -19,8 +19,10 @@ //! `set_auth_u2m`). A host may also drive its own token flow and inject //! it via PAT. //! -//! Transaction methods (autocommit / commit / rollback) are deferred to -//! v0.1 per `docs/spec-v0.md` addendum A5. +//! Transaction control (autocommit / commit / rollback) is exposed via +//! `kernel_session_set_autocommit` / `_get_autocommit` / `_commit` / +//! `_rollback`, gated by `kernel_session_config_set_ignore_transactions` +//! (default = ignore). Backed by the shared `Session` transaction methods. use super::{block_on_ffi, KernelStatusCode}; use crate::config::{AuthConfig, ConnectionConfig, HttpConfig, ProxyConfig, TlsConfig}; @@ -102,6 +104,11 @@ pub struct KernelSessionConfig { /// lets a host make its own backoff/attempt policy authoritative (a /// JDBC-style `RetryWaitMin` / `RetryWaitMax` / `RetryMax` surface). retry: Option, + /// Whether transaction control is ignored (no-oped). Defaults to `true` + /// (matching the reference/JDBC `IgnoreTransactions=1`); a host opts into + /// real transactions via `kernel_session_config_set_ignore_transactions` + /// with `false`. Maps to [`DefaultOpts::ignore_transactions`]. + ignore_transactions: bool, } /// C-side proxy config captured from `kernel_session_config_set_proxy`. @@ -177,6 +184,8 @@ pub unsafe extern "C" fn kernel_session_config_new( tls: TlsSpec::default(), custom_headers: Vec::new(), retry: None, + // Default to ignoring transactions, matching IgnoreTransactions=1. + ignore_transactions: true, }); std::ptr::write(out, Box::into_raw(config)); KernelStatusCode::Success @@ -590,6 +599,26 @@ pub unsafe extern "C" fn kernel_session_config_set_tls_skip_hostname_verificatio }) } +/// Set whether transaction control is ignored (no-oped). Pass `true` +/// (the default) for `IgnoreTransactions=1` semantics — `SQLEndTran` / +/// commit / rollback / autocommit-off become silent no-ops. Pass `false` +/// to enable real multi-statement transactions (Private Preview; requires +/// catalog-managed tables server-side). Maps to +/// [`DefaultOpts::ignore_transactions`]. +/// +/// # Safety +/// `config` must be a live config handle. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_ignore_transactions( + config: *mut KernelSessionConfig, + ignore: bool, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.ignore_transactions = ignore; + Ok(()) + }) +} + /// Shared body for the config setters: null-check the handle, clear the /// thread-local error, run `f` against the borrowed config, and store /// any error. @@ -722,6 +751,7 @@ fn build_session(config: KernelSessionConfig) -> Result Result KernelStatusCode; -// pub unsafe extern "C" fn kernel_session_commit(...) -> KernelStatusCode; -// pub unsafe extern "C" fn kernel_session_rollback(...) -> KernelStatusCode; +/// Set autocommit mode on the session. `enabled = false` begins explicit +/// transaction mode (subsequent statements run in a transaction until +/// `kernel_session_commit` / `kernel_session_rollback`); `true` returns to +/// auto-commit. Issues `SET AUTOCOMMIT = TRUE|FALSE` on the server. +/// +/// A no-op returning `Success` when the session was configured with +/// `ignore_transactions = true` (the default). Must be called from a +/// native (non-async-runtime) thread. +/// +/// # Safety +/// `session` must be a live session handle from [`kernel_session_open`]. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_set_autocommit( + session: *mut kernel_session_t, + enabled: bool, +) -> KernelStatusCode { + crate::c_abi::error::clear_error(); + let Some(session) = (session as *const Session).as_ref() else { + crate::c_abi::error::store_error( + Error::invalid_argument() + .message("kernel_session_set_autocommit: session must not be null"), + ); + return KernelStatusCode::InvalidArgument; + }; + match block_on_ffi(|| session.set_autocommit(enabled)) { + Ok(()) => KernelStatusCode::Success, + Err(code) => code, + } +} + +/// Read the session's current autocommit mode into `*out`. Local read — no +/// server round-trip. +/// +/// # Safety +/// `session` must be a live session handle; `out` must be a writable `bool*`. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_get_autocommit( + session: *const kernel_session_t, + out: *mut bool, +) -> KernelStatusCode { + crate::c_abi::error::clear_error(); + let Some(session) = (session as *const Session).as_ref() else { + crate::c_abi::error::store_error( + Error::invalid_argument() + .message("kernel_session_get_autocommit: session must not be null"), + ); + return KernelStatusCode::InvalidArgument; + }; + if out.is_null() { + crate::c_abi::error::store_error( + Error::invalid_argument() + .message("kernel_session_get_autocommit: out must not be null"), + ); + return KernelStatusCode::InvalidArgument; + } + std::ptr::write(out, session.autocommit()); + KernelStatusCode::Success +} + +/// Commit the current transaction (issues `COMMIT`). A no-op returning +/// `Success` when the session has `ignore_transactions = true`. Must be +/// called from a native (non-async-runtime) thread. +/// +/// # Safety +/// `session` must be a live session handle from [`kernel_session_open`]. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_commit(session: *mut kernel_session_t) -> KernelStatusCode { + crate::c_abi::error::clear_error(); + let Some(session) = (session as *const Session).as_ref() else { + crate::c_abi::error::store_error( + Error::invalid_argument().message("kernel_session_commit: session must not be null"), + ); + return KernelStatusCode::InvalidArgument; + }; + match block_on_ffi(|| session.commit()) { + Ok(()) => KernelStatusCode::Success, + Err(code) => code, + } +} + +/// Roll back the current transaction (issues `ROLLBACK`). A no-op returning +/// `Success` when the session has `ignore_transactions = true`. Requires +/// catalog-managed tables server-side for the rollback to take effect. Must +/// be called from a native (non-async-runtime) thread. +/// +/// # Safety +/// `session` must be a live session handle from [`kernel_session_open`]. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_rollback( + session: *mut kernel_session_t, +) -> KernelStatusCode { + crate::c_abi::error::clear_error(); + let Some(session) = (session as *const Session).as_ref() else { + crate::c_abi::error::store_error( + Error::invalid_argument().message("kernel_session_rollback: session must not be null"), + ); + return KernelStatusCode::InvalidArgument; + }; + match block_on_ffi(|| session.rollback()) { + Ok(()) => KernelStatusCode::Success, + Err(code) => code, + } +} #[cfg(test)] mod tests { diff --git a/src/config.rs b/src/config.rs index ad3b414b..85a7e93b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -173,10 +173,32 @@ fn parse_org_id(http_path: &str) -> Option { /// Optional: per-session defaults applied to statements that don't /// override. #[non_exhaustive] -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone)] pub struct DefaultOpts { pub catalog: Option, pub schema: Option, + + /// When `true` (the default), transaction-control operations are + /// silently no-oped: `Session::set_autocommit(false)`, + /// `Session::commit()`, and `Session::rollback()` return `Ok(())` + /// without issuing any server statement. Mirrors the reference/JDBC + /// `IgnoreTransactions` connection property, whose default is `1` + /// (transactions disabled). Set to `false` to opt into real + /// multi-statement transactions (a Private Preview feature; requires + /// catalog-managed tables server-side). + pub ignore_transactions: bool, +} + +impl Default for DefaultOpts { + fn default() -> Self { + Self { + catalog: None, + schema: None, + // Match the reference/JDBC default of IgnoreTransactions=1: + // transaction control is no-oped unless a caller opts in. + ignore_transactions: true, + } + } } // ─── Authentication ───────────────────────────────────────────────────────── diff --git a/src/session.rs b/src/session.rs index 33fe926d..6f9e2598 100644 --- a/src/session.rs +++ b/src/session.rs @@ -36,12 +36,14 @@ //! //! ## Transactions //! -//! Multi-statement transaction methods (`set_autocommit` / `commit` / -//! `rollback`) are intentionally **omitted** in v0. The Databricks -//! server-side semantics for autocommit are still being settled, and -//! we prefer to leave the surface unspecified rather than ship a -//! signature we may need to reshape. The methods will be added once -//! the server contract stabilises. +//! Multi-statement transaction control (`set_autocommit` / `commit` / +//! `rollback`) is expressed as session-scoped SQL (`SET AUTOCOMMIT`, +//! `COMMIT`, `ROLLBACK`), mirroring the reference and JDBC drivers, and +//! is shared by every wrapper via the C ABI. It is gated by +//! [`DefaultOpts::ignore_transactions`] (default = ignore, matching +//! `IgnoreTransactions=1`): when ignored, the methods are no-ops; when +//! enabled, they drive real transactions (a Private Preview feature that +//! requires catalog-managed tables server-side). use crate::auth::{ AuthProvider, AuthorizationCodeProvider, ClientCredentialsProvider, PersonalAccessToken, @@ -110,6 +112,24 @@ pub(crate) struct SessionInner { /// transient `delete_session` failures don't leak the server- /// side session. closed: std::sync::atomic::AtomicBool, + + /// Client-tracked autocommit state. `true` (the default) means every + /// statement auto-commits at the server; `false` means statements run + /// inside an explicit transaction until [`Session::commit`] / + /// [`Session::rollback`]. Toggled by [`Session::set_autocommit`], which + /// also issues the corresponding `SET AUTOCOMMIT` statement to the + /// server. Cached here (rather than round-tripped on every read), + /// mirroring the JDBC driver's `DatabricksSession.autoCommit`. + autocommit: std::sync::atomic::AtomicBool, + + /// When `true`, transaction-control operations ([`Session::set_autocommit`] + /// with `false`, [`Session::commit`], [`Session::rollback`]) are silently + /// no-oped — they return `Ok(())` without issuing any server statement. + /// Mirrors the reference/JDBC `IgnoreTransactions` connection property + /// (default = ignore); drivers pass it through via + /// [`DefaultOpts::ignore_transactions`]. Multi-statement transactions are + /// a Private Preview feature; setting this `false` opts in. + ignore_transactions: bool, } impl SessionInner { @@ -353,6 +373,10 @@ impl Session { runtime_handle, log_span, closed: std::sync::atomic::AtomicBool::new(false), + // Autocommit defaults to on (every statement commits); a + // caller opts into explicit transactions via set_autocommit. + autocommit: std::sync::atomic::AtomicBool::new(true), + ignore_transactions: defaults.ignore_transactions, }), }) } @@ -370,6 +394,92 @@ impl Session { Metadata::new(Arc::clone(&self.inner)) } + // ─── Transaction control ──────────────────────────────────────────── + // + // Transaction control is expressed as session-scoped SQL, matching the + // reference and JDBC drivers: set_autocommit → `SET AUTOCOMMIT`, + // commit → `COMMIT`, rollback → `ROLLBACK`. These run on this session + // so the server keeps the transaction context across statements. + // Autocommit state is client-tracked (cached in SessionInner) rather + // than round-tripped on every read. When the session was built with + // `ignore_transactions = true` (the default, mirroring + // `IgnoreTransactions=1`), these are silent no-ops. Centralising this + // here means every C-ABI consumer (ODBC / Python / Go / Node) gets + // identical transaction semantics from one implementation. + + /// Current autocommit mode. `true` (default) = each statement commits + /// immediately; `false` = statements run in an explicit transaction + /// until [`commit`](Self::commit) / [`rollback`](Self::rollback). This + /// is a local read (no server round-trip). + pub fn autocommit(&self) -> bool { + self.inner + .autocommit + .load(std::sync::atomic::Ordering::Acquire) + } + + /// Set autocommit mode. Issues `SET AUTOCOMMIT = TRUE|FALSE` on the + /// server and, on success, caches the new state. Setting `false` + /// begins explicit-transaction mode; setting `true` returns to + /// auto-commit (committing any open transaction, per server + /// semantics). + /// + /// No-op returning `Ok(())` when the session has `ignore_transactions` + /// set (transactions disabled) — the state is not changed and no + /// statement is sent. This mirrors the reference/JDBC behavior under + /// `IgnoreTransactions=1`. + pub async fn set_autocommit(&self, enabled: bool) -> Result<()> { + if self.inner.ignore_transactions { + return Ok(()); + } + self.run_txn_statement(if enabled { + "SET AUTOCOMMIT = TRUE" + } else { + "SET AUTOCOMMIT = FALSE" + }) + .await?; + self.inner + .autocommit + .store(enabled, std::sync::atomic::Ordering::Release); + Ok(()) + } + + /// Commit the current transaction by issuing `COMMIT`. No-op returning + /// `Ok(())` when `ignore_transactions` is set. On a server with no open + /// transaction (e.g. autocommit still on) the server decides the + /// outcome; the kernel surfaces any error unchanged. + pub async fn commit(&self) -> Result<()> { + if self.inner.ignore_transactions { + return Ok(()); + } + self.run_txn_statement("COMMIT").await + } + + /// Roll back the current transaction by issuing `ROLLBACK`. No-op + /// returning `Ok(())` when `ignore_transactions` is set. Requires + /// catalog-managed tables server-side for the rollback to take effect. + pub async fn rollback(&self) -> Result<()> { + if self.inner.ignore_transactions { + return Ok(()); + } + self.run_txn_statement("ROLLBACK").await + } + + /// Run a transaction-control statement (`SET AUTOCOMMIT` / `COMMIT` / + /// `ROLLBACK`) to completion on this session and discard its result. + /// These statements return no result set, so we execute and drop the + /// executed handle (its `Drop` closes the server statement). Errors + /// propagate through the normal `KernelError` taxonomy. + async fn run_txn_statement(&self, sql: &'static str) -> Result<()> { + let span = self.inner.log_span().clone(); + async { + let mut stmt = self.statement(); + stmt.spec().sql(sql); + stmt.execute().await.map(|_executed| ()) + } + .instrument(span) + .await + } + /// Initiate the fire-and-forget server-side `DeleteSession` now, /// without awaiting it or consuming `self`. Idempotent. Used by the C /// ABI's `kernel_session_close` so the delete is initiated on close @@ -604,6 +714,21 @@ impl SessionBuilder { self } + /// Whether transaction control is ignored (no-oped). `true` (the + /// default) matches the reference/JDBC `IgnoreTransactions=1`; `false` + /// enables real multi-statement transactions (Private Preview). + /// + /// A convenience over [`Self::defaults`] for the common case of + /// toggling only this flag — and the supported way to set it from + /// outside the crate, since [`DefaultOpts`] is `#[non_exhaustive]`. + /// Merges into any `DefaultOpts` already supplied via `defaults`. + pub fn ignore_transactions(mut self, ignore: bool) -> Self { + let mut d = self.defaults.take().unwrap_or_default(); + d.ignore_transactions = ignore; + self.defaults = Some(d); + self + } + /// HTTP client tuning — request / overall timeouts, connection-pool /// size. Defaults are sane for typical workloads. pub fn http(mut self, http: HttpConfig) -> Self { @@ -1326,4 +1451,65 @@ mod is_open_tests { "after initiate_delete the session must report not-open" ); } + + #[test] + fn default_opts_ignore_transactions_defaults_to_true() { + // Matches the reference/JDBC IgnoreTransactions=1 default. + assert!(DefaultOpts::default().ignore_transactions); + } + + /// With ignore_transactions = true (default), the transaction-control + /// methods are no-ops: they return Ok WITHOUT issuing any statement. + /// The mock server exposes ONLY session create/delete — no statement + /// endpoint — so any attempt to run `SET AUTOCOMMIT`/`COMMIT`/`ROLLBACK` + /// SQL would fail. Their success here proves the no-op short-circuit. + #[tokio::test] + async fn transaction_controls_are_noop_when_ignored() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(r#"{"session_id":"sess-txn","warehouse_id":"test_wh"}"#), + ) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/sessions/sess-txn")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + + let session = Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") + .expect("valid http_path"), + ) + .auth(AuthConfig::Pat { + token: "dapi_test_token".into(), + }) + // ignore_transactions defaults to true; be explicit for the test. + .defaults(DefaultOpts { + ignore_transactions: true, + ..Default::default() + }) + .open() + .await + .expect("session must open"); + + assert!(session.autocommit(), "default autocommit is on"); + // All three no-op and succeed without hitting a (non-existent) + // statement endpoint. + session + .set_autocommit(false) + .await + .expect("set_autocommit no-op"); + session.commit().await.expect("commit no-op"); + session.rollback().await.expect("rollback no-op"); + // State unchanged because the set was ignored. + assert!( + session.autocommit(), + "autocommit must stay on when transactions are ignored" + ); + } } diff --git a/tests/v0_transactions_e2e.rs b/tests/v0_transactions_e2e.rs new file mode 100644 index 00000000..ee6df3ae --- /dev/null +++ b/tests/v0_transactions_e2e.rs @@ -0,0 +1,173 @@ +// 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. + +//! End-to-end tests for transaction control (`Session::set_autocommit` / +//! `commit` / `rollback`) against a live Databricks workspace. +//! +//! Real multi-statement transactions require a catalog-managed table +//! (`USING DELTA TBLPROPERTIES ('delta.feature.catalogManaged' = 'supported')`) +//! and a schema the test principal can create in. The test uses +//! `main.oss_odbc_probe` and skips (rather than fails) if it can't create there. +//! +//! Run with: +//! +//! ```sh +//! set -a && source ~/.databricks/pecotesting-creds && set +a +//! cargo test --test v0_transactions_e2e -- --ignored +//! ``` + +use databricks_sql_kernel::{AuthConfig, ResultStream, Session}; +use std::env; + +const SCHEMA: &str = "main.oss_odbc_probe"; +const TABLE: &str = "main.oss_odbc_probe.kernel_txn_test"; + +fn env_var(key: &str) -> Option { + env::var(key).ok().filter(|v| !v.is_empty()) +} + +async fn live_session(ignore_transactions: bool) -> Session { + let host = env_var("DATABRICKS_HOST").expect("DATABRICKS_HOST required"); + let path = env_var("DATABRICKS_HTTP_PATH").expect("DATABRICKS_HTTP_PATH required"); + let token = env_var("DATABRICKS_TOKEN").expect("DATABRICKS_TOKEN required"); + + Session::builder() + .http_path(host, path) + .auth(AuthConfig::Pat { token }) + .ignore_transactions(ignore_transactions) + .open() + .await + .expect("Session::open against live workspace") +} + +/// Run a statement to completion, discarding its result. Returns Err on +/// failure so callers can decide to skip vs. assert. +async fn run(session: &Session, sql: &str) -> databricks_sql_kernel::Result<()> { + let mut stmt = session.statement(); + stmt.spec().sql(sql); + stmt.execute().await.map(|_| ()) +} + +async fn count(session: &Session) -> i64 { + let mut stmt = session.statement(); + stmt.spec().sql(format!("SELECT COUNT(*) FROM {TABLE}")); + let mut exec = stmt.execute().await.expect("count query"); + let stream: &mut ResultStream = exec.result_stream_mut(); + stream.next_batch().await.unwrap().unwrap(); + let row = stream.next_row_in_batch().expect("one row"); + row.get_i64(0).unwrap().unwrap_or(0) +} + +/// Create the catalog-managed test table; returns false (→ skip) if the +/// principal lacks CREATE on the schema or the table type is unsupported. +async fn setup_table(session: &Session) -> bool { + if run(session, &format!("CREATE SCHEMA IF NOT EXISTS {SCHEMA}")) + .await + .is_err() + { + eprintln!("skip: cannot create schema {SCHEMA}"); + return false; + } + let create = format!( + "CREATE TABLE IF NOT EXISTS {TABLE} (id INT) USING DELTA \ + TBLPROPERTIES ('delta.feature.catalogManaged' = 'supported')" + ); + if run(session, &create).await.is_err() { + eprintln!("skip: cannot create catalog-managed table {TABLE}"); + return false; + } + run(session, &format!("DELETE FROM {TABLE}")) + .await + .expect("clear table"); + true +} + +/// With ignore_transactions = false, ROLLBACK must actually undo an insert +/// on a catalog-managed table. +#[tokio::test] +#[ignore] +async fn rollback_undoes_insert_when_transactions_enabled() { + let session = live_session(/* ignore_transactions = */ false).await; + if !setup_table(&session).await { + return; // environment can't host the test; skip. + } + + assert_eq!(count(&session).await, 0, "table should start empty"); + + session + .set_autocommit(false) + .await + .expect("set_autocommit(false)"); + assert!(!session.autocommit(), "autocommit should be off"); + + run(&session, &format!("INSERT INTO {TABLE} VALUES (777)")) + .await + .expect("insert"); + + session.rollback().await.expect("rollback"); + assert_eq!( + count(&session).await, + 0, + "ROLLBACK must undo the insert when transactions are enabled" + ); + + // COMMIT path: insert then commit persists. + run(&session, &format!("INSERT INTO {TABLE} VALUES (888)")) + .await + .expect("insert 2"); + session.commit().await.expect("commit"); + assert_eq!(count(&session).await, 1, "COMMIT must persist the insert"); + + // Cleanup. + run(&session, &format!("DELETE FROM {TABLE}")).await.ok(); + session.commit().await.ok(); + session.close().await.expect("session close"); +} + +/// With ignore_transactions = true (the default), the control calls are +/// no-ops: they succeed but do not begin a transaction, so an insert is +/// auto-committed and a subsequent ROLLBACK does nothing. +#[tokio::test] +#[ignore] +async fn transactions_are_noop_when_ignored() { + let session = live_session(/* ignore_transactions = */ true).await; + if !setup_table(&session).await { + return; + } + + // No-ops all succeed. + session + .set_autocommit(false) + .await + .expect("set_autocommit no-op"); + // Autocommit state is unchanged (still reports the default `true`), + // because the call was ignored. + assert!( + session.autocommit(), + "autocommit should stay true when transactions are ignored" + ); + + run(&session, &format!("INSERT INTO {TABLE} VALUES (999)")) + .await + .expect("insert"); + session.rollback().await.expect("rollback no-op"); + assert_eq!( + count(&session).await, + 1, + "ROLLBACK is a no-op when transactions are ignored — the auto-committed row survives" + ); + + run(&session, &format!("DELETE FROM {TABLE}")).await.ok(); + session.close().await.expect("session close"); +}