@@ -37,13 +37,39 @@ use arrow_ipc::writer::StreamWriter;
3737use arrow_schema:: SchemaRef ;
3838use databricks_sql_kernel:: {
3939 Error as KernelError , ExecutedStatement , ExecutedStatementHandle , ResultBatch ,
40+ Statement as KernelStatement ,
4041} ;
4142
4243use crate :: error:: napi_err_from_kernel;
4344use crate :: result:: { ArrowBatch , ArrowSchema } ;
4445use crate :: runtime;
4546use crate :: util:: guarded;
4647
48+ /// Inner state for the JS-visible `Statement` wrapper.
49+ ///
50+ /// **Why we also hold the parent kernel `Statement`:** the kernel's
51+ /// `Statement::Drop` (`src/statement/mutable.rs:341-361`) invalidates
52+ /// its produced `ExecutedStatement` via the shared `ValidityFlag`. If
53+ /// the binding wrapper held only the `ExecutedStatement`, the parent
54+ /// kernel `Statement` constructed in `Connection::execute_statement`
55+ /// would drop at the end of that function, flipping the validity flag
56+ /// and rendering every subsequent `cancel()` / `close()` call against
57+ /// the executed handle a no-op that throws
58+ /// `InvalidStatementHandle("executed-statement handle has been
59+ /// invalidated by a re-execute on its parent Statement")`.
60+ ///
61+ /// Keeping the kernel `Statement` alive in the same `Arc<Mutex<…>>`
62+ /// as the `ExecutedStatement` ties their lifetimes together — the
63+ /// validity flag stays set for as long as JS holds the wrapper.
64+ struct StatementInner {
65+ /// The kernel's `Statement` (mutable). Kept alive solely to
66+ /// prevent its `Drop` from invalidating `executed`.
67+ _parent : KernelStatement ,
68+ /// The executed handle — drives `fetchNextBatch` / `cancel` /
69+ /// `close`.
70+ executed : ExecutedStatement ,
71+ }
72+
4773/// Opaque executed-statement handle.
4874///
4975/// **Current concurrency shape** — every method takes `inner.lock()`
@@ -62,7 +88,11 @@ use crate::util::guarded;
6288/// disposed statement can still read them.
6389#[ napi]
6490pub struct Statement {
65- inner : Arc < Mutex < Option < ExecutedStatement > > > ,
91+ /// Wraps the kernel `Statement` + `ExecutedStatement` pair so the
92+ /// parent's `Drop` doesn't fire (and invalidate the executed
93+ /// handle via the shared `ValidityFlag`) while JS still holds
94+ /// this wrapper. See `StatementInner` docs above.
95+ inner : Arc < Mutex < Option < StatementInner > > > ,
6696 /// Schema captured at construction. Available even after `close()`.
6797 schema : SchemaRef ,
6898 /// Server-issued id. Available even after `close()` for log
@@ -79,13 +109,20 @@ pub struct Statement {
79109impl Statement {
80110 /// Crate-internal constructor — called from
81111 /// `Connection::execute_statement` once the kernel hands back the
82- /// `ExecutedStatement`. Caches `schema` and `statement_id` so
83- /// they're readable after `close()`.
84- pub ( crate ) fn from_executed ( executed : ExecutedStatement ) -> Self {
112+ /// `ExecutedStatement`. The parent kernel `Statement` is passed
113+ /// in alongside so its `Drop` doesn't fire while the JS side
114+ /// still holds the executed handle (see `StatementInner` docs
115+ /// above). `schema` and `statement_id` are read off the executed
116+ /// handle here and cached on the wrapper so they remain readable
117+ /// after `close()` for log correlation / error reporting.
118+ pub ( crate ) fn from_executed ( parent : KernelStatement , executed : ExecutedStatement ) -> Self {
85119 let schema = executed. schema ( ) ;
86120 let statement_id = executed. statement_id ( ) . to_owned ( ) ;
87121 Self {
88- inner : Arc :: new ( Mutex :: new ( Some ( executed) ) ) ,
122+ inner : Arc :: new ( Mutex :: new ( Some ( StatementInner {
123+ _parent : parent,
124+ executed,
125+ } ) ) ) ,
89126 schema,
90127 statement_id,
91128 finished : Arc :: new ( AtomicBool :: new ( false ) ) ,
@@ -119,7 +156,8 @@ impl Statement {
119156 let finished = Arc :: clone ( & self . finished ) ;
120157 guarded ( async move {
121158 let mut guard = inner. lock ( ) . await ;
122- let executed = guard. as_mut ( ) . ok_or_else ( statement_closed_err) ?;
159+ let inner_state = guard. as_mut ( ) . ok_or_else ( statement_closed_err) ?;
160+ let executed = & mut inner_state. executed ;
123161
124162 let stream = executed. result_stream_mut ( ) ;
125163 let maybe_batch = stream. next_batch ( ) . await . map_err ( napi_err_from_kernel) ?;
@@ -204,8 +242,12 @@ impl Statement {
204242 let inner = Arc :: clone ( & self . inner ) ;
205243 guarded ( async move {
206244 let guard = inner. lock ( ) . await ;
207- let executed = guard. as_ref ( ) . ok_or_else ( statement_closed_err) ?;
208- executed. cancel ( ) . await . map_err ( napi_err_from_kernel)
245+ let inner_state = guard. as_ref ( ) . ok_or_else ( statement_closed_err) ?;
246+ inner_state
247+ . executed
248+ . cancel ( )
249+ . await
250+ . map_err ( napi_err_from_kernel)
209251 } )
210252 . await
211253 }
@@ -231,14 +273,22 @@ impl Statement {
231273 pub async fn close ( & self ) -> napi:: Result < ( ) > {
232274 let inner = Arc :: clone ( & self . inner ) ;
233275 guarded ( async move {
234- // Take the handle out so `Drop` knows there's nothing left
235- // to clean up.
236- let executed = {
276+ // Take the inner state out so `Drop` knows there's nothing
277+ // left to clean up. The parent kernel `Statement`'s Drop
278+ // runs here too — but only AFTER the executed handle's
279+ // close has finished, so we still observe a clean
280+ // server-side close result before the validity flag flips.
281+ let inner_state = {
237282 let mut guard = inner. lock ( ) . await ;
238283 guard. take ( )
239284 } ;
240- if let Some ( executed) = executed {
241- executed. close ( ) . await . map_err ( napi_err_from_kernel) ?;
285+ if let Some ( inner_state) = inner_state {
286+ inner_state
287+ . executed
288+ . close ( )
289+ . await
290+ . map_err ( napi_err_from_kernel) ?;
291+ // _parent drops here, after close has resolved.
242292 }
243293 Ok ( ( ) )
244294 } )
@@ -261,12 +311,16 @@ impl Drop for Statement {
261311 } ;
262312 let inner = Arc :: clone ( & self . inner ) ;
263313 handle. spawn ( async move {
264- // Drop the executed statement on the runtime. The kernel's
314+ // Drop the inner state on the runtime. The kernel's
265315 // `ExecutedStatement::Drop` already spawns a fire-and-forget
266316 // `close_statement` against its own captured handle, so we
267317 // just need to ensure the value is dropped inside a tokio
268318 // context (the kernel's Drop reads `runtime_handle.clone()`
269- // and spawns; that handle is the same one we captured here).
319+ // and spawns; that handle is the same one we captured
320+ // here). The kernel `Statement` we kept alive in
321+ // `_parent` drops at the same time, but it only owns
322+ // local state (its Drop is non-async — see
323+ // `src/statement/mutable.rs:341-361`).
270324 let _taken = {
271325 let mut guard = inner. lock ( ) . await ;
272326 guard. take ( )
0 commit comments