Skip to content
Closed
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
3 changes: 3 additions & 0 deletions napi/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 13 additions & 0 deletions napi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,19 @@ futures = { version = "0.3", default-features = false, features = ["std"] }
arrow-array = "57"
arrow-schema = "57"
arrow-ipc = "57"
# Copy-into-cage result handoff (`zerocopy.rs`): we read each `RecordBatch`'s
# `ArrayData` buffer tree and copy each buffer into a fresh in-cage
# (V8-allocated) napi `ArrayBuffer`. `arrow-data` names `ArrayData`,
# `arrow-buffer` names `Buffer` / `NullBuffer` / `MutableBuffer`. Both arrive
# transitively via `arrow-array`; declared explicitly (same `57` line) so we
# can name the types directly without leaning on a re-export.
arrow-data = "57"
arrow-buffer = "57"
# `arrow-select::concat::concat_batches` compacts a sliced (non-zero-offset)
# batch into an offset-0 copy before the copycage handoff — the JS importer's
# `makeData` cannot apply a logical element offset, so the kernel normalises
# offsets to 0 here. Same `57` line as the rest of the arrow deps.
arrow-select = "57"

# Error envelope serialization. Already a kernel transitive dep; the
# direct declaration is so we can use `serde_json::json!` in
Expand Down
39 changes: 39 additions & 0 deletions napi/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -669,6 +669,21 @@ export declare class AsyncResultHandle {
* `Statement.fetchNextBatch()` payload for the same query.
*/
fetchNextBatch(): Promise<ArrowBatch | null>
/**
* Copy-into-cage variant of `fetchNextBatch` (Flavour A): hands the
* batch's Arrow buffers to JS as in-cage (V8-allocated) `ArrayBuffer`s
* with the bytes `memcpy`'d in, instead of serialising to Arrow IPC
* bytes. Mirrors `Statement::fetch_next_batch_copycage` exactly — this
* is the handle the *async query path* (`awaitResult()`) exposes, so
* the driver's normal `executeStatement` flow can use copycage rather
* than silently falling back to IPC. See `crate::zerocopy::CopyCageBatch`.
*
* Any offset-sliced array is compacted to offset 0 first
* (`zerocopy::compact_to_offset_zero`); the JS importer's `makeData`
* cannot apply a logical element offset. Returns `null` at end of
* stream, exactly like `fetchNextBatch`.
*/
fetchNextBatchCopycage(): Promise<{ numRows: number, columns: any[] } | null>
/**
* Result schema as an Arrow IPC payload (schema header only,
* no record-batch message). Available before any batches have
Expand Down Expand Up @@ -1007,6 +1022,30 @@ export declare class Statement {
* succeed or fail consistently.
*/
fetchNextBatch(): Promise<ArrowBatch | null>
/**
* Copy-into-cage variant of `fetchNextBatch` (Flavour A): hands the
* batch's Arrow buffers to JS as in-cage (V8-allocated) `ArrayBuffer`s
* with the bytes `memcpy`'d in, instead of serialising to Arrow IPC
* bytes (`fetchNextBatch`). See `crate::zerocopy::CopyCageBatch`.
*
* Cage-safe (works under the V8 sandbox / Electron) and GC-clean — V8
* owns the bytes, so no Arc/finalizer is needed. Costs one plain copy
* per buffer but still avoids the IPC path's serialize + decode passes.
*
* Any offset-sliced array is compacted to offset 0 first
* (`zerocopy::compact_to_offset_zero`), because the JS importer's
* `makeData` cannot apply a logical element offset.
*
* Returns `null` at end of stream, exactly like `fetchNextBatch`. Same
* error/auto-close/finished semantics — only the result encoding
* differs, so the two are interchangeable per-fetch.
*
* `ts_return_type` pins a structural shape in the generated d.ts:
* `CopyCageBatch` is a manual `ToNapiValue` type (not a `#[napi(object)]`
* struct), so napi-rs has no interface to emit for it. The driver
* re-types the value precisely via `KernelArrowImport.ts`.
*/
fetchNextBatchCopycage(): Promise<{ numRows: number, columns: any[] } | null>
/**
* Result schema as an Arrow IPC payload (schema header only, no
* record-batch message). Available before any batches have been
Expand Down
54 changes: 54 additions & 0 deletions napi/src/async_statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,60 @@ impl AsyncResultHandle {
.await
}

/// Copy-into-cage variant of `fetchNextBatch` (Flavour A): hands the
/// batch's Arrow buffers to JS as in-cage (V8-allocated) `ArrayBuffer`s
/// with the bytes `memcpy`'d in, instead of serialising to Arrow IPC
/// bytes. Mirrors `Statement::fetch_next_batch_copycage` exactly — this
/// is the handle the *async query path* (`awaitResult()`) exposes, so
/// the driver's normal `executeStatement` flow can use copycage rather
/// than silently falling back to IPC. See `crate::zerocopy::CopyCageBatch`.
///
/// Any offset-sliced array is compacted to offset 0 first
/// (`zerocopy::compact_to_offset_zero`); the JS importer's `makeData`
/// cannot apply a logical element offset. Returns `null` at end of
/// stream, exactly like `fetchNextBatch`.
#[napi(ts_return_type = "Promise<{ numRows: number, columns: any[] } | null>")]
pub async fn fetch_next_batch_copycage(
&self,
) -> napi::Result<Option<crate::zerocopy::CopyCageBatch>> {
let inner = Arc::clone(&self.inner);
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"),
)),
));
}
};
// Normalise any offset-sliced array to offset 0 — the JS importer
// builds every `Data` at offset 0 and cannot honour a logical
// element offset. Inline (non-sliced) batches return unchanged.
let record_batch = crate::zerocopy::compact_to_offset_zero(record_batch.clone())
.map_err(|e| {
napi_err_from_kernel(
KernelError::internal()
.message(format!("copycage offset-0 compaction failed: {e}")),
)
})?;
Ok(Some(crate::zerocopy::CopyCageBatch::new(record_batch)))
})
.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` —
Expand Down
1 change: 1 addition & 0 deletions napi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ pub(crate) mod result;
pub(crate) mod runtime;
pub(crate) mod statement;
pub(crate) mod util;
pub(crate) mod zerocopy;

/// Returns the native binding's crate version (`CARGO_PKG_VERSION`).
///
Expand Down
71 changes: 71 additions & 0 deletions napi/src/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,77 @@ impl Statement {
.await
}

/// Copy-into-cage variant of `fetchNextBatch` (Flavour A): hands the
/// batch's Arrow buffers to JS as in-cage (V8-allocated) `ArrayBuffer`s
/// with the bytes `memcpy`'d in, instead of serialising to Arrow IPC
/// bytes (`fetchNextBatch`). See `crate::zerocopy::CopyCageBatch`.
///
/// Cage-safe (works under the V8 sandbox / Electron) and GC-clean — V8
/// owns the bytes, so no Arc/finalizer is needed. Costs one plain copy
/// per buffer but still avoids the IPC path's serialize + decode passes.
///
/// Any offset-sliced array is compacted to offset 0 first
/// (`zerocopy::compact_to_offset_zero`), because the JS importer's
/// `makeData` cannot apply a logical element offset.
///
/// Returns `null` at end of stream, exactly like `fetchNextBatch`. Same
/// error/auto-close/finished semantics — only the result encoding
/// differs, so the two are interchangeable per-fetch.
///
/// `ts_return_type` pins a structural shape in the generated d.ts:
/// `CopyCageBatch` is a manual `ToNapiValue` type (not a `#[napi(object)]`
/// struct), so napi-rs has no interface to emit for it. The driver
/// re-types the value precisely via `KernelArrowImport.ts`.
#[napi(ts_return_type = "Promise<{ numRows: number, columns: any[] } | null>")]
pub async fn fetch_next_batch_copycage(
&self,
) -> napi::Result<Option<crate::zerocopy::CopyCageBatch>> {
let inner = Arc::clone(&self.inner);
let finished = Arc::clone(&self.finished);
guarded(async move {
let mut guard = inner.lock().await;
let inner_state = guard.as_mut().ok_or_else(statement_closed_err)?;
let maybe_batch = inner_state
.next_batch()
.await
.map_err(napi_err_from_kernel)?;
let Some(batch) = maybe_batch else {
finished.store(true, Ordering::Release);
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-sql-kernel-napi v{} cannot decode this batch \
shape, upgrade the binding",
env!("CARGO_PKG_VERSION"),
)),
));
}
};
// Normalise any offset-sliced array to offset 0 — the JS importer
// builds every `Data` at offset 0 and cannot honour a logical
// element offset, so a sliced array would read the wrong rows.
// Inline (non-sliced) Databricks batches return unchanged.
let record_batch = crate::zerocopy::compact_to_offset_zero(record_batch.clone())
.map_err(|e| {
napi_err_from_kernel(
KernelError::internal()
.message(format!("copycage offset-0 compaction failed: {e}")),
)
})?;
// `RecordBatch::clone` is a shallow Arc bump (no buffer copy); the
// owned batch lives until the bytes are memcpy'd into the cage in
// `CopyCageBatch`'s `ToNapiValue`, after which it drops — V8 owns
// the copies, so no finalizer keeps the native memory alive.
Ok(Some(crate::zerocopy::CopyCageBatch::new(record_batch)))
})
.await
}

/// Result schema as an Arrow IPC payload (schema header only, no
/// record-batch message). Available before any batches have been
/// fetched, and remains available after `close()` — the kernel
Expand Down
Loading
Loading