diff --git a/napi/src/async_statement.rs b/napi/src/async_statement.rs new file mode 100644 index 00000000..94b4d252 --- /dev/null +++ b/napi/src/async_statement.rs @@ -0,0 +1,484 @@ +// 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. + +//! Opaque `AsyncStatement` + `AsyncResultHandle` wrappers around the +//! kernel's submit/poll/await_result path. +//! +//! - `Connection.submitStatement(sql, options?)` builds a kernel +//! `Statement`, calls `submit()` (which sends `wait_timeout=0s` so +//! the server returns Pending/Running immediately with a +//! statement_id), and wraps the returned `ExecutedAsyncStatement` +//! in this napi class. JS callers drive polling via `status()` or +//! `awaitResult()`. +//! +//! - `AsyncStatement.status()` issues a single GetStatementStatus +//! RPC, mapped to a JS-side string enum +//! (`'Pending'|'Running'|'Succeeded'|'Failed'|'Cancelled'|'Closed'`). +//! The Failed variant carries the same error envelope the sync +//! path produces (sql_state / error_code / query_id when present). +//! +//! - `AsyncStatement.awaitResult()` blocks until the server reaches +//! a terminal state, then returns an `AsyncResultHandle` over the +//! materialised `ResultStream`. The kernel's own +//! `AwaitResultCancelGuard` already covers drop-cancel safety: if +//! the JS Promise's underlying tokio future is dropped mid-poll +//! (e.g. a timeout wrapper, a tokio::select! loser), the kernel +//! fires a fire-and-forget `cancel_statement` so the server stops +//! charging DBUs on the orphaned query. The `util::guarded` +//! `catch_unwind` wrapper that we apply to every entry here covers +//! the V8-panic-across-boundary case on top of that. +//! +//! Cancel-vs-close vs the sync path is identical: `cancel()` / +//! `close()` route through the `ExecutedStatementHandle` trait the +//! kernel implements for both `ExecutedStatement` and +//! `ExecutedAsyncStatement`. The `Arc>>` shape is +//! the same as `Connection`/`Statement` so Drop's fire-and-forget +//! cleanup behaves consistently. + +use std::sync::Arc; +use tokio::sync::Mutex; + +use arrow_schema::SchemaRef; +use databricks_sql_kernel::{ + Error as KernelError, ExecutedAsyncStatement, ExecutedStatementHandle, ResultBatch, + ResultStream, Statement as KernelStatement, StatementStatus, +}; + +use crate::error::napi_err_from_kernel; +use crate::result::{ArrowBatch, ArrowSchema}; +use crate::runtime; +use crate::util::guarded; + +// ───────────────────────── shared helpers ───────────────────────── + +/// Closed-state error builder for both `AsyncStatement` and +/// `AsyncResultHandle`. Mirrors the sync `Statement` path's +/// `statement_closed_err` so the TS reviver sees the same +/// `KernelError(code='InvalidStatementHandle')` shape regardless of +/// which napi class produced the error. +fn closed_err(what: &str) -> napi::Error { + napi_err_from_kernel( + KernelError::invalid_statement_handle() + .message(format!("{what} already closed")), + ) +} + +/// Encode a `RecordBatch` (or schema-only payload) as a complete +/// Arrow IPC stream. Duplicates the sync-path encoder in +/// `statement.rs::encode_ipc_stream`; the helper is private there +/// and the two paths produce byte-identical output, so we re-emit +/// it here rather than expanding the surface of `statement` for one +/// re-use site. If a third caller appears, this becomes the lifting +/// trigger to extract into `bindings_common`. +fn encode_ipc_stream( + schema: &SchemaRef, + batch: Option<&arrow_array::RecordBatch>, +) -> napi::Result> { + // Conservative initial capacity — schema header alone is ~hundreds + // of bytes; a single batch can be hundreds of KB. Sized to avoid + // multiple small grows on schema-only payloads while not + // over-allocating for them. + let mut buf = Vec::with_capacity(1024); + { + let mut writer = arrow_ipc::writer::StreamWriter::try_new(&mut buf, schema) + .map_err(|e| { + napi_err_from_kernel( + KernelError::internal() + .message(format!("Arrow IPC writer init failed: {e}")), + ) + })?; + if let Some(rb) = batch { + writer.write(rb).map_err(|e| { + napi_err_from_kernel( + KernelError::internal() + .message(format!("Arrow IPC writer write failed: {e}")), + ) + })?; + } + writer.finish().map_err(|e| { + napi_err_from_kernel( + KernelError::internal() + .message(format!("Arrow IPC writer finish failed: {e}")), + ) + })?; + } + Ok(buf) +} + +// ───────────────────────── AsyncStatement ───────────────────────── + +/// Inner state for the JS-visible `AsyncStatement` wrapper. Same +/// shape rationale as `StatementInner` in `statement.rs`: we hold +/// the parent kernel `Statement` alive so its `Drop` (which +/// invalidates the executed handle via the shared `ValidityFlag`) +/// doesn't fire while JS still holds this wrapper. +struct AsyncStatementInner { + /// The kernel's `Statement` (mutable). Kept alive solely to + /// prevent its `Drop` from invalidating `executed_async`. + _parent: KernelStatement, + /// The kernel async-consumption handle — drives `status()` / + /// `awaitResult()` / `cancel()` / `close()`. + executed_async: ExecutedAsyncStatement, +} + +/// Opaque async-statement handle. +/// +/// Returned by `Connection.submitStatement(...)` after the kernel +/// `Statement::submit()` returns (server sent `wait_timeout=0s`, so +/// the response carries a `statement_id` but the statement is still +/// `Pending`/`Running`). JS drives polling via `status()` / +/// `awaitResult()`. +/// +/// Concurrency shape matches the sync `Statement`: every method +/// takes `inner.lock()` and holds the guard across the kernel +/// `.await`. tokio `Mutex` is FIFO. `cancel()` / `close()` queue +/// behind any in-flight `awaitResult()` until it returns naturally. +/// The kernel's `AwaitResultCancelGuard` covers the drop-cancel +/// case independently — see module docs. +#[napi] +pub struct AsyncStatement { + inner: Arc>>, + /// Server-issued statement id. Cached at construction; readable + /// even after `close()` for log correlation against kernel / + /// server logs which key on the same id. + statement_id: String, +} + +impl AsyncStatement { + /// Crate-internal constructor — called from + /// `Connection::submit_statement` once the kernel hands back + /// the `ExecutedAsyncStatement`. The parent kernel `Statement` + /// is passed in alongside so its `Drop` doesn't fire while JS + /// still holds the executed-async handle (see + /// `StatementInner` docs in `statement.rs` for the + /// validity-flag rationale). + pub(crate) fn from_executed_async( + parent: KernelStatement, + executed_async: ExecutedAsyncStatement, + ) -> Self { + let statement_id = executed_async.statement_id().to_owned(); + Self { + inner: Arc::new(Mutex::new(Some(AsyncStatementInner { + _parent: parent, + executed_async, + }))), + statement_id, + } + } +} + +#[napi] +impl AsyncStatement { + /// Server-issued statement id. Cached at construction; readable + /// even after `close()` so JS-side log lines can correlate + /// against kernel / server logs which key on the same id. + #[napi(getter)] + pub fn statement_id(&self) -> &str { + &self.statement_id + } + + /// One-shot status check. Returns a string enum matching the + /// kernel `StatementStatus` shape: + /// `'Pending' | 'Running' | 'Succeeded' | 'Failed' | + /// 'Cancelled' | 'Closed'`. Returns + /// `KernelError(InvalidStatementHandle)` if the statement has + /// been explicitly `close()`d. + /// + /// The `Failed` variant collapses to the string `'Failed'` on + /// the JS side; the underlying error envelope (sql_state / + /// error_code / query_id) is surfaced by `awaitResult()`'s + /// rejection, which is where callers actually need the typed + /// error. `status()` is intended for polling progress UIs + /// that only need the state name. + #[napi] + pub async fn status(&self) -> napi::Result { + let inner = Arc::clone(&self.inner); + guarded(async move { + let guard = inner.lock().await; + let inner_state = guard.as_ref().ok_or_else(|| closed_err("AsyncStatement"))?; + let status = inner_state + .executed_async + .status() + .await + .map_err(napi_err_from_kernel)?; + Ok(status_to_string(&status)) + }) + .await + } + + /// Block until the server reaches a terminal state, then return + /// an `AsyncResultHandle` that wraps the materialised result + /// stream. The handle exposes `fetchNextBatch()` / `schema()` + /// for consuming the result, plus `statementId` for log + /// correlation. + /// + /// Drop-cancel safety: kernel `await_result` installs + /// `AwaitResultCancelGuard` which fires a fire-and-forget + /// `cancel_statement` if the future is dropped mid-poll + /// (timeout, tokio::select! loser, JS-side `Promise.race` + /// loser). The `util::guarded` `catch_unwind` here covers the + /// V8-panic-across-boundary case on top. Returns + /// `KernelError(InvalidStatementHandle)` if the statement has + /// been explicitly `close()`d. + #[napi] + pub async fn await_result(&self) -> napi::Result { + let inner = Arc::clone(&self.inner); + guarded(async move { + // Acquire and HOLD the lock across the kernel await: + // dropping the lock guard while the long-running + // `await_result()` is in-flight would allow `cancel()` / + // `close()` to race for the inner state. The kernel-side + // `AwaitResultCancelGuard` covers the drop-the-future + // case; we cover the concurrent-method case here. + let guard = inner.lock().await; + let inner_state = guard.as_ref().ok_or_else(|| closed_err("AsyncStatement"))?; + let stream = inner_state + .executed_async + .await_result() + .await + .map_err(napi_err_from_kernel)?; + let statement_id = inner_state.executed_async.statement_id().to_owned(); + let schema = stream.schema(); + Ok(AsyncResultHandle { + inner: Arc::new(Mutex::new(Some(stream))), + schema, + statement_id, + }) + }) + .await + } + + /// Server-side cancel. Returns + /// `KernelError(InvalidStatementHandle)` if the statement has + /// been explicitly `close()`d. Idempotent against a server + /// that already reached a terminal state — the kernel's + /// `cancel_statement` is a no-op there. + #[napi] + pub async fn cancel(&self) -> napi::Result<()> { + let inner = Arc::clone(&self.inner); + guarded(async move { + let guard = inner.lock().await; + let inner_state = guard.as_ref().ok_or_else(|| closed_err("AsyncStatement"))?; + inner_state + .executed_async + .cancel() + .await + .map_err(napi_err_from_kernel) + }) + .await + } + + /// Explicit close. Idempotent — a second call on an + /// already-closed handle returns `Ok(())`. On `Err`, the napi + /// inner is already `None`, so a JS-side retry sees the + /// closed-handle short-circuit and returns `Ok(())` without + /// re-attempting the wire call. The kernel's own `Drop` + /// fire-and-forget retry runs once in the background. + #[napi] + pub async fn close(&self) -> napi::Result<()> { + let inner = Arc::clone(&self.inner); + guarded(async move { + let taken = { + let mut guard = inner.lock().await; + guard.take() + }; + let Some(inner_state) = taken else { + return Ok(()); + }; + inner_state + .executed_async + .close() + .await + .map_err(napi_err_from_kernel) + }) + .await + } +} + +impl Drop for AsyncStatement { + fn drop(&mut self) { + // Best-effort cleanup — same shape as `Connection::Drop`. + // JS callers needing a guaranteed close-with-error-surface + // call `close()` explicitly. + let Some(handle) = runtime::try_get_handle() else { + return; + }; + let inner = Arc::clone(&self.inner); + handle.spawn(async move { + let _taken = { + let mut guard = inner.lock().await; + guard.take() + }; + }); + } +} + +// ─────────────────────── AsyncResultHandle ──────────────────────── + +/// Opaque result-fetch handle returned by +/// `AsyncStatement.awaitResult()`. Wraps a kernel `ResultStream` +/// directly; structurally analogous to the sync `Statement`'s +/// fetch-side surface (`fetchNextBatch` / `schema` / +/// `statementId`). +/// +/// `cancel()` / `close()` are not exposed: the parent +/// `AsyncStatement` owns server-side lifecycle. A `close()` here +/// would create dual-ownership of the same statement_id with +/// inconsistent close semantics. Callers `close()` the parent +/// `AsyncStatement` after they're done fetching. +/// +/// Schema is cached at construction so it survives the underlying +/// stream being drained; mirrors the sync `Statement.schema()` +/// post-close contract. +#[napi] +pub struct AsyncResultHandle { + /// `Option` only so a future explicit-close path + /// can `.take()` consistently. Today the slot is filled at + /// construction and never emptied until Drop. + inner: Arc>>, + schema: SchemaRef, + statement_id: String, +} + +#[napi] +impl AsyncResultHandle { + /// Server-issued statement id. Cached at construction; readable + /// for log correlation. Matches the parent `AsyncStatement`'s + /// `statementId`. + #[napi(getter)] + pub fn statement_id(&self) -> &str { + &self.statement_id + } + + /// Pull the next batch of results. Returns `null` when the + /// stream is exhausted. The returned `ArrowBatch.ipcBytes` is a + /// complete Arrow IPC stream (schema header + 1 record-batch + /// message), suitable for handing to `apache-arrow`'s + /// `RecordBatchReader`. Byte-identical to the sync + /// `Statement.fetchNextBatch()` payload for the same query. + #[napi] + pub async fn fetch_next_batch(&self) -> napi::Result> { + let inner = Arc::clone(&self.inner); + let schema = self.schema.clone(); + guarded(async move { + let mut guard = inner.lock().await; + let stream = guard + .as_mut() + .ok_or_else(|| closed_err("AsyncResultHandle"))?; + let maybe_batch = stream.next_batch().await.map_err(napi_err_from_kernel)?; + let Some(batch) = maybe_batch else { + return Ok(None); + }; + let record_batch = match batch { + ResultBatch::Arrow(rb) => rb, + _ => { + return Err(napi_err_from_kernel( + KernelError::invalid_argument().message(format!( + "non-Arrow ResultBatch variant from kernel — \ + databricks-sea-native v{} cannot decode this batch \ + shape, upgrade the binding", + env!("CARGO_PKG_VERSION"), + )), + )); + } + }; + let bytes = encode_ipc_stream(&schema, Some(record_batch))?; + Ok(Some(ArrowBatch { + ipc_bytes: bytes.into(), + })) + }) + .await + } + + /// Result schema as an Arrow IPC payload (schema header only, + /// no record-batch message). Available before any batches have + /// been fetched. Sync because the body has no `.await` — + /// `encode_ipc_stream` is pure CPU work over the cached + /// `Arc`. + #[napi] + pub fn schema(&self) -> napi::Result { + let bytes = encode_ipc_stream(&self.schema, None)?; + Ok(ArrowSchema { + ipc_bytes: bytes.into(), + }) + } +} + +// ───────────────────────── status mapping ───────────────────────── + +/// Map `StatementStatus` to the JS-visible string. The `Failed` +/// variant collapses to `"Failed"`; the underlying error envelope +/// is surfaced only via `awaitResult()`'s rejection, which is where +/// callers actually need the typed error. `status()` is for +/// progress UIs. +fn status_to_string(s: &StatementStatus) -> String { + match s { + StatementStatus::Pending => "Pending", + StatementStatus::Running => "Running", + StatementStatus::Succeeded => "Succeeded", + StatementStatus::Failed(_) => "Failed", + StatementStatus::Cancelled => "Cancelled", + StatementStatus::Closed => "Closed", + // `StatementStatus` is `#[non_exhaustive]`. A future kernel + // variant the binding doesn't recognise surfaces as + // `"Unknown"` so JS callers see something deterministic + // instead of a panic; upgrading the binding maps the variant + // to its real string. If you see this in production logs, + // the binding is older than the kernel it's linked against. + _ => "Unknown", + } + .to_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn status_to_string_covers_all_variants() { + assert_eq!(status_to_string(&StatementStatus::Pending), "Pending"); + assert_eq!(status_to_string(&StatementStatus::Running), "Running"); + assert_eq!(status_to_string(&StatementStatus::Succeeded), "Succeeded"); + assert_eq!(status_to_string(&StatementStatus::Cancelled), "Cancelled"); + assert_eq!(status_to_string(&StatementStatus::Closed), "Closed"); + let failed = StatementStatus::Failed(KernelError::sql_error().message("boom")); + assert_eq!(status_to_string(&failed), "Failed"); + } + + #[test] + fn closed_err_carries_invalid_statement_handle_envelope() { + let err = closed_err("AsyncStatement"); + assert!( + err.reason.starts_with(crate::error::ERROR_SENTINEL), + "expected envelope-sentinel-prefixed error, got: {}", + err.reason, + ); + assert!( + err.reason.contains(r#""code":"InvalidStatementHandle""#), + "envelope payload missing InvalidStatementHandle: {}", + err.reason, + ); + assert!( + err.reason.contains("AsyncStatement already closed"), + "closed-state error must carry the human message: {}", + err.reason, + ); + } + + #[test] + fn closed_err_status_collapses_to_invalid_arg() { + let err = closed_err("AsyncResultHandle"); + assert_eq!(err.status, napi::Status::InvalidArg); + } +} diff --git a/napi/src/connection.rs b/napi/src/connection.rs index 20d3d11a..df0ccafb 100644 --- a/napi/src/connection.rs +++ b/napi/src/connection.rs @@ -27,16 +27,72 @@ //! fire-and-forget close on the captured runtime handle if explicit //! close was never called. +use std::collections::HashMap; use std::sync::Arc; use tokio::sync::Mutex; use databricks_sql_kernel::{Error as KernelError, Session}; +use crate::async_statement::AsyncStatement; use crate::error::napi_err_from_kernel; use crate::runtime; use crate::statement::Statement; use crate::util::guarded; +/// Per-statement options for `Connection.executeStatement`. +/// +/// Mirrors the kernel `StatementSpec` knobs that are safe to thread +/// through napi without a kernel-side change. Today this covers: +/// - `statementConf` — per-statement Spark conf overlay +/// (`StatementSpec.statement_conf` → SEA `parameters` / +/// Thrift `confOverlay`) +/// - `queryTags` — convenience wrapper over `statementConf` with +/// key `query_tags`; serialised to the same comma-separated +/// `key:value` wire shape NodeJS Thrift's `serializeQueryTags` +/// produces (`lib/utils/queryTags.ts`). Backslashes in keys are +/// doubled; backslash/colon/comma in values are backslash-escaped. +/// +/// Positional parameters, named parameters, row limit, and wait +/// timeout are deferred: they require either a non-trivial JS↔napi +/// `TypedValue` mapping (params) or a kernel-side `StatementSpec` +/// extension (`row_limit`/`wait_timeout`). Both land in follow-on PRs. +/// +/// **Tag-order caveat (M4 parity note).** The napi `queryTags` field +/// is a Rust `HashMap` whose iteration order is +/// non-deterministic, so the serialised `query_tags` value may have +/// a different key order than Thrift's `serializeQueryTags` (which +/// iterates `Object.keys(...)` in insertion order) for the same +/// input. The SEA server is order-insensitive on conf values, so +/// the two are functionally equivalent. If a caller needs +/// byte-identical Thrift parity, the JS adapter pre-serialises via +/// `serializeQueryTags` and writes the result into +/// `statementConf["query_tags"]` directly — see +/// `SeaSessionBackend.executeStatement` in the NodeJS driver. This +/// path is the one the production code uses. +#[allow( + dead_code, + reason = "exported via napi macro codegen; not called from Rust" +)] +#[napi(object)] +pub struct ExecuteOptions { + /// Per-statement Spark conf overlay. Merged on top of the + /// session-level `sessionConf` at execute time; this map wins + /// on key collisions. Unknown keys are rejected by the server. + pub statement_conf: Option>, + /// Query tags as key→value pairs. Serialised to a comma- + /// separated `key:value` string (backslash-escaping `\`, `:`, + /// `,`) and placed into `statementConf["query_tags"]`, matching + /// NodeJS Thrift's `serializeQueryTags` wire shape. Passing + /// both `queryTags` AND a `query_tags` key in `statementConf` + /// raises `InvalidArgument` — the caller's intent is ambiguous + /// so we refuse to silently pick one over the other. + /// + /// See the struct-level "Tag-order caveat" for the + /// HashMap-iteration-order vs `Object.keys`-iteration-order + /// divergence and the byte-identical-Thrift-parity workaround. + pub query_tags: Option>, +} + /// Closed-state error builder. Mirrors `statement::statement_closed_err` /// — route through the kernel envelope so the TS reviver mints a typed /// `KernelError(code='InvalidStatementHandle')`. Single source of truth @@ -47,6 +103,73 @@ fn connection_closed_err() -> napi::Error { ) } +/// Merge `statement_conf` and `query_tags` from JS-supplied +/// `ExecuteOptions` into the single `HashMap` the +/// kernel's `StatementSpec::statement_conf` accepts. +/// +/// Returns `Ok(None)` when no per-statement conf is set (caller skips +/// the `.statement_conf(...)` builder call so the kernel sees the +/// session-level conf untouched). Returns `Ok(Some(conf))` when at +/// least one knob was set. Returns `Err(InvalidArgument)` when both +/// `queryTags` and `statementConf["query_tags"]` are present — the +/// caller's intent is ambiguous. +fn build_merged_statement_conf( + options: Option, +) -> napi::Result>> { + let Some(options) = options else { + return Ok(None); + }; + + let mut conf = options.statement_conf.unwrap_or_default(); + if let Some(tags) = options.query_tags { + if !tags.is_empty() && conf.contains_key("query_tags") { + return Err(napi_err_from_kernel( + KernelError::invalid_argument().message( + "ExecuteOptions: cannot supply both `queryTags` and \ + `statementConf[\"query_tags\"]` — pick one", + ), + )); + } + if !tags.is_empty() { + conf.insert("query_tags".to_string(), serialize_query_tags(&tags)); + } + } + + if conf.is_empty() { + Ok(None) + } else { + Ok(Some(conf)) + } +} + +/// Serialise a tag map to the same wire shape NodeJS Thrift's +/// `serializeQueryTags` produces: comma-separated `key:value` pairs. +/// Backslashes in keys are doubled; backslash, colon, and comma in +/// values are backslash-escaped. Null/empty values would produce a +/// bare key with no colon — but the napi `HashMap` +/// shape can't carry nulls today, so every tag here is `key:value`. +/// +/// Match the Thrift wire shape exactly: the SEA server merges +/// `confOverlay.query_tags` the same way regardless of which backend +/// produced it, and JS callers porting from Thrift expect identical +/// behaviour. +fn serialize_query_tags(tags: &HashMap) -> String { + tags.iter() + .map(|(k, v)| { + let esc_key = k.replace('\\', "\\\\"); + let esc_val = v + .chars() + .flat_map(|c| match c { + '\\' | ':' | ',' => vec!['\\', c], + other => vec![other], + }) + .collect::(); + format!("{esc_key}:{esc_val}") + }) + .collect::>() + .join(",") +} + /// Opaque connection handle wrapping a kernel `Session`. /// /// `inner` is `Arc>>` so: @@ -88,17 +211,38 @@ impl Connection { /// Execute a SQL statement and return a Statement handle that /// streams batches via `fetchNextBatch()`. /// - /// No per-statement options: catalog / schema / sessionConf are - /// session-level (`openSession`). + /// Catalog / schema / sessionConf are session-level + /// (`openSession`). Per-statement options on `ExecuteOptions`: + /// - `statementConf` — per-statement Spark conf overlay + /// - `queryTags` — serialised to a comma-separated `key:value` + /// string and placed in `statement_conf["query_tags"]`, + /// matching NodeJS Thrift's `serializeQueryTags` wire shape + /// + /// `options` is omitted/`None` for the no-options path; passing + /// `{ statementConf: {} }` (an empty map) is treated the same as + /// omission to keep the wire shape stable for the common case. #[napi] - pub async fn execute_statement(&self, sql: String) -> napi::Result { + pub async fn execute_statement( + &self, + sql: String, + options: Option, + ) -> napi::Result { let inner = Arc::clone(&self.inner); + // Merge `query_tags` into `statement_conf` at the napi boundary + // so the kernel sees a single conf map. Serialise the tag + // map to the comma-separated `key:value` wire shape NodeJS + // Thrift produces in `serializeQueryTags` + // (`lib/utils/queryTags.ts`). + let merged_conf = build_merged_statement_conf(options)?; guarded(async move { let guard = inner.lock().await; let session = guard.as_ref().ok_or_else(connection_closed_err)?; let mut stmt = session.statement(); stmt.spec().sql(sql); + if let Some(conf) = merged_conf { + stmt.spec().statement_conf(conf); + } let executed = stmt.execute().await.map_err(napi_err_from_kernel)?; // Pass the parent kernel `Statement` into the JS wrapper. @@ -110,6 +254,52 @@ impl Connection { .await } + /// Submit a SQL statement asynchronously and return an + /// `AsyncStatement` handle. The kernel's `Statement::submit()` + /// sends `wait_timeout=0s`, so the server returns immediately + /// with a `statement_id` while the query is still + /// `Pending`/`Running`. JS drives polling via the returned + /// handle's `status()` / `awaitResult()` methods. + /// + /// `options` carries the same per-statement knobs as + /// `executeStatement` (`statementConf` + `queryTags`). The + /// merging + serialisation are shared via + /// `build_merged_statement_conf`. + /// + /// Long-running queries that would blow past the sync polling + /// budget should use this path. Cancel-while-pending is + /// supported through `AsyncStatement.cancel()`; drop-cancel + /// during `awaitResult()` is handled by the kernel's + /// `AwaitResultCancelGuard` (fire-and-forget + /// `cancel_statement` if the future is dropped mid-poll). + #[napi] + pub async fn submit_statement( + &self, + sql: String, + options: Option, + ) -> napi::Result { + let inner = Arc::clone(&self.inner); + let merged_conf = build_merged_statement_conf(options)?; + guarded(async move { + let guard = inner.lock().await; + let session = guard.as_ref().ok_or_else(connection_closed_err)?; + + let mut stmt = session.statement(); + stmt.spec().sql(sql); + if let Some(conf) = merged_conf { + stmt.spec().statement_conf(conf); + } + + let executed_async = stmt.submit().await.map_err(napi_err_from_kernel)?; + // Pass the parent kernel `Statement` into the JS wrapper + // for the same validity-flag lifetime reason as the sync + // path (see `AsyncStatementInner` docs in + // `async_statement.rs`). + Ok(AsyncStatement::from_executed_async(stmt, executed_async)) + }) + .await + } + /// Explicit close. Awaits the server-side `DeleteSession` so the /// JS caller can observe failures (auth revoked mid-session, /// warehouse stopped, network error). Idempotent — a second call @@ -218,4 +408,199 @@ mod tests { }; assert_eq!(conn.session_id(), "session-survives-close"); } + + // ─── ExecuteOptions / build_merged_statement_conf ─────────────────── + + #[test] + fn merged_conf_none_when_options_is_none() { + let result = build_merged_statement_conf(None).unwrap(); + assert!(result.is_none(), "no options → no statement_conf"); + } + + #[test] + fn merged_conf_none_when_both_maps_empty() { + let result = build_merged_statement_conf(Some(ExecuteOptions { + statement_conf: Some(HashMap::new()), + query_tags: Some(HashMap::new()), + })) + .unwrap(); + assert!(result.is_none(), "empty maps → no statement_conf"); + } + + #[test] + fn merged_conf_passes_through_statement_conf() { + let mut conf = HashMap::new(); + conf.insert("ANSI_MODE".to_string(), "true".to_string()); + let result = build_merged_statement_conf(Some(ExecuteOptions { + statement_conf: Some(conf), + query_tags: None, + })) + .unwrap() + .unwrap(); + assert_eq!(result.get("ANSI_MODE").map(String::as_str), Some("true")); + } + + #[test] + fn merged_conf_query_tags_serialised_into_query_tags_key() { + let mut tags = HashMap::new(); + tags.insert("team".to_string(), "platform".to_string()); + let result = build_merged_statement_conf(Some(ExecuteOptions { + statement_conf: None, + query_tags: Some(tags), + })) + .unwrap() + .unwrap(); + // Single-tag case is deterministic regardless of HashMap order. + assert_eq!( + result.get("query_tags").map(String::as_str), + Some("team:platform"), + ); + } + + #[test] + fn merged_conf_query_tags_escape_special_chars_in_values() { + let mut tags = HashMap::new(); + tags.insert("k".to_string(), "v:1,v\\2".to_string()); + let result = build_merged_statement_conf(Some(ExecuteOptions { + statement_conf: None, + query_tags: Some(tags), + })) + .unwrap() + .unwrap(); + let encoded = result.get("query_tags").unwrap(); + // `:` → `\:`, `,` → `\,`, `\` → `\\`. Order in the input is + // `v:1,v\2` so the encoded form is `v\:1\,v\\2`. + assert_eq!(encoded, "k:v\\:1\\,v\\\\2"); + } + + #[test] + fn merged_conf_query_tags_escape_backslash_in_keys() { + let mut tags = HashMap::new(); + tags.insert("k\\1".to_string(), "v".to_string()); + let result = build_merged_statement_conf(Some(ExecuteOptions { + statement_conf: None, + query_tags: Some(tags), + })) + .unwrap() + .unwrap(); + assert_eq!( + result.get("query_tags").map(String::as_str), + Some("k\\\\1:v") + ); + } + + #[test] + fn merged_conf_rejects_dual_query_tags_definition() { + let mut conf = HashMap::new(); + conf.insert("query_tags".to_string(), "explicit:value".to_string()); + let mut tags = HashMap::new(); + tags.insert("team".to_string(), "platform".to_string()); + let err = build_merged_statement_conf(Some(ExecuteOptions { + statement_conf: Some(conf), + query_tags: Some(tags), + })) + .expect_err("must reject when both are set"); + assert!( + err.reason.contains("cannot supply both"), + "error must explain the conflict: {}", + err.reason, + ); + } + + #[test] + fn merged_conf_empty_query_tags_does_not_collide_with_existing_key() { + // An empty `queryTags: {}` map should be ignored, so the + // caller can still pass an explicit + // `statementConf["query_tags"]` alongside `queryTags: {}` + // without tripping the ambiguity guard. Convention: empty + // input maps mean "not supplied". + let mut conf = HashMap::new(); + conf.insert("query_tags".to_string(), "explicit:value".to_string()); + let result = build_merged_statement_conf(Some(ExecuteOptions { + statement_conf: Some(conf), + query_tags: Some(HashMap::new()), + })) + .unwrap() + .unwrap(); + assert_eq!( + result.get("query_tags").map(String::as_str), + Some("explicit:value"), + ); + } + + // ─── DA round-2 M4 parity — byte-shape vs Thrift's serializeQueryTags ─ + + /// `serializeQueryTags` (NodeJS Thrift, `lib/utils/queryTags.ts`) + /// is the canonical wire shape for `query_tags`. Pin the + /// per-tag byte shape produced by the kernel-side serializer + /// against the algorithm Thrift uses, so a regression on either + /// side fails this test. + /// + /// Algorithm (per Thrift): + /// - Keys: backslash doubled (`\` → `\\`); no other escaping + /// - Values: backslash, colon, and comma each backslash-escaped + /// - Tags: joined with `,` + /// - Single-tag case is order-deterministic; multi-tag case + /// asserts each pair appears regardless of HashMap iteration + /// order (the documented order caveat). + #[test] + fn serialize_query_tags_matches_thrift_byte_shape_single_tag() { + let mut tags = HashMap::new(); + tags.insert("team".to_string(), "platform".to_string()); + assert_eq!(serialize_query_tags(&tags), "team:platform"); + } + + #[test] + fn serialize_query_tags_matches_thrift_byte_shape_escapes() { + // Per Thrift's `escapedValue.replace(/[\\:,]/g, c => '\\' + c)`: + // input `v:1,v\2` + // output `v\:1\,v\\2` + let mut tags = HashMap::new(); + tags.insert("k".to_string(), "v:1,v\\2".to_string()); + assert_eq!(serialize_query_tags(&tags), "k:v\\:1\\,v\\\\2"); + } + + #[test] + fn serialize_query_tags_matches_thrift_byte_shape_key_backslash_only() { + // Per Thrift's `escapedKey = key.replace(/\\/g, '\\\\')`: + // input `k\1` + // output `k\\1` + // Colons/commas in keys are NOT escaped on Thrift's path — + // they're only escaped in values. Test pins this asymmetry + // so a future "uniformity" refactor that escapes them in + // keys too gets caught. + let mut tags = HashMap::new(); + tags.insert("k\\1".to_string(), "v".to_string()); + assert_eq!(serialize_query_tags(&tags), "k\\\\1:v"); + } + + #[test] + fn serialize_query_tags_empty_map_yields_empty_string() { + // Thrift returns `undefined` for empty input, but Thrift's + // caller only invokes the serializer when input is non-empty + // (see `lib/DBSQLSession.ts:231` `if (serializedQueryTags + // !== undefined)`). Our serializer is called only by + // `build_merged_statement_conf` which already filters empty + // input out, so this test pins the never-called case for + // defense. + assert_eq!(serialize_query_tags(&HashMap::new()), ""); + } + + #[test] + fn serialize_query_tags_multi_tag_contains_each_pair_regardless_of_order() { + // Multi-tag case: HashMap iteration is non-deterministic, so + // we can't assert a single byte string. Assert each pair is + // present and the join uses `,`. SEA server treats conf + // values as order-insensitive, so this is functionally + // equivalent to the Thrift output regardless of order. + let mut tags = HashMap::new(); + tags.insert("a".to_string(), "1".to_string()); + tags.insert("b".to_string(), "2".to_string()); + let s = serialize_query_tags(&tags); + let pairs: std::collections::HashSet<&str> = s.split(',').collect(); + assert!( + pairs == ["a:1", "b:2"].iter().copied().collect(), + "got: {s}", + ); + } } diff --git a/napi/src/lib.rs b/napi/src/lib.rs index 455bfc91..37d72f02 100644 --- a/napi/src/lib.rs +++ b/napi/src/lib.rs @@ -39,6 +39,7 @@ #[macro_use] extern crate napi_derive; +pub(crate) mod async_statement; pub(crate) mod connection; pub(crate) mod database; pub(crate) mod error;