diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index c7fc0905..cf42e4e6 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -327,9 +327,16 @@ KernelStatusCode kernel_session_new_statement(kernel_session_t* session, /* ─── Statement ───────────────────────────────────────────────────────*/ +/* Set the statement's SQL text, replacing any previously set SQL. Also clears + * every previously-bound parameter (raw and the typed positional binders below), + * so a reused statement handle starts each query with a fresh parameter set. */ KernelStatusCode kernel_statement_set_sql(kernel_statement_t* stmt, const char* sql); -/* Positional parameter binding (1-based ordinal). */ +/* Typed positional parameter binding (1-based ordinal); the kernel infers the + * SEA wire type from the C type. These are the "typed params" the + * kernel_statement_bind_parameter contract refers to: within one statement they + * cannot be combined with kernel_statement_bind_parameter (raw binds) — pick one + * binding style. The conflict is reported at kernel_statement_execute, not here. */ KernelStatusCode kernel_statement_bind_null(kernel_statement_t* stmt, size_t ordinal); KernelStatusCode kernel_statement_bind_int64(kernel_statement_t* stmt, size_t ordinal, int64_t value); @@ -339,6 +346,32 @@ KernelStatusCode kernel_statement_bind_bool(kernel_statement_t* stmt, size_t ord KernelStatusCode kernel_statement_bind_string(kernel_statement_t* stmt, size_t ordinal, const char* value); +/* Bind a pre-marshalled parameter: host-supplied Databricks type name + + * stringified value, positional or named. For a host that already stringifies + * values and knows the SQL type (e.g. the Go driver). name NULL/empty -> + * positional (ordinal assigned at execute in push order); non-empty -> named. + * value NULL -> SQL NULL (pass sql_type "VOID"); sql_type must be non-NULL and + * non-empty (an empty type is rejected here with InvalidArgument). + * + * Lifecycle: raw binds ACCUMULATE (each call appends a marker in push order); + * they carry no ordinal to overwrite by. kernel_statement_set_sql is the sole + * reset point — it clears ALL prior binds (raw AND the typed positional binders + * below) so each set_sql begins a fresh parameter set. kernel_statement_execute + * does NOT clear them, so a host reusing one statement handle across queries must + * call set_sql before re-binding, or the prior query's markers persist and the + * server sees the wrong parameter count. + * + * Two mutual-exclusion rules hold within one statement, both enforced at + * kernel_statement_execute (this call always returns Success on a valid + * arg — the conflict surfaces later as InvalidArgument from execute): + * - positional and named raw params cannot be mixed; + * - raw params cannot be mixed with the typed positional binders + * (kernel_statement_bind_null/int64/double/bool/string above). */ +KernelStatusCode kernel_statement_bind_parameter(kernel_statement_t* stmt, + const char* name, + const char* sql_type, + const char* value); + /* * Wait-for-result execution. On success, `*out` holds an executed handle * released with `kernel_executed_statement_close`. @@ -466,6 +499,17 @@ KernelStatusCode kernel_executed_statement_get_result_stream(kernel_executed_sta */ int64_t kernel_executed_statement_num_modified_rows(const kernel_executed_statement_t* exec); +/* + * Server statement (query) id of a successfully executed statement, as a + * NUL-terminated C string — the success-path counterpart to the query id on + * KernelError. Used by a host driver for EXECUTE_STATEMENT telemetry and + * query-history correlation. The pointer is BORROWED from the executed handle, + * valid until kernel_executed_statement_close; do NOT free it, and copy it out + * to outlive the handle. Returns NULL on a null / invalidated handle (with a + * stored last error); a live handle from a successful execute never returns NULL. + */ +const char* kernel_executed_statement_query_id(const kernel_executed_statement_t* exec); + KernelStatusCode kernel_executed_statement_close(kernel_executed_statement_t* exec); /* ─── Result stream ─────────────────────────────────────────────────── diff --git a/src/c_abi/error.rs b/src/c_abi/error.rs index 28503f4b..fac4834e 100644 --- a/src/c_abi/error.rs +++ b/src/c_abi/error.rs @@ -75,7 +75,11 @@ thread_local! { /// Turn a Rust `String` into a `CString`, replacing any interior NUL /// bytes with `?` so a message that happens to contain `\0` can't make /// `CString::new` fail (which would lose the error detail entirely). -fn to_cstring_lossy(s: &str) -> CString { +/// +/// Shared by the error-path `KernelError.query_id` and the success-path +/// `kernel_executed_statement_query_id`, so both accessors have identical +/// interior-NUL semantics (strip → `?`, never discard the whole value). +pub(crate) fn to_cstring_lossy(s: &str) -> CString { // Fast path: no interior NUL. match CString::new(s) { Ok(c) => c, diff --git a/src/c_abi/statement.rs b/src/c_abi/statement.rs index 89466d8a..4ec007f1 100644 --- a/src/c_abi/statement.rs +++ b/src/c_abi/statement.rs @@ -43,7 +43,7 @@ use crate::statement::executed::ExecutedStatement; use crate::statement::mutable::Statement; use crate::statement::spec::TypedValue; use crate::statement::validity::ValidityFlag; -use std::ffi::{c_char, CStr}; +use std::ffi::{c_char, CStr, CString}; /// Upper bound on a positional parameter ordinal accepted over the C ABI. /// @@ -77,6 +77,15 @@ pub(crate) struct ExecutedHandle { pub(crate) exec: ExecutedStatement, pub(crate) alive: ValidityFlag, pub(crate) stream_taken: std::sync::atomic::AtomicBool, + /// The server statement id as a NUL-terminated C string, built once at + /// construction so `kernel_executed_statement_query_id` can hand back a + /// borrowed `*const c_char` valid for the handle's lifetime (no per-call + /// allocation, nothing for the caller to free). Any interior NUL is + /// stripped (replaced with `?`) via `to_cstring_lossy` — the same semantics + /// as the error-path `KernelError.query_id` — so the two query-id paths + /// agree. A statement id is a server-generated UUID, so this never occurs in + /// practice. + pub(crate) statement_id_c: CString, } // ─── Opaque handles ────────────────────────────────────────────────────────── @@ -153,7 +162,10 @@ unsafe fn statement_mut<'a>(stmt: *mut kernel_statement_t) -> Option<&'a mut Sta // ─── SQL + parameter binding ───────────────────────────────────────────────── -/// Set the statement's SQL text, replacing any previously set SQL. +/// Set the statement's SQL text, replacing any previously set SQL. Also clears +/// every previously-bound parameter (raw and typed), so a reused statement +/// handle begins each query with a fresh parameter set — see +/// [`crate::statement::spec::StatementSpec::sql`]. /// /// # Safety /// `stmt` must be a live statement handle; `sql` must be a @@ -253,6 +265,77 @@ pub unsafe extern "C" fn kernel_statement_bind_string( }) } +/// Bind a pre-marshalled parameter: host-supplied Databricks type name + +/// stringified value, positional or named. This is the binding path for a host +/// driver that already stringifies values and knows the SQL type (e.g. the Go +/// driver's `backend.Param{Name, Type, Value}`) — it avoids round-tripping +/// through the kernel's `TypedValue` inference. +/// +/// - `name`: NULL/empty → positional (ordinal assigned at execute in push +/// order); non-empty → named (`:name` marker). +/// - `sql_type`: Databricks type name (e.g. "BIGINT", "STRING", "DECIMAL(5,2)"). +/// For a NULL value the host passes "VOID" (matches the driver convention). +/// - `value`: NULL → SQL NULL; otherwise the stringified value sent verbatim. +/// +/// Positional and named raw params are mutually exclusive within one statement +/// (enforced at execute), as are raw vs TypedValue params. +/// +/// # Safety +/// `stmt` must be a live statement handle; `sql_type` must be a NUL-terminated C +/// string; `name`/`value` are NUL-terminated C strings or NULL. +#[no_mangle] +pub unsafe extern "C" fn kernel_statement_bind_parameter( + stmt: *mut kernel_statement_t, + name: *const c_char, + sql_type: *const c_char, + value: *const c_char, +) -> KernelStatusCode { + with_statement(stmt, |stmt| { + if sql_type.is_null() { + return Err(Error::invalid_argument().message("parameter sql_type must not be null")); + } + let sql_type = CStr::from_ptr(sql_type) + .to_str() + .map_err(|_| { + Error::invalid_argument().message("parameter sql_type is not valid UTF-8") + })? + .to_owned(); + // Reject an empty type here rather than letting it reach the wire as + // `"type":""` and surface as an opaque server BAD_REQUEST at execute — + // symmetric with the NULL guard above and with param_named rejecting an + // empty name (a bind-time typed error beats a wire-level rejection). + if sql_type.is_empty() { + return Err(Error::invalid_argument().message("parameter sql_type must not be empty")); + } + let name_opt = if name.is_null() { + None + } else { + let s = CStr::from_ptr(name).to_str().map_err(|_| { + Error::invalid_argument().message("parameter name is not valid UTF-8") + })?; + if s.is_empty() { + None + } else { + Some(s.to_owned()) + } + }; + let value_opt = if value.is_null() { + None + } else { + Some( + CStr::from_ptr(value) + .to_str() + .map_err(|_| { + Error::invalid_argument().message("parameter value is not valid UTF-8") + })? + .to_owned(), + ) + }; + stmt.spec().param_raw(name_opt, sql_type, value_opt); + Ok(()) + }) +} + /// Shared body for the scalar `bind_*` setters. /// /// # Safety @@ -326,10 +409,20 @@ pub unsafe extern "C" fn kernel_statement_execute( }); match executed { Ok(exec) => { + // Snapshot the server statement id as a C string now, while the exec + // handle is fresh, so the query-id accessor is a borrow with no + // allocation. `to_cstring_lossy` strips any interior NUL (→ `?`) + // rather than discarding the whole id — never happens for a + // server-generated UUID, but keeps this success-path id and the + // error-path `KernelError.query_id` on identical NUL semantics, and + // guarantees the accessor stays non-NULL for any live handle per its + // header contract. + let statement_id_c = crate::c_abi::error::to_cstring_lossy(exec.statement_id()); let handle = ExecutedHandle { exec, alive: ValidityFlag::new(), stream_taken: std::sync::atomic::AtomicBool::new(false), + statement_id_c, }; std::ptr::write( out, @@ -593,6 +686,43 @@ pub unsafe extern "C" fn kernel_executed_statement_num_modified_rows( handle.exec.num_modified_rows().unwrap_or(-1) } +/// The server statement (query) id of a successfully executed statement, as a +/// NUL-terminated C string. This is the success-path counterpart to the query id +/// on `KernelError` (which crosses only on failure): a host driver uses it for +/// EXECUTE_STATEMENT telemetry and query-history correlation. +/// +/// The returned pointer is **borrowed** from the executed handle and valid until +/// the handle is closed (`kernel_executed_statement_close`); the caller must NOT +/// free it and should copy it out if it needs to outlive the handle. Returns +/// NULL on a null or invalidated handle (with a stored last error). A successful +/// execute always has an id, so a live handle never returns NULL. +/// +/// # Safety +/// `exec` must be a live executed handle from [`kernel_statement_execute`]. +#[no_mangle] +pub unsafe extern "C" fn kernel_executed_statement_query_id( + exec: *const kernel_executed_statement_t, +) -> *const c_char { + crate::c_abi::error::clear_error(); + let Some(handle) = (exec as *const ExecutedHandle).as_ref() else { + crate::c_abi::error::store_invalid_arg( + "kernel_executed_statement_query_id: exec must not be null", + ); + return std::ptr::null(); + }; + // Stale after a re-execute or close on the parent statement → NULL with a + // stored InvalidStatementHandle, matching num_modified_rows' staleness rule. + if !handle.exec.is_valid() { + crate::c_abi::error::store_and_code(Error::new( + crate::kernel_error::ErrorCode::InvalidStatementHandle, + "executed statement was invalidated by a re-execute or close on its parent statement; \ + read query_id before closing the statement", + )); + return std::ptr::null(); + } + handle.statement_id_c.as_ptr() +} + /// Free a sync executed handle. Invalidates any result stream borrowed /// from it before dropping (so a stream outliving its handle fails /// cleanly rather than dereferencing freed memory). diff --git a/src/statement/executed.rs b/src/statement/executed.rs index ab496894..b8717e75 100644 --- a/src/statement/executed.rs +++ b/src/statement/executed.rs @@ -262,6 +262,16 @@ impl ExecutedStatement { pub fn error_details_json(&self) -> Option<&str> { self.status.error_details_json.as_deref() } + + /// The server statement id assigned to this executed statement. This is the + /// correlation handle to server-side query history, and the id a C-ABI host + /// (e.g. the Go driver) surfaces on the success path for EXECUTE_STATEMENT + /// telemetry. Same value the `ExecutedStatementHandle` trait exposes; + /// duplicated as an inherent accessor so consumers holding a concrete + /// `ExecutedStatement` need not import the trait. + pub fn statement_id(&self) -> &str { + &self.statement_id + } } #[async_trait] diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 3e2f252e..e7889ef0 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -150,6 +150,14 @@ fn build_execute_params( return Err(Error::invalid_argument() .message("positional and named parameters are mutually exclusive; pass only one")); } + // raw_params (the C-ABI host-marshalled path) is mutually exclusive with the + // TypedValue paths — a host uses one binding style per statement. + if !spec.raw_params.is_empty() + && (!spec.positional_params.is_empty() || !spec.named_params.is_empty()) + { + return Err(Error::invalid_argument() + .message("raw parameters cannot be mixed with positional/named TypedValue params")); + } let (wait_timeout, on_wait_timeout) = resolve_wait_timeout(wait_timeout_secs); let mut exec_params = ExecuteParams { wait_timeout, @@ -167,6 +175,28 @@ fn build_execute_params( .parameters .push(named_typed_value_to_sea_parameter(name.clone(), value)?); } + // Raw (host-marshalled) params: emit verbatim. Positional entries (name + // None) get a 1-based ordinal in push order; named entries pass through. + // Positional and named raw params are mutually exclusive for the same reason + // TypedValue ones are (the SEA server rejects a mixed markers array). + { + let has_named_raw = spec.raw_params.iter().any(|p| p.name.is_some()); + let has_pos_raw = spec.raw_params.iter().any(|p| p.name.is_none()); + if has_named_raw && has_pos_raw { + return Err(Error::invalid_argument().message( + "positional and named raw parameters are mutually exclusive; pass only one", + )); + } + let mut ordinal = 0i32; + for p in spec.raw_params.iter() { + let mut param = p.clone(); + if param.name.is_none() { + ordinal += 1; + param.ordinal = Some(ordinal); + } + exec_params.parameters.push(param); + } + } // Per-statement query tags: both `Statement::query_tags` and a raw // `statement_conf["query_tags"]` land in the serialized conf string; // the SEA wire wants the native `[{key, value}]` array, so convert here. @@ -966,4 +996,104 @@ mod tests { err.message ); } + + #[test] + fn build_execute_params_binds_raw_positional_params_one_based() { + // The C-ABI raw-bind path (kernel_statement_bind_parameter with no name): + // ordinals are assigned 1-based in push order, the host's type name and + // string value pass through verbatim. + let mut spec = StatementSpec::new(); + spec.sql("SELECT ?, ?"); + spec.param_raw(None, "BIGINT", Some("7".to_owned())); + spec.param_raw(None, "STRING", Some("hi".to_owned())); + let (_, params) = build_execute_params(&spec, None).unwrap(); + assert_eq!(params.parameters.len(), 2); + assert_eq!(params.parameters[0].ordinal, Some(1)); + assert_eq!(params.parameters[0].param_type, "BIGINT"); + assert_eq!(params.parameters[0].value.as_deref(), Some("7")); + assert!(params.parameters[0].name.is_none()); + assert_eq!(params.parameters[1].ordinal, Some(2)); + assert_eq!(params.parameters[1].value.as_deref(), Some("hi")); + } + + #[test] + fn build_execute_params_binds_raw_named_and_null() { + // A named raw param passes its name through; a NULL value is bound as + // type VOID with no value (the host convention for SQL NULL). + let mut spec = StatementSpec::new(); + spec.sql("SELECT :flag, :maybe"); + spec.param_raw(Some("flag".to_owned()), "BOOLEAN", Some("true".to_owned())); + spec.param_raw(Some("maybe".to_owned()), "VOID", None); + let (_, params) = build_execute_params(&spec, None).unwrap(); + assert_eq!(params.parameters.len(), 2); + assert_eq!(params.parameters[0].name.as_deref(), Some("flag")); + assert!(params.parameters[0].ordinal.is_none()); + assert_eq!(params.parameters[1].name.as_deref(), Some("maybe")); + assert_eq!(params.parameters[1].param_type, "VOID"); + assert!(params.parameters[1].value.is_none()); + } + + #[test] + fn build_execute_params_rejects_raw_mixed_with_typed() { + // A host uses one binding style per statement: raw + TypedValue is rejected. + let mut spec = StatementSpec::new(); + spec.sql("SELECT ?, ?"); + spec.param(1, TypedValue::Int64(7)).unwrap(); + spec.param_raw(None, "STRING", Some("x".to_owned())); + let err = build_execute_params(&spec, None).expect_err("raw + typed must be rejected"); + assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); + assert!(err.message.contains("raw parameters cannot be mixed")); + } + + #[test] + fn build_execute_params_rejects_raw_mixed_positional_and_named() { + // Positional and named raw params are mutually exclusive, like the + // TypedValue markers — a mixed markers array is rejected by the server. + let mut spec = StatementSpec::new(); + spec.sql("SELECT ?, :n"); + spec.param_raw(None, "BIGINT", Some("1".to_owned())); + spec.param_raw(Some("n".to_owned()), "BIGINT", Some("2".to_owned())); + let err = build_execute_params(&spec, None) + .expect_err("mixed positional + named raw must be rejected"); + assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); + assert!(err.message.contains("mutually exclusive")); + } + + #[test] + fn build_execute_params_rejects_raw_mixed_with_named_typed() { + // The raw-vs-typed guard's second disjunct: raw mixed with a *named* + // TypedValue bind (not just positional) is equally rejected — a host + // uses one binding style per statement. + let mut spec = StatementSpec::new(); + spec.sql("SELECT :n, ?"); + spec.param_named("n", TypedValue::Int64(99)).unwrap(); + spec.param_raw(None, "STRING", Some("x".to_owned())); + let err = + build_execute_params(&spec, None).expect_err("raw + named-typed must be rejected"); + assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); + assert!(err.message.contains("raw parameters cannot be mixed")); + } + + #[test] + fn build_execute_params_binds_raw_empty_string_value_distinct_from_null() { + // A SQL driver must distinguish an empty-string value from SQL NULL: + // Some("") stays a present empty value on the wire, while None (VOID) is + // SQL NULL. The C bridge maps a null `value` pointer → None and any + // non-null (including "") → Some, so this pins that boundary. + let mut spec = StatementSpec::new(); + spec.sql("SELECT ?, ?"); + spec.param_raw(None, "STRING", Some(String::new())); + spec.param_raw(None, "VOID", None); + let (_, params) = build_execute_params(&spec, None).unwrap(); + assert_eq!(params.parameters.len(), 2); + assert_eq!( + params.parameters[0].value.as_deref(), + Some(""), + "empty-string value must stay a present empty value, not NULL" + ); + assert!( + params.parameters[1].value.is_none(), + "VOID/None must be SQL NULL, distinct from an empty string" + ); + } } diff --git a/src/statement/spec.rs b/src/statement/spec.rs index d760fa85..288bb0ae 100644 --- a/src/statement/spec.rs +++ b/src/statement/spec.rs @@ -191,6 +191,23 @@ pub struct StatementSpec { /// kernel rejects at bind time before the wire. pub named_params: HashMap, + /// Pre-marshalled SEA parameters (name/ordinal + Databricks type name + + /// stringified value). This is the shape a C-ABI host driver already + /// produces — e.g. the Go driver stringifies every value and carries the + /// SQL type name (`BIGINT`, `STRING`, `DECIMAL(..)`, `VOID` for NULL) — so + /// rather than round-trip through `TypedValue`, such a host pushes + /// `StatementParameter`s here directly. Mutually exclusive with + /// `positional_params` / `named_params` (mixing marker styles is rejected + /// the same way). Empty unless a host used the raw-bind path. + /// + /// `pub(crate)` deliberately: this holds the raw SEA wire struct + /// (`StatementParameter`, `#[derive(Serialize)]`, not `#[non_exhaustive]`), + /// so exposing it publicly would make evolving the wire type — trivially + /// non-breaking on the wire — a breaking change to the kernel crate. The + /// public surface is [`Self::param_raw`], which takes only strings; a + /// future alternate transport can then re-shape this field freely. + pub(crate) raw_params: Vec, + /// Per-statement conf overlay. Maps to SEA `parameters` / /// Thrift `confOverlay`. Merged on top of the session-level /// `session_conf` at execute time; this map wins on key collisions. @@ -213,9 +230,35 @@ impl StatementSpec { Self::default() } - /// Set the SQL text. Replaces any previously set SQL. + /// Set the SQL text. Replaces any previously set SQL and clears **every** + /// bound parameter — raw, positional-typed, and named-typed — so each + /// `sql()` begins a fresh set of *bound parameters*. + /// + /// Scope note: this clears the three parameter collections only. It does + /// **not** reset `statement_conf` (e.g. query tags) or `row_limit`, which + /// survive a `sql()` call and must be re-set explicitly if a reused handle + /// should not carry them into the next query. + /// + /// This is the single reset point for the *bound parameters* of a reused + /// statement handle. New SQL has its own parameter markers, so carrying + /// prior binds into it is never correct; clearing all three here matches the + /// prepared-statement mental model (new SQL → fresh binds) and keeps the + /// reset uniform across binding styles. Without it, a reused handle leaks + /// stale binds into the next query + /// in two ways: raw binds only `push` (no overwrite-by-ordinal), so they + /// would accumulate across executes; and typed positional binds overwrite by + /// ordinal (`param`) but a *shrinking* arity would keep the stale + /// high-ordinal slots, emitting more markers than the new SQL has. A host + /// that bound typed params for one query then raw-binds the next would also + /// trip the raw-vs-typed exclusion check on the leftover typed slots. + /// + /// The idiom is always `set_sql` → bind → execute per query, so binds are + /// re-supplied after each `sql()` and nothing depends on them surviving it. pub fn sql(&mut self, sql: impl Into) -> &mut Self { self.sql = Some(sql.into()); + self.raw_params.clear(); + self.positional_params.clear(); + self.named_params.clear(); self } @@ -264,6 +307,39 @@ impl StatementSpec { Ok(self) } + /// Push a pre-marshalled SEA parameter (host-stringified value + Databricks + /// type name). `name` empty → positional (ordinal assigned at execute in + /// push order, 1-based); non-empty → named. `value` None → SQL NULL (the + /// host passes type "VOID"). This is the raw-bind path a C-ABI host uses; it + /// bypasses `TypedValue` inference because the host already knows the wire + /// type and string form. + /// + /// **Append-only, one-shot per query.** Each call *appends* a marker; unlike + /// the typed [`Self::param`] binder there is no overwrite-by-ordinal (a raw + /// positional carries no ordinal until execute assigns it in push order), so + /// re-binding to "correct" a value adds a second marker rather than + /// replacing the first. Bind each marker exactly once per query; the only + /// reset is [`Self::sql`]. This matches the intended consumer contract — a + /// C-ABI host (e.g. the Go driver) binds its arg set once per execute on a + /// fresh handle and never re-binds in place. Duplicate-name detection on the + /// named raw path is deferred to a later PR, in lockstep with the same + /// tightening on [`Self::param_named`], so the raw and typed-named paths stay + /// symmetric rather than raw being stricter. + pub fn param_raw( + &mut self, + name: Option, + param_type: impl Into, + value: Option, + ) -> &mut Self { + self.raw_params.push(crate::types::sea::StatementParameter { + name, + ordinal: None, // assigned at build time for positional + param_type: param_type.into(), + value, + }); + self + } + /// Set the per-statement conf overlay. Replaces any previously-set map. pub fn statement_conf(&mut self, conf: HashMap) -> &mut Self { self.statement_conf = conf; @@ -521,6 +597,51 @@ mod tests { assert!(s.named_params.is_empty()); } + #[test] + fn sql_clears_all_params_so_reuse_does_not_accumulate() { + // A host reusing one statement (set_sql → bind → execute, repeat) must not + // carry stale params into the next query: sql() is the single reset point + // and clears EVERY binding style. After a second set_sql + bind, exactly + // the second query's params remain — for raw and typed alike. + let mut s = StatementSpec::new(); + s.sql("SELECT ?"); + s.param_raw(None, "BIGINT", Some("1".to_owned())); + assert_eq!(s.raw_params.len(), 1); + + s.sql("SELECT ?"); // re-set for the next execute + assert!(s.raw_params.is_empty(), "sql() must clear prior raw params"); + s.param_raw(None, "STRING", Some("hi".to_owned())); + assert_eq!(s.raw_params.len(), 1); + assert_eq!(s.raw_params[0].value.as_deref(), Some("hi")); + } + + #[test] + fn sql_clears_typed_params_so_reuse_does_not_accumulate() { + // The typed path is reset by sql() too: a shrinking-arity reuse must not + // keep stale high-ordinal slots, and a switch from typed to raw binds must + // not trip the raw-vs-typed exclusion on leftover typed params. + let mut s = StatementSpec::new(); + s.sql("SELECT ?, ?"); + s.param(1, TypedValue::Int64(1)).unwrap(); + s.param(2, TypedValue::Int64(2)).unwrap(); + s.param_named("k", TypedValue::Null).unwrap(); + assert_eq!(s.positional_params.len(), 2); + assert_eq!(s.named_params.len(), 1); + + s.sql("SELECT ?"); // narrower query on the reused handle + assert!( + s.positional_params.is_empty(), + "sql() must clear prior positional typed params" + ); + assert!( + s.named_params.is_empty(), + "sql() must clear prior named typed params" + ); + // The reused handle can now raw-bind without tripping raw-vs-typed exclusion. + s.param_raw(None, "BIGINT", Some("9".to_owned())); + assert_eq!(s.raw_params.len(), 1); + } + // ─── query_tags merge behaviour ───────────────────────────────────── #[test] diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index b96dfdef..1b721723 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -230,6 +230,16 @@ static void test_bind_null_handle_rejected(void) { CHECK(rc == KernelStatusCode_InvalidArgument, "bind_null(NULL stmt) → InvalidArgument"); rc = kernel_statement_set_sql(NULL, "SELECT 1"); CHECK(rc == KernelStatusCode_InvalidArgument, "set_sql(NULL stmt) → InvalidArgument"); + rc = kernel_statement_bind_parameter(NULL, NULL, "BIGINT", "7"); + CHECK(rc == KernelStatusCode_InvalidArgument, "bind_parameter(NULL stmt) → InvalidArgument"); +} + +/* Executed-handle accessors on a null handle → sentinel + stored error, no crash. */ +static void test_executed_null_handle_rejected(void) { + const char* qid = kernel_executed_statement_query_id(NULL); + CHECK(qid == NULL, "query_id(NULL exec) → NULL"); + int64_t n = kernel_executed_statement_num_modified_rows(NULL); + CHECK(n == -1, "num_modified_rows(NULL exec) → -1"); } int main(void) { @@ -245,6 +255,7 @@ int main(void) { test_is_open_null_guards(); test_submit_stub_rejects(); test_bind_null_handle_rejected(); + test_executed_null_handle_rejected(); if (failures == 0) { fprintf(stderr, "\nAll C ABI smoke checks passed.\n"); diff --git a/tests/v0_c_abi_canceller_wiremock.rs b/tests/v0_c_abi_canceller_wiremock.rs index a83814d3..b7f86ab7 100644 --- a/tests/v0_c_abi_canceller_wiremock.rs +++ b/tests/v0_c_abi_canceller_wiremock.rs @@ -46,13 +46,15 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; +use databricks_sql_kernel::c_abi::error::{kernel_get_last_error, KernelError}; use databricks_sql_kernel::c_abi::session::{ kernel_session_close, kernel_session_config_new, kernel_session_config_set_auth_pat, kernel_session_config_set_http_path, kernel_session_new_statement, kernel_session_open, kernel_session_t, KernelSessionConfig, }; use databricks_sql_kernel::c_abi::statement::{ - kernel_executed_statement_close, kernel_executed_statement_t, + kernel_executed_statement_close, kernel_executed_statement_query_id, + kernel_executed_statement_t, kernel_statement_bind_parameter, kernel_statement_canceller_cancel, kernel_statement_canceller_free, kernel_statement_canceller_new, kernel_statement_canceller_t, kernel_statement_close, kernel_statement_execute, kernel_statement_set_sql, kernel_statement_t, @@ -481,6 +483,548 @@ fn cancel_before_execute_is_a_noop_success() { } } +#[test] +fn query_id_returns_server_statement_id_on_success() { + // A successful inline execute exposes the server statement id through + // kernel_executed_statement_query_id — the success-path counterpart to the + // query id on KernelError. The returned pointer is borrowed from the handle. + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = rt.block_on(async { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_close_any(&server).await; + // POST /statements returns a terminal SUCCEEDED body carrying the id. + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with( + ResponseTemplate::new(200).set_body_string(succeeded_empty_body("stmt-qid-1")), + ) + .mount(&server) + .await; + server + }); + let uri = server.uri(); + + unsafe { + let session = open_session_c_abi(&uri); + let mut stmt: *mut kernel_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_session_new_statement(session, &mut stmt), + KernelStatusCode::Success + ); + let sql = CString::new("SELECT 1").unwrap(); + assert_eq!( + kernel_statement_set_sql(stmt, sql.as_ptr()), + KernelStatusCode::Success + ); + let mut exec: *mut kernel_executed_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_statement_execute(stmt, &mut exec), + KernelStatusCode::Success + ); + assert!(!exec.is_null()); + + let qid_ptr = kernel_executed_statement_query_id(exec); + assert!( + !qid_ptr.is_null(), + "a successful execute must expose a query id" + ); + let qid = std::ffi::CStr::from_ptr(qid_ptr).to_str().unwrap(); + assert_eq!(qid, "stmt-qid-1"); + + // Teardown (order: executed handle → statement → session). The + // invalidated-handle → NULL path is covered separately by + // `query_id_is_null_after_reexecute_invalidates_the_handle` (closing this + // handle here would free it, so calling query_id after close would be a + // use-after-free, not the staleness path this accessor guards). + assert_eq!( + kernel_executed_statement_close(exec), + KernelStatusCode::Success + ); + assert_eq!(kernel_statement_close(stmt), KernelStatusCode::Success); + assert_eq!(kernel_session_close(session), KernelStatusCode::Success); + } +} + +#[test] +fn query_id_is_null_after_reexecute_invalidates_the_handle() { + // The staleness guard: re-executing on the same statement flips the prior + // executed handle's shared ValidityFlag (invalidate_prior), so a query_id + // call on that now-stale handle returns NULL with a stored + // InvalidStatementHandle — a defined error, not a borrow into a dead handle. + // (Distinct from `close(exec)`, which frees the handle; re-execute leaves the + // C handle allocated but logically invalid, which is what this accessor must + // detect.) Two executes issue distinct ids so the assertion is unambiguous. + let rt = tokio::runtime::Runtime::new().unwrap(); + let second_started = Arc::new(AtomicBool::new(false)); + let server = rt.block_on(async { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_close_any(&server).await; + // Both executes run to SUCCEEDED (terminal inline), so neither leaves a + // running query behind; the second execute is what invalidates exec1. + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with(SequencedExecute { + first: succeeded_empty_body("stmt-qid-A"), + rest: succeeded_empty_body("stmt-qid-B"), + calls: AtomicUsize::new(0), + second_started: Arc::clone(&second_started), + }) + .mount(&server) + .await; + server + }); + let uri = server.uri(); + + unsafe { + let session = open_session_c_abi(&uri); + let mut stmt: *mut kernel_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_session_new_statement(session, &mut stmt), + KernelStatusCode::Success + ); + let sql = CString::new("SELECT 1").unwrap(); + assert_eq!( + kernel_statement_set_sql(stmt, sql.as_ptr()), + KernelStatusCode::Success + ); + + // First execute → exec1 exposes stmt-qid-A while it is live. + let mut exec1: *mut kernel_executed_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_statement_execute(stmt, &mut exec1), + KernelStatusCode::Success + ); + let qid1 = kernel_executed_statement_query_id(exec1); + assert!(!qid1.is_null(), "live handle must expose its id"); + assert_eq!( + std::ffi::CStr::from_ptr(qid1).to_str().unwrap(), + "stmt-qid-A" + ); + + // Re-execute on the same statement invalidates exec1 (does NOT free it). + let mut exec2: *mut kernel_executed_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_statement_execute(stmt, &mut exec2), + KernelStatusCode::Success + ); + + // exec1 is now stale: query_id → NULL with a stored InvalidStatementHandle. + let stale = kernel_executed_statement_query_id(exec1); + assert!( + stale.is_null(), + "query_id on a re-execute-invalidated handle must be NULL, not a stale borrow" + ); + let mut err = std::mem::MaybeUninit::::uninit(); + assert!( + kernel_get_last_error(err.as_mut_ptr()), + "a stored error must accompany the NULL" + ); + assert_eq!( + err.assume_init().code, + KernelStatusCode::InvalidStatementHandle as i32, + "stale-handle query_id must store InvalidStatementHandle" + ); + + // exec2 (the live handle) still works and returns the second id. + let qid2 = kernel_executed_statement_query_id(exec2); + assert!(!qid2.is_null()); + assert_eq!( + std::ffi::CStr::from_ptr(qid2).to_str().unwrap(), + "stmt-qid-B" + ); + + assert_eq!( + kernel_executed_statement_close(exec2), + KernelStatusCode::Success + ); + assert_eq!(kernel_statement_close(stmt), KernelStatusCode::Success); + assert_eq!(kernel_session_close(session), KernelStatusCode::Success); + } +} + +#[test] +fn bind_parameter_null_and_empty_sql_type_are_rejected_at_bind() { + // The bridge validates sql_type before pushing: NULL type and empty type both + // return InvalidArgument at bind (a typed error beats an opaque wire-level + // BAD_REQUEST at execute). A NULL value with a valid type is accepted (SQL + // NULL, the host passes "VOID"). No server round-trip is needed for the + // rejections, so this drives the bridge directly on a live statement. + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = rt.block_on(async { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_close_any(&server).await; + server + }); + let uri = server.uri(); + + unsafe { + let session = open_session_c_abi(&uri); + let mut stmt: *mut kernel_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_session_new_statement(session, &mut stmt), + KernelStatusCode::Success + ); + let sql = CString::new("SELECT ?").unwrap(); + assert_eq!( + kernel_statement_set_sql(stmt, sql.as_ptr()), + KernelStatusCode::Success + ); + + let bigint = CString::new("BIGINT").unwrap(); + let empty = CString::new("").unwrap(); + let seven = CString::new("7").unwrap(); + + // NULL sql_type → InvalidArgument. + assert_eq!( + kernel_statement_bind_parameter( + stmt, + std::ptr::null(), + std::ptr::null(), + seven.as_ptr() + ), + KernelStatusCode::InvalidArgument, + "NULL sql_type must be rejected at bind" + ); + // Empty sql_type → InvalidArgument (symmetric with the NULL guard). + assert_eq!( + kernel_statement_bind_parameter(stmt, std::ptr::null(), empty.as_ptr(), seven.as_ptr()), + KernelStatusCode::InvalidArgument, + "empty sql_type must be rejected at bind" + ); + // A NULL value with a valid type is fine (SQL NULL via "VOID" is the more + // idiomatic form, but a null value with any type binds as NULL). + assert_eq!( + kernel_statement_bind_parameter( + stmt, + std::ptr::null(), + bigint.as_ptr(), + std::ptr::null() + ), + KernelStatusCode::Success, + "NULL value with a valid type binds as SQL NULL" + ); + + assert_eq!(kernel_statement_close(stmt), KernelStatusCode::Success); + assert_eq!(kernel_session_close(session), KernelStatusCode::Success); + } +} + +#[test] +fn bind_parameter_positive_flow_normalizes_and_reaches_the_wire() { + // End-to-end reference for a consuming host: bind a positional raw param + // (empty name → positional), a named raw param, and a NULL value through the + // real C entry point, execute against the mock, and read back the server id. + // Asserts the bridge's normalization (empty-name → positional ordinal, null + // value → SQL NULL) actually reaches the SEA `parameters` wire array — the + // path all the param_raw unit tests bypass by calling param_raw directly. + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = rt.block_on(async { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_close_any(&server).await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with( + ResponseTemplate::new(200).set_body_string(succeeded_empty_body("stmt-bind-1")), + ) + .mount(&server) + .await; + server + }); + let uri = server.uri(); + + unsafe { + let session = open_session_c_abi(&uri); + let mut stmt: *mut kernel_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_session_new_statement(session, &mut stmt), + KernelStatusCode::Success + ); + // Two positional markers + a NULL — all positional (empty/NULL name). + let sql = CString::new("SELECT ?, ?, ?").unwrap(); + assert_eq!( + kernel_statement_set_sql(stmt, sql.as_ptr()), + KernelStatusCode::Success + ); + + let empty_name = CString::new("").unwrap(); + let bigint = CString::new("BIGINT").unwrap(); + let string_t = CString::new("STRING").unwrap(); + let void_t = CString::new("VOID").unwrap(); + let v_seven = CString::new("7").unwrap(); + let v_empty = CString::new("").unwrap(); + + // Empty name → positional ordinal 1, value "7". + assert_eq!( + kernel_statement_bind_parameter( + stmt, + empty_name.as_ptr(), + bigint.as_ptr(), + v_seven.as_ptr() + ), + KernelStatusCode::Success + ); + // NULL name → positional ordinal 2, empty-string value (present, not NULL). + assert_eq!( + kernel_statement_bind_parameter( + stmt, + std::ptr::null(), + string_t.as_ptr(), + v_empty.as_ptr() + ), + KernelStatusCode::Success + ); + // NULL value → positional ordinal 3, SQL NULL (type VOID). + assert_eq!( + kernel_statement_bind_parameter( + stmt, + std::ptr::null(), + void_t.as_ptr(), + std::ptr::null() + ), + KernelStatusCode::Success + ); + + let mut exec: *mut kernel_executed_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_statement_execute(stmt, &mut exec), + KernelStatusCode::Success + ); + assert!(!exec.is_null()); + + // query_id round-trips on the success path after a param bind. + let qid = kernel_executed_statement_query_id(exec); + assert!(!qid.is_null()); + assert_eq!( + std::ffi::CStr::from_ptr(qid).to_str().unwrap(), + "stmt-bind-1" + ); + + assert_eq!( + kernel_executed_statement_close(exec), + KernelStatusCode::Success + ); + assert_eq!(kernel_statement_close(stmt), KernelStatusCode::Success); + assert_eq!(kernel_session_close(session), KernelStatusCode::Success); + } + + // The normalization reached the wire: inspect the POST body. + let posts = rt.block_on(async { + server + .received_requests() + .await + .expect("received_requests available") + .into_iter() + .filter(|r| { + r.method == wiremock::http::Method::POST + && r.url.path() == "/api/2.0/sql/statements" + }) + .collect::>() + }); + assert_eq!(posts.len(), 1, "exactly one execute POST"); + let body: serde_json::Value = serde_json::from_slice(&posts[0].body).unwrap(); + let params = body["parameters"].as_array().expect("parameters array"); + assert_eq!(params.len(), 3, "three bound params on the wire"); + // Positional ordinals assigned 1..=3 in push order; no name key emitted. + assert_eq!(params[0]["ordinal"], 1); + assert_eq!(params[0]["type"], "BIGINT"); + assert_eq!(params[0]["value"], "7"); + assert!( + params[0].get("name").is_none(), + "positional param has no name" + ); + // Empty-string value stays present (distinct from SQL NULL below). + assert_eq!(params[1]["ordinal"], 2); + assert_eq!(params[1]["value"], ""); + // NULL value: `value` omitted (serde skips None), type VOID. + assert_eq!(params[2]["ordinal"], 3); + assert_eq!(params[2]["type"], "VOID"); + assert!( + params[2].get("value").is_none() || params[2]["value"].is_null(), + "SQL NULL param emits no value" + ); +} + +#[test] +fn bind_parameter_named_reaches_the_wire_with_name_and_no_ordinal() { + // Companion to the positional-only positive flow: a non-empty name must + // serialize a `:name` marker on the SEA `parameters` array — a `"name"` key + // and NO `"ordinal"` key. The named-raw path is a documented first-class + // binding for a C-ABI host (e.g. the Go driver's named `backend.Param`), and + // the param_raw unit tests exercise it only by calling param_raw directly, + // bypassing the C bridge. This pins name → wire through the real entry point, + // so a bridge regression (name dropped, spurious ordinal, `:` mishandled) + // fails a test instead of shipping a malformed markers array to the server. + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = rt.block_on(async { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_close_any(&server).await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with( + ResponseTemplate::new(200).set_body_string(succeeded_empty_body("stmt-named-1")), + ) + .mount(&server) + .await; + server + }); + let uri = server.uri(); + + unsafe { + let session = open_session_c_abi(&uri); + let mut stmt: *mut kernel_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_session_new_statement(session, &mut stmt), + KernelStatusCode::Success + ); + let sql = CString::new("SELECT :id, :label").unwrap(); + assert_eq!( + kernel_statement_set_sql(stmt, sql.as_ptr()), + KernelStatusCode::Success + ); + + let name_id = CString::new("id").unwrap(); + let name_label = CString::new("label").unwrap(); + let bigint = CString::new("BIGINT").unwrap(); + let string_t = CString::new("STRING").unwrap(); + let v_seven = CString::new("7").unwrap(); + let v_hi = CString::new("hi").unwrap(); + + assert_eq!( + kernel_statement_bind_parameter( + stmt, + name_id.as_ptr(), + bigint.as_ptr(), + v_seven.as_ptr() + ), + KernelStatusCode::Success + ); + assert_eq!( + kernel_statement_bind_parameter( + stmt, + name_label.as_ptr(), + string_t.as_ptr(), + v_hi.as_ptr() + ), + KernelStatusCode::Success + ); + + let mut exec: *mut kernel_executed_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_statement_execute(stmt, &mut exec), + KernelStatusCode::Success + ); + assert!(!exec.is_null()); + + assert_eq!( + kernel_executed_statement_close(exec), + KernelStatusCode::Success + ); + assert_eq!(kernel_statement_close(stmt), KernelStatusCode::Success); + assert_eq!(kernel_session_close(session), KernelStatusCode::Success); + } + + let posts = rt.block_on(async { + server + .received_requests() + .await + .expect("received_requests available") + .into_iter() + .filter(|r| { + r.method == wiremock::http::Method::POST + && r.url.path() == "/api/2.0/sql/statements" + }) + .collect::>() + }); + assert_eq!(posts.len(), 1, "exactly one execute POST"); + let body: serde_json::Value = serde_json::from_slice(&posts[0].body).unwrap(); + let params = body["parameters"].as_array().expect("parameters array"); + assert_eq!(params.len(), 2, "two named params on the wire"); + // Named markers carry a `name` key and NO `ordinal` key (serde skips None). + for (i, (name, ty, val)) in [("id", "BIGINT", "7"), ("label", "STRING", "hi")] + .iter() + .enumerate() + { + assert_eq!(params[i]["name"], *name, "named param {i} keeps its name"); + assert_eq!(params[i]["type"], *ty); + assert_eq!(params[i]["value"], *val); + assert!( + params[i].get("ordinal").is_none(), + "named param {i} emits no ordinal" + ); + } +} + +#[test] +fn bind_parameter_rejects_non_utf8_in_each_string_arg() { + // The C boundary the Go driver hits carries arbitrary bytes. Each of the + // three string args (sql_type, name, value) has its own `to_str()` guard that + // must reject a non-UTF-8 sequence with InvalidArgument, keeping the + // SQL-NULL-vs-corrupt-value distinction crisp (a future from_utf8_lossy swap + // would silently smuggle replacement chars to the wire — this fails first). + // No round-trip needed; the rejections happen at bind on a live statement. + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = rt.block_on(async { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_close_any(&server).await; + server + }); + let uri = server.uri(); + + // A lone 0xFF byte is never valid UTF-8. CString rejects interior NULs, not + // high bytes, so this builds a valid NUL-terminated C string of invalid UTF-8. + let bad = CString::new(vec![0xffu8]).unwrap(); + let bigint = CString::new("BIGINT").unwrap(); + let name_ok = CString::new("id").unwrap(); + let value_ok = CString::new("7").unwrap(); + + unsafe { + let session = open_session_c_abi(&uri); + let mut stmt: *mut kernel_statement_t = std::ptr::null_mut(); + assert_eq!( + kernel_session_new_statement(session, &mut stmt), + KernelStatusCode::Success + ); + let sql = CString::new("SELECT ?").unwrap(); + assert_eq!( + kernel_statement_set_sql(stmt, sql.as_ptr()), + KernelStatusCode::Success + ); + + // Non-UTF-8 sql_type → InvalidArgument. + assert_eq!( + kernel_statement_bind_parameter( + stmt, + name_ok.as_ptr(), + bad.as_ptr(), + value_ok.as_ptr() + ), + KernelStatusCode::InvalidArgument, + "non-UTF-8 sql_type must be rejected at bind" + ); + // Non-UTF-8 name → InvalidArgument. + assert_eq!( + kernel_statement_bind_parameter(stmt, bad.as_ptr(), bigint.as_ptr(), value_ok.as_ptr()), + KernelStatusCode::InvalidArgument, + "non-UTF-8 name must be rejected at bind" + ); + // Non-UTF-8 value → InvalidArgument. + assert_eq!( + kernel_statement_bind_parameter(stmt, name_ok.as_ptr(), bigint.as_ptr(), bad.as_ptr()), + KernelStatusCode::InvalidArgument, + "non-UTF-8 value must be rejected at bind" + ); + + assert_eq!(kernel_statement_close(stmt), KernelStatusCode::Success); + assert_eq!(kernel_session_close(session), KernelStatusCode::Success); + } +} + #[test] fn cancel_rpc_failure_returns_error_and_sets_dispatched_false() { let rt = tokio::runtime::Runtime::new().unwrap();