Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion napi/src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,11 @@ impl Connection {
stmt.spec().sql(sql);

let executed = stmt.execute().await.map_err(napi_err_from_kernel)?;
Ok(Statement::from_executed(executed))
// Pass the parent kernel `Statement` into the JS wrapper.
// Dropping it here would invalidate the executed handle
// via the shared ValidityFlag — see `StatementInner` docs
// in `statement.rs` for the rationale.
Ok(Statement::from_executed(stmt, executed))
})
.await
}
Expand Down
84 changes: 69 additions & 15 deletions napi/src/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,39 @@ use arrow_ipc::writer::StreamWriter;
use arrow_schema::SchemaRef;
use databricks_sql_kernel::{
Error as KernelError, ExecutedStatement, ExecutedStatementHandle, ResultBatch,
Statement as KernelStatement,
};

use crate::error::napi_err_from_kernel;
use crate::result::{ArrowBatch, ArrowSchema};
use crate::runtime;
use crate::util::guarded;

/// Inner state for the JS-visible `Statement` wrapper.
///
/// **Why we also hold the parent kernel `Statement`:** the kernel's
/// `Statement::Drop` (`src/statement/mutable.rs:341-361`) invalidates
/// its produced `ExecutedStatement` via the shared `ValidityFlag`. If
/// the binding wrapper held only the `ExecutedStatement`, the parent
/// kernel `Statement` constructed in `Connection::execute_statement`
/// would drop at the end of that function, flipping the validity flag
/// and rendering every subsequent `cancel()` / `close()` call against
/// the executed handle a no-op that throws
/// `InvalidStatementHandle("executed-statement handle has been
/// invalidated by a re-execute on its parent Statement")`.
///
/// Keeping the kernel `Statement` alive in the same `Arc<Mutex<…>>`
/// as the `ExecutedStatement` ties their lifetimes together — the
/// validity flag stays set for as long as JS holds the wrapper.
struct StatementInner {
/// The kernel's `Statement` (mutable). Kept alive solely to
/// prevent its `Drop` from invalidating `executed`.
_parent: KernelStatement,
/// The executed handle — drives `fetchNextBatch` / `cancel` /
/// `close`.
executed: ExecutedStatement,
}

/// Opaque executed-statement handle.
///
/// **Current concurrency shape** — every method takes `inner.lock()`
Expand All @@ -62,7 +88,11 @@ use crate::util::guarded;
/// disposed statement can still read them.
#[napi]
pub struct Statement {
inner: Arc<Mutex<Option<ExecutedStatement>>>,
/// Wraps the kernel `Statement` + `ExecutedStatement` pair so the
/// parent's `Drop` doesn't fire (and invalidate the executed
/// handle via the shared `ValidityFlag`) while JS still holds
/// this wrapper. See `StatementInner` docs above.
inner: Arc<Mutex<Option<StatementInner>>>,
/// Schema captured at construction. Available even after `close()`.
schema: SchemaRef,
/// Server-issued id. Available even after `close()` for log
Expand All @@ -79,13 +109,20 @@ pub struct Statement {
impl Statement {
/// Crate-internal constructor — called from
/// `Connection::execute_statement` once the kernel hands back the
/// `ExecutedStatement`. Caches `schema` and `statement_id` so
/// they're readable after `close()`.
pub(crate) fn from_executed(executed: ExecutedStatement) -> Self {
/// `ExecutedStatement`. The parent kernel `Statement` is passed
/// in alongside so its `Drop` doesn't fire while the JS side
/// still holds the executed handle (see `StatementInner` docs
/// above). `schema` and `statement_id` are read off the executed
/// handle here and cached on the wrapper so they remain readable
/// after `close()` for log correlation / error reporting.
pub(crate) fn from_executed(parent: KernelStatement, executed: ExecutedStatement) -> Self {
let schema = executed.schema();
let statement_id = executed.statement_id().to_owned();
Self {
inner: Arc::new(Mutex::new(Some(executed))),
inner: Arc::new(Mutex::new(Some(StatementInner {
_parent: parent,
executed,
}))),
schema,
statement_id,
finished: Arc::new(AtomicBool::new(false)),
Expand Down Expand Up @@ -119,7 +156,8 @@ impl Statement {
let finished = Arc::clone(&self.finished);
guarded(async move {
let mut guard = inner.lock().await;
let executed = guard.as_mut().ok_or_else(statement_closed_err)?;
let inner_state = guard.as_mut().ok_or_else(statement_closed_err)?;
let executed = &mut inner_state.executed;

let stream = executed.result_stream_mut();
let maybe_batch = stream.next_batch().await.map_err(napi_err_from_kernel)?;
Expand Down Expand Up @@ -204,8 +242,12 @@ impl Statement {
let inner = Arc::clone(&self.inner);
guarded(async move {
let guard = inner.lock().await;
let executed = guard.as_ref().ok_or_else(statement_closed_err)?;
executed.cancel().await.map_err(napi_err_from_kernel)
let inner_state = guard.as_ref().ok_or_else(statement_closed_err)?;
inner_state
.executed
.cancel()
.await
.map_err(napi_err_from_kernel)
})
.await
}
Expand All @@ -231,14 +273,22 @@ impl Statement {
pub async fn close(&self) -> napi::Result<()> {
let inner = Arc::clone(&self.inner);
guarded(async move {
// Take the handle out so `Drop` knows there's nothing left
// to clean up.
let executed = {
// Take the inner state out so `Drop` knows there's nothing
// left to clean up. The parent kernel `Statement`'s Drop
// runs here too — but only AFTER the executed handle's
// close has finished, so we still observe a clean
// server-side close result before the validity flag flips.
let inner_state = {
let mut guard = inner.lock().await;
guard.take()
};
if let Some(executed) = executed {
executed.close().await.map_err(napi_err_from_kernel)?;
if let Some(inner_state) = inner_state {
inner_state
.executed
.close()
.await
.map_err(napi_err_from_kernel)?;
// _parent drops here, after close has resolved.
}
Ok(())
})
Expand All @@ -261,12 +311,16 @@ impl Drop for Statement {
};
let inner = Arc::clone(&self.inner);
handle.spawn(async move {
// Drop the executed statement on the runtime. The kernel's
// Drop the inner state on the runtime. The kernel's
// `ExecutedStatement::Drop` already spawns a fire-and-forget
// `close_statement` against its own captured handle, so we
// just need to ensure the value is dropped inside a tokio
// context (the kernel's Drop reads `runtime_handle.clone()`
// and spawns; that handle is the same one we captured here).
// and spawns; that handle is the same one we captured
// here). The kernel `Statement` we kept alive in
// `_parent` drops at the same time, but it only owns
// local state (its Drop is non-async — see
// `src/statement/mutable.rs:341-361`).
let _taken = {
let mut guard = inner.lock().await;
guard.take()
Expand Down
3 changes: 1 addition & 2 deletions src/metadata/static_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -837,8 +837,7 @@ mod tests {
.downcast_ref::<Int32Array>()
.unwrap();

let mut by_name: std::collections::HashMap<&str, i32> =
std::collections::HashMap::new();
let mut by_name: std::collections::HashMap<&str, i32> = std::collections::HashMap::new();
for i in 0..rb.num_rows() {
by_name.insert(names.value(i), data_types.value(i));
}
Expand Down
38 changes: 13 additions & 25 deletions src/metadata/type_mapping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,11 +148,7 @@ const MAX_PARSE_DEPTH: usize = 64;
/// only consulted at the `INTERVAL` arm — it has no meaning for
/// nested composites, so passing it down is harmless and lets the
/// caller specify it once.
fn parse_type(
s: &str,
type_interval_type: Option<&str>,
depth: usize,
) -> Option<DataType> {
fn parse_type(s: &str, type_interval_type: Option<&str>, depth: usize) -> Option<DataType> {
if depth >= MAX_PARSE_DEPTH {
return None;
}
Expand Down Expand Up @@ -279,11 +275,7 @@ fn split_top_level_commas(s: &str) -> Vec<&str> {
/// `list_(t)` default also uses `"item"`. Using anything else would
/// make the empty-result schema fail field-level equality against
/// the non-empty Arrow IPC payload.
fn parse_array(
s: &str,
type_interval_type: Option<&str>,
depth: usize,
) -> Option<DataType> {
fn parse_array(s: &str, type_interval_type: Option<&str>, depth: usize) -> Option<DataType> {
let inner = inside_angle_brackets(s)?;
let inner_dt = parse_type(inner, type_interval_type, depth + 1)?;
Some(DataType::List(Arc::new(Field::new_list_field(
Expand All @@ -293,11 +285,7 @@ fn parse_array(

/// Parse `MAP<K, V>` into Arrow's canonical `Map(entries: Struct{key, value})`.
/// Field names `"entries"` / `"key"` / `"value"` match pyarrow.map_(k, v).
fn parse_map(
s: &str,
type_interval_type: Option<&str>,
depth: usize,
) -> Option<DataType> {
fn parse_map(s: &str, type_interval_type: Option<&str>, depth: usize) -> Option<DataType> {
let inner = inside_angle_brackets(s)?;
let parts = split_top_level_commas(inner);
if parts.len() != 2 {
Expand All @@ -319,11 +307,7 @@ fn parse_map(
/// Parse `STRUCT<name:type, name:type, ...>` into `Struct(Fields::from([Field; N]))`.
/// Each child field is nullable (SEA's manifest doesn't carry per-field
/// nullability) — same convention used elsewhere in the kernel.
fn parse_struct(
s: &str,
type_interval_type: Option<&str>,
depth: usize,
) -> Option<DataType> {
fn parse_struct(s: &str, type_interval_type: Option<&str>, depth: usize) -> Option<DataType> {
let inner = inside_angle_brackets(s)?;
if inner.is_empty() {
return Some(DataType::Struct(Fields::empty()));
Expand Down Expand Up @@ -820,7 +804,10 @@ mod tests {
assert_eq!(databricks_type_to_xdbc("ARRAY<STRING>"), JDBC_ARRAY);
assert_eq!(databricks_type_to_xdbc("ARRAY<ARRAY<INT>>"), JDBC_ARRAY);
assert_eq!(databricks_type_to_xdbc("MAP<STRING,INT>"), JDBC_JAVA_OBJECT);
assert_eq!(databricks_type_to_xdbc("MAP<STRING, STRING>"), JDBC_JAVA_OBJECT);
assert_eq!(
databricks_type_to_xdbc("MAP<STRING, STRING>"),
JDBC_JAVA_OBJECT
);
assert_eq!(databricks_type_to_xdbc("STRUCT<a:INT>"), JDBC_STRUCT);
assert_eq!(
databricks_type_to_xdbc("STRUCT<a:INT, b:STRING>"),
Expand Down Expand Up @@ -977,9 +964,7 @@ mod tests {
// Server-controlled `type_text` could nest arbitrarily;
// without a depth guard the recursive parser would blow the
// stack. 64 levels of nesting is well past anything real.
let deep = "ARRAY<".repeat(MAX_PARSE_DEPTH + 1)
+ "INT"
+ &">".repeat(MAX_PARSE_DEPTH + 1);
let deep = "ARRAY<".repeat(MAX_PARSE_DEPTH + 1) + "INT" + &">".repeat(MAX_PARSE_DEPTH + 1);
assert_eq!(databricks_type_to_arrow(&deep), DataType::Utf8);
}

Expand All @@ -993,7 +978,10 @@ mod tests {
match dt {
DataType::Decimal128(p, s) => {
assert!(p >= 1, "precision must clamp to >= 1, got {p}");
assert!((-38..=38).contains(&s), "scale must be in [-38,38], got {s}");
assert!(
(-38..=38).contains(&s),
"scale must be in [-38,38], got {s}"
);
}
other => panic!("expected Decimal128, got {other:?}"),
}
Expand Down
20 changes: 18 additions & 2 deletions src/reader/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -781,8 +781,24 @@ mod tests {
// keyword-matching the `type_text`. Bare `"INTERVAL"` (no
// qualifier) historically meant DAY_TIME; preserve that.
let manifest = make_manifest(vec![
make_column_info("ym", "INTERVAL", "INTERVAL YEAR TO MONTH", 0, None, None, None),
make_column_info("ds", "INTERVAL", "INTERVAL DAY TO SECOND", 1, None, None, None),
make_column_info(
"ym",
"INTERVAL",
"INTERVAL YEAR TO MONTH",
0,
None,
None,
None,
),
make_column_info(
"ds",
"INTERVAL",
"INTERVAL DAY TO SECOND",
1,
None,
None,
None,
),
make_column_info("bare", "INTERVAL", "INTERVAL", 2, None, None, None),
]);
let schema = ResultReaderFactory::extract_schema_from_manifest(Some(&manifest)).unwrap();
Expand Down