diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 6aa75289..edd11940 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -16,6 +16,11 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Changed +- `Session::attach_async_statement` no longer infers modified-row counts from + ambiguous result-column names when the submitted SQL is unavailable. ID-only + attachments now report only counts supplied in statement status metadata; + retain the handle returned by `Statement::submit` when inferred DML counts + are required. - Rust ADBC requests identify themselves as `RustADBCDatabricksDriver/` with an optional partner entry from `adbc.databricks.user_agent_entry` (`adbc.spark.user_agent_entry` is a compatibility alias). `User-Agent` in @@ -25,6 +30,12 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Fixed +- Affected-row inference now uses the submitted statement type, so ordinary + query results with columns such as `num_affected_rows` remain query rows. + Inference from result rows is limited to recognized modifying forms; other + forms, including SQL scripting blocks, leave the inferred count unknown. + Count result schemas for DML, COPY INTO, CTAS/RTAS, and literal EXECUTE + IMMEDIATE writes continue to populate `num_modified_rows`. - `Session::open` authenticates once before resolving feature flags. A failed OAuth token request now fails the open immediately instead of being sent a second time by CreateSession. --- diff --git a/docs/spec-v0.md b/docs/spec-v0.md index 80b7685e..3ac610cc 100644 --- a/docs/spec-v0.md +++ b/docs/spec-v0.md @@ -705,6 +705,13 @@ impl ExecutedAsyncStatement { pub async fn fetch_result(&self) -> Result; } +// Session::attach_async_statement(statement_id) returns a non-owning handle +// for resume-by-id workflows. An attached handle has no submitted SQL, so it +// cannot distinguish a DML count result from a query using the same column +// names. Its modified-row count reflects only status metadata and otherwise +// remains unknown, including after result fetching. Callers that require +// inferred DML counts retain the handle returned by Statement::submit(). + // `statement_id`, `cancel`, `close` come from `ExecutedStatementHandle`. // Both ExecutedStatement and ExecutedAsyncStatement fire fire-and-forget diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index c626ee89..fb4dded9 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -705,6 +705,12 @@ impl Session { /// *closed* statement is not an error — the server keeps reporting /// `CLOSED` (and terminal `SUCCEEDED`/`FAILED`) until GC, so the /// returned handle's `status()` surfaces the real server state. + /// + /// Because an ID-only attachment has no submitted SQL, it cannot safely + /// infer modified-row counts from ambiguous result-column names. Its + /// `num_modified_rows` is populated only when status metadata supplies a + /// count; retain the original submitted handle when inferred counts are + /// required. fn attach_async_statement( &self, py: Python<'_>, diff --git a/src/client/mod.rs b/src/client/mod.rs index e2f59a71..6b495283 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -46,6 +46,6 @@ pub use retry::{ pub(crate) use sea::SeaRestTransport; pub(crate) use transport::{ ChunkLinkFetchResult, DirectOutcome, ExecuteResponse, ExecuteResult, ExecuteResultData, - ExecutionTimeout, InlineChunkFetchResult, SessionAttribution, SessionInfo, Transport, - TransportConfig, + ExecutionTimeout, FetchResultOutcome, InlineChunkFetchResult, SessionAttribution, SessionInfo, + Transport, TransportConfig, }; diff --git a/src/client/sea.rs b/src/client/sea.rs index 2a490aac..ceb269ba 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -20,8 +20,8 @@ use crate::client::retry::RequestType; use crate::client::{ ChunkLinkFetchResult, DatabricksHttpClient, DirectOutcome, ExecuteResponse, ExecuteResult, - ExecuteResultData, ExecutionTimeout, InlineChunkFetchResult, SessionAttribution, SessionInfo, - Transport, TransportConfig, + ExecuteResultData, ExecutionTimeout, FetchResultOutcome, InlineChunkFetchResult, + SessionAttribution, SessionInfo, Transport, TransportConfig, }; use crate::kernel_error::{Error, Result}; use crate::klog::{debug, warn}; @@ -128,10 +128,6 @@ enum SessionRoute { struct TerminalExecution { statement_id: String, outcome: TerminalExecutionOutcome, - /// Whether the terminal response came from GetStatementStatus. The old - /// synchronous path enriched those responses with a DML count, but not an - /// initial terminal ExecuteStatement response. - response_from_poll: bool, } /// Terminal-state mapping belongs to execution, while reader/schema creation @@ -433,19 +429,19 @@ impl SeaRestTransport { } /// Fetch statement status for callers that expose the status directly. - /// - /// Unlike the synchronous execution loop, async status callers need the DML row - /// count before fetching the result, so this path retains the existing enrichment. async fn get_statement_status( &self, statement_id: &str, session_attribution: SessionAttribution, + infer_num_modified_rows: bool, ) -> Result { let mut response = self .get_statement_status_raw(statement_id, session_attribution) .await?; - self.enrich_num_modified_rows(&mut response, session_attribution) - .await; + if infer_num_modified_rows { + self.enrich_num_modified_rows(&mut response, session_attribution) + .await; + } Ok(response) } @@ -459,8 +455,8 @@ impl SeaRestTransport { /// explicit result fetch. No extra round-trip: the count rides on the status /// poll the caller already made. /// - /// Gated on the manifest's column signature so SELECTs (real columns) never - /// hit the decode path; a DML-count result is always tiny and inline. + /// Callers must enable this only for submitted DML because aliases can exactly + /// match the result signature. async fn enrich_num_modified_rows( &self, response: &mut ExecuteResponse, @@ -587,10 +583,9 @@ impl SeaRestTransport { response: ExecuteResponse, timeout: ExecutionTimeout, status_request_in_flight: &AtomicBool, - ) -> Result<(ExecuteResponse, bool)> { + ) -> Result { let started = std::time::Instant::now(); let mut current_response = response; - let mut response_from_poll = false; loop { match current_response.status.state { @@ -635,13 +630,12 @@ impl SeaRestTransport { .await; status_request_in_flight.store(false, Ordering::Release); current_response = status_result?; - response_from_poll = true; } StatementState::Succeeded | StatementState::Failed | StatementState::Canceled | StatementState::Closed => { - return Ok((current_response, response_from_poll)); + return Ok(current_response); } } } @@ -846,7 +840,7 @@ impl SeaRestTransport { } } - let (response, response_from_poll) = self + let response = self .wait_for_terminal(response, timeout, status_request_in_flight) .await .map_err(|error| TerminalExecutionFailure { @@ -865,7 +859,6 @@ impl SeaRestTransport { Ok(TerminalExecution { statement_id, outcome, - response_from_poll, }) } @@ -1012,9 +1005,8 @@ impl SeaRestTransport { let TerminalExecution { statement_id, outcome, - response_from_poll, } = terminal; - let mut response = match outcome { + let response = match outcome { TerminalExecutionOutcome::Succeeded(response) => response, TerminalExecutionOutcome::Failed(error) => { self.close_orphaned_statement(&statement_id, "terminal_outcome") @@ -1022,15 +1014,6 @@ impl SeaRestTransport { return Err(error); } }; - // Preserve the old sync behavior: a terminal GetStatementStatus response - // is DML-enriched before the result reader is handed off. It now happens - // after terminal mapping, keeping this result work out of the execution - // phase without shifting it onto the public result stream. - if response_from_poll { - self.enrich_num_modified_rows(&mut response, SessionAttribution::Current) - .await; - } - let reader_factory = self.reader_factory()?; match self.materialise_response(reader_factory, response).await { Ok(result) => Ok(result), @@ -1393,19 +1376,32 @@ impl Transport for SeaRestTransport { &self, statement_id: &str, session_attribution: SessionAttribution, - ) -> Result> { + infer_num_modified_rows: bool, + ) -> Result { let response = self - .get_statement_status(statement_id, session_attribution) + .get_statement_status(statement_id, session_attribution, infer_num_modified_rows) .await?; + let status = response.status.clone(); match Self::terminal_outcome(response) { StatementOutcome::Done(r) => { - let reader_factory = self.reader_factory()?; - let reader = reader_factory + let reader_factory = match self.reader_factory() { + Ok(reader_factory) => reader_factory, + Err(error) => { + return Ok(FetchResultOutcome::TerminalError { error, status }); + } + }; + let reader = match reader_factory .create_reader(&r.statement_id, &r, session_attribution) - .await?; + .await + { + Ok(reader) => reader, + Err(error) => { + return Ok(FetchResultOutcome::TerminalError { error, status }); + } + }; let telemetry_result_format = Self::telemetry_result_format(&r); let telemetry_is_compressed = Self::telemetry_is_compressed(&r); - Ok(Some(ExecuteResult { + Ok(FetchResultOutcome::Ready(ExecuteResult { statement_id: r.statement_id, reader, manifest: r.manifest, @@ -1414,8 +1410,8 @@ impl Transport for SeaRestTransport { status: r.status, })) } - StatementOutcome::NotReady(_) => Ok(None), - StatementOutcome::Err(e) => Err(e), + StatementOutcome::NotReady(_) => Ok(FetchResultOutcome::NotReady), + StatementOutcome::Err(error) => Ok(FetchResultOutcome::TerminalError { error, status }), } } @@ -1423,8 +1419,9 @@ impl Transport for SeaRestTransport { &self, statement_id: &str, session_attribution: SessionAttribution, + infer_num_modified_rows: bool, ) -> Result { - self.get_statement_status(statement_id, session_attribution) + self.get_statement_status(statement_id, session_attribution, infer_num_modified_rows) .await } @@ -1998,7 +1995,7 @@ mod tests { } #[tokio::test] - async fn execute_statement_enriches_polled_dml_before_result_handoff() { + async fn execute_statement_leaves_dml_inference_to_statement_layer() { use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; @@ -2047,12 +2044,8 @@ mod tests { .await .expect("polled DML execution must succeed"); - // Assert at the transport boundary, before Statement::execute can - // derive the same value from its public ResultStream fallback. - assert_eq!(result.status.num_modified_rows, Some(9)); + assert_eq!(result.status.num_modified_rows, None); - // Enrichment uses an independent throwaway reader. The reader handed - // to the caller must still contain the DML summary row. let mut stream = ResultStream::from_reader(result.reader) .await .expect("result reader must initialise"); @@ -2802,7 +2795,7 @@ mod tests { .await .expect("execute must succeed"); transport - .get_statement_status("statement-1", SessionAttribution::Current) + .get_statement_status("statement-1", SessionAttribution::Current, false) .await .expect("owned status must succeed"); transport @@ -2933,8 +2926,8 @@ mod tests { } #[tokio::test] - async fn attached_dml_reads_use_standard_urls_without_advancing_session_version() { - use wiremock::matchers::{method, path, query_param}; + async fn attached_status_preserves_wire_count_without_advancing_session_version() { + use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; let server = MockServer::start().await; @@ -2954,44 +2947,21 @@ mod tests { let mut response: serde_json::Value = serde_json::from_str(&succeeded_inline_dml_body("attached", 9)).unwrap(); - let mut chunk = response["result"].clone(); - chunk["chunk_index"] = json!(1); - let schema = Schema::new(vec![Field::new( - "num_affected_rows", - DataType::Int64, - false, - )]); - let mut empty_ipc = Vec::new(); - StreamWriter::try_new(&mut empty_ipc, &schema) - .unwrap() - .finish() - .unwrap(); response["status"]["session_version"] = json!({ "version_id": 11 }); - response["manifest"]["total_chunk_count"] = json!(2); - response["result"]["attachment"] = json!(STANDARD.encode(&empty_ipc)); - response["result"]["row_count"] = json!(0); - response["result"]["next_chunk_index"] = json!(1); + response["status"]["num_modified_rows"] = json!(9); Mock::given(method("GET")) .and(path("/api/2.0/sql/statements/attached")) .respond_with(ResponseTemplate::new(200).set_body_json(response)) .expect(1) .mount(&server) .await; - Mock::given(method("GET")) - .and(path("/api/2.0/sql/statements/attached/result/chunks/1")) - .and(query_param("row_offset", "0")) - .respond_with(ResponseTemplate::new(200).set_body_json(chunk)) - .expect(1) - .mount(&server) - .await; - let transport = create_ready_test_client_against(&server.uri(), TransportConfig::default()); transport .create_session(None, None, HashMap::new()) .await .expect("session creation must succeed"); let status = transport - .get_statement_status("attached", SessionAttribution::Detached) + .get_statement_status("attached", SessionAttribution::Detached, false) .await .expect("attached status must succeed"); @@ -3090,7 +3060,7 @@ mod tests { .await .expect("FAST execution must send the initial session version"); transport - .get_statement_status("statement-1", SessionAttribution::Current) + .get_statement_status("statement-1", SessionAttribution::Current, false) .await .expect("session-owned polling must observe the terminal version"); assert_eq!( @@ -3186,7 +3156,7 @@ mod tests { transport.observe_session_version(Some(SessionVersion { version_id: 7 })); transport - .get_statement_status("owned", SessionAttribution::Current) + .get_statement_status("owned", SessionAttribution::Current, false) .await .expect("session-owned polling must succeed"); assert_eq!( @@ -3195,7 +3165,7 @@ mod tests { ); transport - .statement_status("detached", SessionAttribution::Detached) + .statement_status("detached", SessionAttribution::Detached, false) .await .expect("detached polling must succeed"); assert_eq!( diff --git a/src/client/transport.rs b/src/client/transport.rs index 8f58cfe7..7d01f4a1 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -24,7 +24,7 @@ //! enum, which the kernel resolves to a concrete `Transport` impl //! internally. -use crate::kernel_error::Result; +use crate::kernel_error::{Error, Result}; use crate::reader::ResultReader; use crate::telemetry::ExecutionResultFormat; use crate::types::cloudfetch::CloudFetchLink; @@ -145,6 +145,15 @@ pub(crate) struct ExecuteResult { pub status: StatementStatus, } +pub(crate) enum FetchResultOutcome { + Ready(ExecuteResult), + NotReady, + TerminalError { + error: Error, + status: StatementStatus, + }, +} + impl std::fmt::Debug for ExecuteResult { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ExecuteResult") @@ -356,15 +365,8 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { /// Refresh status for an already-submitted statement and, if /// terminal-and-succeeded, materialise the reader. /// - /// Returns: - /// - `Ok(Some(ExecuteResult))` when the server reports - /// `Succeeded` (or `Closed` with inline data, which the SEA - /// server emits for one-batch results). - /// - `Ok(None)` when the server reports `Pending` / `Running` — - /// the caller should `status()` again later. - /// - `Err(...)` on `Failed` / `Cancelled` / true `Closed`-without-data - /// with the same structured error - /// `Transport::execute_statement`'s polling path produces. + /// Errors after a terminal wire response retain its status so the owning + /// handle can cache the terminal observation before returning the error. /// /// Used by `ExecutedAsyncStatement::fetch_result` and inside the /// `await_result` poll loop. @@ -372,7 +374,8 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { &self, statement_id: &str, session_attribution: SessionAttribution, - ) -> Result>; + infer_num_modified_rows: bool, + ) -> Result; /// One-shot status check for an in-flight statement. Returns the /// full `ExecuteResponse` (status + manifest + initial result, if @@ -382,6 +385,7 @@ pub(crate) trait Transport: Send + Sync + std::fmt::Debug { &self, statement_id: &str, session_attribution: SessionAttribution, + infer_num_modified_rows: bool, ) -> Result; // --- Result Fetching (CloudFetch) --- diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index c0fcf8ac..2811d822 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -1201,7 +1201,8 @@ mod tests { &self, _statement_id: &str, _session_attribution: crate::client::SessionAttribution, - ) -> Result> { + _infer_num_modified_rows: bool, + ) -> Result { unimplemented!("fetch_completed_result not used by the link-fetcher mock") } @@ -1209,6 +1210,7 @@ mod tests { &self, _statement_id: &str, _session_attribution: crate::client::SessionAttribution, + _infer_num_modified_rows: bool, ) -> Result { unimplemented!("statement_status not used by the link-fetcher mock") } diff --git a/src/reader/mod.rs b/src/reader/mod.rs index c9532fbf..f593c23c 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -1974,13 +1974,15 @@ mod tests { &self, _: &str, _: crate::client::SessionAttribution, - ) -> Result> { + _: bool, + ) -> Result { unreachable!() } async fn statement_status( &self, _: &str, _: crate::client::SessionAttribution, + _: bool, ) -> Result { unreachable!() } diff --git a/src/session.rs b/src/session.rs index 1a64a209..99938e10 100644 --- a/src/session.rs +++ b/src/session.rs @@ -713,6 +713,13 @@ impl Session { /// what lets `get_query_state` re-attach on every poll without the /// poll loop closing the statement it's watching.) /// + /// Attached handles do not have the submitted SQL needed to distinguish a + /// DML count result from a query using the same column names. Their + /// [`ExecutedAsyncStatement::num_modified_rows`] value therefore reflects + /// only a count supplied in status metadata and otherwise remains `None`, + /// including after result fetching. Retain the handle returned by + /// [`Statement::submit`] when inferred DML counts are required. + /// /// [`status`]: ExecutedAsyncStatement::status /// [`close`]: ExecutedAsyncStatement::close /// [`cancel`]: ExecutedAsyncStatement::cancel @@ -734,7 +741,7 @@ impl Session { let response = self .inner .transport() - .statement_status(&statement_id, SessionAttribution::Detached) + .statement_status(&statement_id, SessionAttribution::Detached, false) .await .map_err(|e| e.with_query_id(&statement_id))?; // NON-OWNING read-only adopt: `new_attached` gives the handle diff --git a/src/statement/dml_count.rs b/src/statement/dml_count.rs index acfedd17..3c44501d 100644 --- a/src/statement/dml_count.rs +++ b/src/statement/dml_count.rs @@ -26,6 +26,8 @@ //! | UPDATE | `num_affected_rows` | //! | DELETE | `num_affected_rows` | //! | MERGE | `num_affected_rows`, `num_updated_rows`, `num_deleted_rows`, `num_inserted_rows` | +//! | COPY INTO | `num_affected_rows`, `num_inserted_rows`, `num_skipped_corrupt_files` | +//! | CTAS, RTAS | `num_affected_rows`, `num_inserted_rows` | //! //! `num_affected_rows` is the total, matching Thrift's `numModifiedRows`. //! Reading it here lets the kernel's `num_modified_rows()` accessor reach @@ -43,22 +45,418 @@ use arrow_array::Array; use arrow_schema::DataType; /// The exact set of column names a SEA DML count result is built from. -const DML_COUNT_COLUMNS: [&str; 4] = [ +const DML_COUNT_COLUMNS: [&str; 5] = [ "num_affected_rows", "num_inserted_rows", "num_updated_rows", "num_deleted_rows", + "num_skipped_corrupt_files", ]; /// The total-affected column whose value maps to `num_modified_rows`. const AFFECTED_ROWS_COLUMN: &str = "num_affected_rows"; +/// SEA result aliases are ambiguous, so row-count extraction also requires a +/// statement form that can modify rows. +pub(crate) fn sql_may_modify_rows(sql: &str) -> bool { + let mut cursor = SqlCursor::new(sql); + let Some(first) = cursor.next_keyword() else { + return false; + }; + if first.eq_ignore_ascii_case("WITH") { + if cursor.skip_ctes().is_none() { + return false; + } + let Some(outer) = cursor.next_keyword() else { + return false; + }; + return cursor.statement_may_modify_rows(outer); + } + cursor.statement_may_modify_rows(first) +} + +fn is_dml_keyword(keyword: &str) -> bool { + ["INSERT", "UPDATE", "DELETE", "MERGE"] + .iter() + .any(|candidate| keyword.eq_ignore_ascii_case(candidate)) +} + +struct SqlCursor<'a> { + sql: &'a str, + index: usize, +} + +fn is_identifier_char(character: char) -> bool { + character == '_' || character.is_alphabetic() || character.is_ascii_digit() +} + +impl<'a> SqlCursor<'a> { + fn new(sql: &'a str) -> Self { + Self { sql, index: 0 } + } + + fn current_char(&self) -> Option { + self.sql[self.index..].chars().next() + } + + fn advance_char(&mut self) { + if let Some(character) = self.current_char() { + self.index += character.len_utf8(); + } + } + + fn is_raw_string(&self) -> bool { + let mut preceding = self.sql[..self.index].chars().rev(); + if !preceding.next().is_some_and(|c| matches!(c, 'R' | 'r')) { + return false; + } + !preceding.next().is_some_and(is_identifier_char) + } + + fn skip_quoted(&mut self, quote: char, backslash_escaped: bool, doubled_quote: bool) { + self.index += 1; + while let Some(character) = self.current_char() { + if backslash_escaped && character == '\\' { + self.advance_char(); + self.advance_char(); + } else if character == quote { + self.advance_char(); + if doubled_quote && self.current_char() == Some(quote) { + self.advance_char(); + } else { + break; + } + } else { + self.advance_char(); + } + } + } + + fn skip_string(&mut self, quote: char) { + let raw = self.is_raw_string(); + self.skip_quoted(quote, !raw, !raw); + } + + fn skip_line_comment(&mut self) { + self.index += 2; + while self.index < self.sql.len() { + if self.sql.as_bytes()[self.index..].starts_with(b"\\\n") { + self.index += 2; + } else if matches!(self.current_char(), Some('\n' | '\r')) { + let has_carriage_return = self.current_char() == Some('\r'); + self.advance_char(); + if has_carriage_return && self.current_char() == Some('\n') { + self.advance_char(); + } + break; + } else { + self.advance_char(); + } + } + } + + fn skip_block_comment(&mut self) { + let bytes = self.sql.as_bytes(); + self.index += 2; + let mut comment_depth = 1usize; + while self.index < bytes.len() && comment_depth > 0 { + if bytes[self.index..].starts_with(b"/*") { + comment_depth += 1; + self.index += 2; + } else if bytes[self.index..].starts_with(b"*/") { + comment_depth -= 1; + self.index += 2; + } else { + self.advance_char(); + } + } + } + + fn skip_trivia(&mut self) { + while self.index < self.sql.len() { + if self.sql.as_bytes()[self.index..].starts_with(b"--") { + self.skip_line_comment(); + continue; + } + if self.sql.as_bytes()[self.index..].starts_with(b"/*") { + self.skip_block_comment(); + continue; + } + if self.current_char().is_some_and(char::is_whitespace) { + self.advance_char(); + continue; + } + break; + } + } + + fn next_keyword(&mut self) -> Option<&'a str> { + self.skip_trivia(); + let start = self.index; + if !self.current_char().is_some_and(is_identifier_char) { + return None; + } + self.advance_char(); + while self.current_char().is_some_and(is_identifier_char) { + self.advance_char(); + } + Some(&self.sql[start..self.index]) + } + + fn next_top_level_keyword(&mut self) -> Option<&'a str> { + loop { + self.skip_trivia(); + match self.current_char()? { + quote @ ('\'' | '"') => self.skip_string(quote), + '`' => self.skip_quoted('`', false, true), + '(' => self.skip_parenthesized()?, + character if is_identifier_char(character) => return self.next_keyword(), + _ => self.advance_char(), + } + } + } + + fn statement_may_modify_rows(&mut self, keyword: &str) -> bool { + if is_dml_keyword(keyword) { + return true; + } + if keyword.eq_ignore_ascii_case("FROM") { + return self.has_multi_insert_body(); + } + if keyword.eq_ignore_ascii_case("COPY") { + return self.consume_keyword("INTO"); + } + if keyword.eq_ignore_ascii_case("CREATE") { + return self.is_create_table_as_select(); + } + if keyword.eq_ignore_ascii_case("REPLACE") { + return self.consume_keyword("TABLE") && self.has_as_query(); + } + if keyword.eq_ignore_ascii_case("EXECUTE") && self.consume_keyword("IMMEDIATE") { + return self.take_string_literal().is_some_and(sql_may_modify_rows); + } + false + } + + fn is_create_table_as_select(&mut self) -> bool { + if self.consume_keyword("OR") && !self.consume_keyword("REPLACE") { + return false; + } + if !self.consume_keyword("TEMP") { + self.consume_keyword("TEMPORARY"); + } + self.consume_keyword("TABLE") && self.has_as_query() + } + + fn has_as_query(&mut self) -> bool { + while let Some(keyword) = self.next_top_level_keyword() { + if keyword.eq_ignore_ascii_case("AS") { + self.skip_trivia(); + while self.current_char() == Some('(') { + self.advance_char(); + self.skip_trivia(); + } + if self.next_keyword().is_some_and(|query| { + ["SELECT", "TABLE", "VALUES", "WITH", "FROM"] + .iter() + .any(|candidate| query.eq_ignore_ascii_case(candidate)) + }) { + return true; + } + } + } + false + } + + fn take_string_literal(&mut self) -> Option<&'a str> { + self.skip_trivia(); + if self.current_char().is_some_and(|c| matches!(c, 'R' | 'r')) { + let prefix = self.index; + self.advance_char(); + if !matches!(self.current_char(), Some('\'' | '"')) { + self.index = prefix; + return None; + } + } + let quote = self.current_char()?; + if !matches!(quote, '\'' | '"') { + return None; + } + let raw = self.is_raw_string(); + self.advance_char(); + let start = self.index; + while let Some(character) = self.current_char() { + if !raw && character == '\\' { + self.advance_char(); + self.advance_char(); + } else if character == quote { + let end = self.index; + self.advance_char(); + if !raw && self.current_char() == Some(quote) { + self.advance_char(); + } else { + return Some(&self.sql[start..end]); + } + } else { + self.advance_char(); + } + } + None + } + + fn has_multi_insert_body(&mut self) -> bool { + while let Some(keyword) = self.next_top_level_keyword() { + if keyword.eq_ignore_ascii_case("SELECT") { + return false; + } + if keyword.eq_ignore_ascii_case("INSERT") { + if self.consume_keyword("WITH") + && (!self.consume_keyword("SCHEMA") || !self.consume_keyword("EVOLUTION")) + { + continue; + } + if self.consume_keyword("OVERWRITE") { + return true; + } + self.consume_keyword("ONCE"); + if self.consume_keyword("INTO") { + self.consume_keyword("ONCE"); + return true; + } + } + } + false + } + + fn consume_keyword(&mut self, expected: &str) -> bool { + let start = self.index; + let matched = self + .next_keyword() + .is_some_and(|keyword| keyword.eq_ignore_ascii_case(expected)); + if !matched { + self.index = start; + } + matched + } + + fn skip_identifier(&mut self) -> Option<()> { + self.skip_trivia(); + match self.current_char()? { + quote @ ('"' | '`') => { + self.skip_quoted(quote, quote == '"', true); + Some(()) + } + character if is_identifier_char(character) => { + self.next_keyword()?; + Some(()) + } + _ => None, + } + } + + fn skip_parenthesized(&mut self) -> Option<()> { + self.skip_trivia(); + if self.current_char() != Some('(') { + return None; + } + self.advance_char(); + let mut depth = 1usize; + while self.index < self.sql.len() { + if self.sql.as_bytes()[self.index..].starts_with(b"--") { + self.skip_line_comment(); + } else if self.sql.as_bytes()[self.index..].starts_with(b"/*") { + self.skip_block_comment(); + } else { + match self.current_char()? { + quote @ ('\'' | '"') => self.skip_string(quote), + '`' => self.skip_quoted('`', false, true), + '(' => { + depth += 1; + self.advance_char(); + } + ')' => { + depth -= 1; + self.advance_char(); + if depth == 0 { + return Some(()); + } + } + _ => self.advance_char(), + } + } + } + None + } + + fn skip_integer_value(&mut self) -> bool { + self.skip_trivia(); + if self.current_char() == Some('?') { + self.advance_char(); + return true; + } + if self.current_char() == Some(':') { + self.advance_char(); + return self.skip_identifier().is_some(); + } + let start = self.index; + while self.current_char().is_some_and(|c| c.is_ascii_digit()) { + self.advance_char(); + } + self.index > start + } + + fn skip_max_recursion_level(&mut self) -> Option { + if !self.consume_keyword("MAX") { + return Some(false); + } + if !self.consume_keyword("RECURSION") + || !self.consume_keyword("LEVEL") + || !self.skip_integer_value() + { + return None; + } + Some(true) + } + + fn skip_ctes(&mut self) -> Option<()> { + self.consume_keyword("RECURSIVE"); + loop { + self.skip_identifier()?; + self.skip_trivia(); + + if self.current_char() == Some('(') { + self.skip_parenthesized()?; + self.skip_trivia(); + let body_follows = if self.skip_max_recursion_level()? { + self.consume_keyword("AS"); + true + } else { + self.consume_keyword("AS") || self.current_char() == Some('(') + }; + if body_follows { + self.skip_parenthesized()?; + } + } else { + self.skip_max_recursion_level()?; + self.consume_keyword("AS"); + self.skip_parenthesized()?; + } + + self.skip_trivia(); + if self.current_char() != Some(',') { + return Some(()); + } + self.advance_char(); + } + } +} + /// Does this result `manifest` describe a DML row-count result? /// /// Same strict signature as [`read_dml_affected_rows`], but checked against /// the manifest's column metadata so a caller can decide whether the inline -/// result is worth decoding *before* building a reader — keeping SELECTs (real -/// columns) off the decode path entirely. +/// result is worth decoding *before* building a reader. The submitted SQL must +/// still be checked because a SELECT can use these exact aliases. pub(crate) fn manifest_is_dml_count(manifest: &ResultManifest) -> bool { let cols = &manifest.schema.columns; !cols.is_empty() @@ -71,13 +469,11 @@ pub(crate) fn manifest_is_dml_count(manifest: &ResultManifest) -> bool { /// If `stream`'s result set is a DML row-count result, return its /// `num_affected_rows` value; otherwise `None`. /// -/// Detection is deliberately strict — **every** column must be one of the -/// known `num_*_rows` counters and `num_affected_rows` must be present — -/// so a `SELECT 1 AS num_affected_rows` (a real query that merely aliases -/// a column to that name) is not mistaken for a DML result. Thrift never -/// faces this ambiguity because it reads the count from operation -/// metadata rather than the result columns; the strict signature keeps us -/// as close as the SEA wire shape allows. +/// Detection is deliberately strict: **every** column must be one of the known +/// `num_*_rows` counters and `num_affected_rows` must be present. This shape is +/// still ambiguous with a SELECT that uses the same aliases, so callers must +/// also gate extraction on the submitted SQL. Thrift does not face this +/// ambiguity because its count comes from operation metadata. /// /// Non-consuming: peeks the first batch and buffers it, so the caller's /// subsequent fetch still sees the row. @@ -129,6 +525,73 @@ mod tests { use arrow_schema::{Field, Schema}; use std::sync::Arc; + #[test] + fn classifies_statements_that_may_modify_rows() { + for sql in [ + "INSERT INTO t VALUES (1)", + "-- comment\nUPDATE t SET value = 1", + "/* outer /* nested */ comment */ DELETE FROM t", + "merge into t using s on t.id = s.id when matched then delete", + "WITH source AS (SELECT 1) INSERT INTO t SELECT * FROM source", + "WITH source (SELECT 1) INSERT INTO t SELECT * FROM source", + "WITH source(id) (SELECT 1) INSERT INTO t SELECT * FROM source", + "WITH source MAX RECURSION LEVEL 10 AS (SELECT 1) UPDATE t SET value = 1", + "WITH source(id) MAX RECURSION LEVEL :limit (SELECT 1) DELETE FROM t", + "WITH source MAX RECURSION LEVEL ? AS (SELECT 1) MERGE INTO t USING source ON false WHEN NOT MATCHED THEN INSERT *", + "WITH source AS (SELECT ') UPDATE t' AS value) UPDATE t SET value = 1", + "WITH source AS (SELECT R'\\' AS value) UPDATE t SET value = 1", + "WITH `source)`(`id)`) AS (SELECT 1) DELETE FROM t", + "WITH café AS (SELECT 1) UPDATE t SET value = 1", + "WITH `source\\` AS (SELECT 1) DELETE FROM t", + "WITH table AS (SELECT 1) UPDATE t SET value = 1", + "FROM source INSERT INTO target SELECT * FROM source", + "WITH source AS (SELECT 1) FROM source INSERT INTO target SELECT * FROM source", + "FROM source INSERT WITH SCHEMA EVOLUTION OVERWRITE target SELECT * FROM source", + "FROM source INSERT ONCE INTO ONCE target SELECT * FROM source", + "FROM insert INSERT INTO target SELECT * FROM insert", + "FROM source AS insert INSERT INTO target SELECT * FROM source", + "COPY INTO target FROM '/Volumes/catalog/schema/volume'", + "CREATE TABLE target USING DELTA AS SELECT 1", + "CREATE TABLE target STORED AS PARQUET AS SELECT 1", + "CREATE TABLE target AS (SELECT 1)", + "CREATE OR REPLACE TABLE target AS SELECT 1", + "CREATE TEMPORARY TABLE target AS VALUES (1)", + "REPLACE TABLE target AS WITH source AS (SELECT 1) SELECT * FROM source", + "REPLACE TABLE target AS (SELECT 1)", + "EXECUTE IMMEDIATE 'INSERT INTO target VALUES (1)'", + "EXECUTE IMMEDIATE R'UPDATE target SET value = 1'", + ] { + assert!(sql_may_modify_rows(sql), "expected modifying SQL: {sql}"); + } + } + + #[test] + fn rejects_queries_and_dml_words_inside_ctes() { + for sql in [ + "SELECT 7 AS num_affected_rows", + "WITH source AS (SELECT 'INSERT INTO t' AS value) SELECT * FROM source", + "WITH source AS (SELECT 1 -- \\\n) UPDATE t\n) SELECT * FROM source", + "WITH update AS (SELECT 7 AS num_affected_rows) SELECT * FROM update", + "WITH source AS (SELECT 1) VALUES (2)", + "WITH source AS (SELECT 1) TABLE source", + "WITH source AS (SELECT 1) (SELECT * FROM source)", + "FROM source SELECT 'INSERT INTO target'", + "FROM insert SELECT *", + "WITH source AS (SELECT 1) FROM source SELECT *", + "EXPLAIN UPDATE t SET value = 1", + "CREATE TABLE t (value BIGINT)", + "CREATE VIEW v AS SELECT 1", + "EXECUTE IMMEDIATE 'SELECT 7 AS num_affected_rows'", + "EXECUTE IMMEDIATE sql_variable", + "WITH source AS (SELECT 1", + ] { + assert!( + !sql_may_modify_rows(sql), + "expected non-modifying SQL: {sql}" + ); + } + } + /// Build a single-batch `ResultStream` from `(name, Int64 values)` columns. async fn count_stream(cols: &[(&str, &[i64])]) -> ResultStream { let fields: Vec = cols @@ -183,6 +646,27 @@ mod tests { assert_eq!(read_dml_affected_rows(&mut s).await.unwrap(), Some(3)); } + #[tokio::test] + async fn copy_into_shape_returns_affected_rows() { + let manifest: ResultManifest = serde_json::from_str( + r#"{"format":"ARROW_STREAM","schema":{"column_count":3,"columns":[ + {"name":"num_affected_rows","type_name":"LONG","type_text":"BIGINT","position":0}, + {"name":"num_inserted_rows","type_name":"LONG","type_text":"BIGINT","position":1}, + {"name":"num_skipped_corrupt_files","type_name":"INT","type_text":"INT","position":2}]}, + "total_row_count":1}"#, + ) + .unwrap(); + assert!(manifest_is_dml_count(&manifest)); + + let mut stream = count_stream(&[ + ("num_affected_rows", &[2]), + ("num_inserted_rows", &[2]), + ("num_skipped_corrupt_files", &[0]), + ]) + .await; + assert_eq!(read_dml_affected_rows(&mut stream).await.unwrap(), Some(2)); + } + #[tokio::test] async fn update_delete_shape_returns_affected_rows() { let mut s = count_stream(&[("num_affected_rows", &[2])]).await; diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 59b8379e..73f74262 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -44,7 +44,7 @@ //! class) can route through whichever handle their language idiom //! prefers; field availability is identical. -use crate::client::{ExecuteResponse, ExecutionTimeout, SessionAttribution}; +use crate::client::{ExecuteResponse, ExecutionTimeout, FetchResultOutcome, SessionAttribution}; use crate::kernel_error::{Error, Result}; use crate::klog::warn; use crate::result_stream::ResultStream; @@ -201,6 +201,7 @@ pub struct ExecutedAsyncStatement { /// server-side cancel. (`Drop` / `close()` are already inert on /// attached handles via `closed=true`.) owning: bool, + infer_num_modified_rows: bool, session_attribution: SessionAttribution, /// Last SEA `StatementStatus` observed by this handle (initial /// `submit_statement` response or any subsequent `status()` / @@ -273,6 +274,20 @@ fn deadline_policy(timeout: ExecutionTimeout) -> (Option, bo } } +pub(crate) struct AsyncExecutionOptions { + timeout: ExecutionTimeout, + infer_num_modified_rows: bool, +} + +impl AsyncExecutionOptions { + pub(crate) fn new(timeout: ExecutionTimeout, infer_num_modified_rows: bool) -> Self { + Self { + timeout, + infer_num_modified_rows, + } + } +} + impl ExecutedAsyncStatement { /// Produce the stable client query-timeout error and schedule bounded, /// best-effort server cleanup when a deadline retained across @@ -317,8 +332,12 @@ impl ExecutedAsyncStatement { closed: Arc, initial_status: crate::types::sea::StatementStatus, statement_telemetry: StatementTelemetry, - timeout: ExecutionTimeout, + options: AsyncExecutionOptions, ) -> Self { + let AsyncExecutionOptions { + timeout, + infer_num_modified_rows, + } = options; let (client_deadline, poll_timeout_disabled) = deadline_policy(timeout); let initial_terminal = initial_status.state.is_terminal(); Self { @@ -329,6 +348,7 @@ impl ExecutedAsyncStatement { owner_released: Arc::new(AtomicBool::new(false)), // The submitting handle owns the statement lifecycle. owning: true, + infer_num_modified_rows, session_attribution: SessionAttribution::Current, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), statement_telemetry, @@ -369,6 +389,7 @@ impl ExecutedAsyncStatement { Arc::new(AtomicBool::new(false)), SessionAttribution::Detached, initial_status, + false, ) } @@ -379,6 +400,7 @@ impl ExecutedAsyncStatement { owner_released: Arc, session_attribution: SessionAttribution, initial_status: crate::types::sea::StatementStatus, + infer_num_modified_rows: bool, ) -> Self { let initial_terminal = initial_status.state.is_terminal(); Self { @@ -388,6 +410,7 @@ impl ExecutedAsyncStatement { closed: Arc::new(AtomicBool::new(true)), owner_released, owning: false, + infer_num_modified_rows, session_attribution, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), statement_telemetry: StatementTelemetry::noop(), @@ -416,6 +439,7 @@ impl ExecutedAsyncStatement { Arc::clone(&self.owner_released), self.session_attribution, status, + self.infer_num_modified_rows, ), }) } @@ -504,15 +528,11 @@ impl ExecutedAsyncStatement { .and_then(|s| s.error_details_json.clone()) } - /// Internal helper — overwrite the cached `StatementStatus` with - /// a fresh poll's response. Called by `status()` / - /// `await_result()` after every successful - /// `statement_status` RPC. Lock poisoning is intentionally - /// swallowed: a poisoned lock here would only happen if a panic - /// landed mid-write, and the recovery path is to keep the prior - /// status visible (worse: a fresh poll's status lost; better: - /// the handle's accessor surface keeps working). + /// A poisoned cache retains its last visible status so accessors remain usable. fn record_latest_status(&self, fresh: crate::types::sea::StatementStatus) { + if fresh.state.is_terminal() { + self.terminal_observed.store(true, Ordering::Release); + } if let Ok(mut guard) = self.latest_status.lock() { *guard = fresh; } @@ -574,10 +594,11 @@ impl ExecutedAsyncStatement { return Err(self.expire_client_query_timeout()); } let status_started = std::time::Instant::now(); - let poll = self - .session - .transport() - .statement_status(&self.statement_id, self.session_attribution); + let poll = self.session.transport().statement_status( + &self.statement_id, + self.session_attribution, + self.infer_num_modified_rows, + ); let response = match self.client_deadline { Some(deadline) if enforce_deadline => { let poll_deadline = deadline @@ -602,12 +623,6 @@ impl ExecutedAsyncStatement { // reflect what THIS handle has observed (instead of the // stale initial-submit snapshot). self.record_latest_status(response.status.clone()); - // Latch the terminal observation so subsequent `status()` - // calls stop enforcing the client deadline against this - // already-finished statement. - if response.status.state.is_terminal() { - self.terminal_observed.store(true, Ordering::Release); - } let status = StatementStatus::from_sea_response(&response); if enforce_deadline && matches!(status, StatementStatus::Pending | StatementStatus::Running) @@ -709,10 +724,11 @@ impl ExecutedAsyncStatement { return Err(self.expire_client_query_timeout()); } let status_started = std::time::Instant::now(); - let poll = self - .session - .transport() - .statement_status(&self.statement_id, self.session_attribution); + let poll = self.session.transport().statement_status( + &self.statement_id, + self.session_attribution, + self.infer_num_modified_rows, + ); let response = match self.client_deadline { Some(deadline) if enforce_deadline => { let poll_deadline = deadline @@ -744,12 +760,6 @@ impl ExecutedAsyncStatement { // accessors reflect THIS poll's observation — not the // initial-submit snapshot that's now stale by minutes. self.record_latest_status(response.status.clone()); - // Latch the terminal observation so a later `status()` - // call stops enforcing the client deadline against this - // already-finished statement. - if response.status.state.is_terminal() { - self.terminal_observed.store(true, Ordering::Release); - } match StatementStatus::from_sea_response(&response) { StatementStatus::Succeeded | StatementStatus::Closed => { if let Some(g) = cancel_guard.take() { @@ -842,15 +852,20 @@ impl ExecutedAsyncStatement { let result = self .session .transport() - .fetch_completed_result(&self.statement_id, self.session_attribution) + .fetch_completed_result( + &self.statement_id, + self.session_attribution, + self.infer_num_modified_rows, + ) .await?; self.check_read_validity()?; match result { - Some(result) => { + FetchResultOutcome::Ready(result) => { self.statement_telemetry.on_result_metadata( result.telemetry_result_format, result.telemetry_is_compressed, ); + self.record_latest_status(result.status.clone()); // If the server already auto-closed the statement // (`state == Closed`), pre-set the shared `closed` flag so // this handle's `close()` / `Drop` — and `invalidate_prior` @@ -870,7 +885,7 @@ impl ExecutedAsyncStatement { // DML the count rides in the result set. Derive it once // (non-consuming) and record it onto the latest status so // `num_modified_rows()` matches the sync path / Thrift. - if self.num_modified_rows().is_none() { + if self.infer_num_modified_rows && self.num_modified_rows().is_none() { if let Some(n) = crate::statement::dml_count::read_dml_affected_rows(&mut stream).await? { @@ -884,7 +899,7 @@ impl ExecutedAsyncStatement { .store(true, Ordering::Release); Ok(stream) } - None => { + FetchResultOutcome::NotReady => { // Re-read the status so the error message names the // observed state (Pending vs Running). Best-effort — // if the status call itself fails, fall back to the @@ -892,7 +907,7 @@ impl ExecutedAsyncStatement { let observed = match self .session .transport() - .statement_status(&self.statement_id, self.session_attribution) + .statement_status(&self.statement_id, self.session_attribution, false) .await { Ok(r) => match r.status.state { @@ -910,6 +925,10 @@ impl ExecutedAsyncStatement { self.statement_id, observed ))) } + FetchResultOutcome::TerminalError { error, status } => { + self.record_latest_status(status); + Err(error) + } } } } diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 5925fed9..b1ee521d 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -60,7 +60,7 @@ use crate::klog::{debug, warn}; use crate::result_stream::ResultStream; use crate::session::SessionInner; use crate::statement::executed::ExecutedStatement; -use crate::statement::executed_async::ExecutedAsyncStatement; +use crate::statement::executed_async::{AsyncExecutionOptions, ExecutedAsyncStatement}; use crate::statement::params::{named_typed_value_to_sea_parameter, typed_value_to_sea_parameter}; use crate::statement::spec::{deserialize_query_tags, ResultFormat, StatementSpec}; use crate::statement::validity::ValidityFlag; @@ -352,6 +352,7 @@ impl Statement { let result = async { self.invalidate_prior().await; let (sql, mut exec_params) = self.prepare_for_dispatch(None)?; + let infer_num_modified_rows = crate::statement::dml_count::sql_may_modify_rows(&sql); let cancel_state = MidExecuteCancelState::new( Arc::clone(&self.session), @@ -417,7 +418,7 @@ impl Statement { // result (non-consuming — the count row still reaches the // caller's fetch) so `num_modified_rows()` matches Thrift. let mut status = result.status; - if status.num_modified_rows.is_none() { + if infer_num_modified_rows && status.num_modified_rows.is_none() { status.num_modified_rows = crate::statement::dml_count::read_dml_affected_rows(&mut result_stream).await?; } @@ -479,6 +480,7 @@ impl Statement { let result = async { self.invalidate_prior().await; let (sql, exec_params) = self.prepare_for_dispatch(Some("0s"))?; + let infer_num_modified_rows = crate::statement::dml_count::sql_may_modify_rows(&sql); let cancel_state = MidExecuteCancelState::new( Arc::clone(&self.session), @@ -548,7 +550,7 @@ impl Statement { // the first poll. response.status, telemetry_for_body, - timeout, + AsyncExecutionOptions::new(timeout, infer_num_modified_rows), )) } .instrument(span) @@ -603,6 +605,7 @@ impl Statement { // alive) is what makes the Completed arm's `close()` a no-op and lets // fire-and-forget DDL commit. let (sql, mut exec_params) = self.prepare_for_dispatch(None)?; + let infer_num_modified_rows = crate::statement::dml_count::sql_may_modify_rows(&sql); let cancel_state = MidExecuteCancelState::new( Arc::clone(&self.session), @@ -674,7 +677,10 @@ impl Statement { closed, resp.status, telemetry_for_body, - ExecutionTimeout::Default, + AsyncExecutionOptions::new( + ExecutionTimeout::Default, + infer_num_modified_rows, + ), ))) } } diff --git a/tests/v0_async_execute_wiremock.rs b/tests/v0_async_execute_wiremock.rs index 18d53cbd..ec282d53 100644 --- a/tests/v0_async_execute_wiremock.rs +++ b/tests/v0_async_execute_wiremock.rs @@ -1279,6 +1279,161 @@ async fn async_status_call_refreshes_cached_status() { async_exec.close().await.expect("close"); } +#[tokio::test] +async fn async_fetch_result_caches_wire_modified_row_count() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + mount_submit(&server, pending_body("stmt-fetch-wire-count")).await; + let batch = int64_batch("value", vec![1]); + mount_status_sequence( + &server, + "stmt-fetch-wire-count", + vec![succeeded_inline_body_with_status( + "stmt-fetch-wire-count", + &batch, + Some(17), + None, + None, + None, + )], + ) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1"); + let async_exec = stmt + .submit_with_timeout(std::time::Duration::from_millis(100)) + .await + .expect("submit"); + assert_eq!(async_exec.num_modified_rows(), None); + + let mut stream = async_exec.fetch_result().await.expect("fetch result"); + assert_eq!(drain(&mut stream).await.len(), 1); + assert_eq!(async_exec.num_modified_rows(), Some(17)); + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + let status = async_exec.status().await.unwrap(); + assert!(matches!(status, StatementStatus::Succeeded), "{status:?}"); + async_exec.close().await.expect("close"); +} + +#[tokio::test] +async fn async_fetch_result_caches_failed_terminal_status() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + mount_submit(&server, pending_body("stmt-fetch-failed")).await; + mount_status_sequence( + &server, + "stmt-fetch-failed", + vec![failed_body("stmt-fetch-failed", "table not found", "42P01")], + ) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT * FROM missing_table"); + let async_exec = stmt + .submit_with_timeout(std::time::Duration::from_millis(100)) + .await + .expect("submit"); + + let error = match async_exec.fetch_result().await { + Ok(_) => panic!("fetch_result on FAILED should error"), + Err(error) => error, + }; + assert_eq!(error.code, ErrorCode::SqlError); + + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + let status = async_exec.status().await.expect("status"); + assert!(matches!(status, StatementStatus::Failed(_)), "{status:?}"); + async_exec.close().await.expect("close"); +} + +#[tokio::test] +async fn async_fetch_result_caches_terminal_status_when_reader_factory_rejects_response() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + mount_submit(&server, pending_body("stmt-fetch-invalid-reader")).await; + let batch = int64_batch("value", vec![1]); + let mut response: serde_json::Value = + serde_json::from_str(&succeeded_inline_body("stmt-fetch-invalid-reader", &batch)).unwrap(); + response["manifest"]["total_chunk_count"] = json!(2); + mount_status_sequence( + &server, + "stmt-fetch-invalid-reader", + vec![response.to_string()], + ) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1"); + let async_exec = stmt + .submit_with_timeout(std::time::Duration::from_millis(100)) + .await + .expect("submit"); + + let error = match async_exec.fetch_result().await { + Ok(_) => panic!("reader factory must reject missing continuation metadata"), + Err(error) => error, + }; + assert_eq!(error.code, ErrorCode::DataLoss); + assert!(error.message.contains("missing per-chunk next_chunk_index")); + + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + let status = async_exec.status().await.expect("status"); + assert!(matches!(status, StatementStatus::Succeeded), "{status:?}"); + async_exec.close().await.expect("close"); +} + +#[tokio::test] +async fn async_select_alias_matching_dml_count_does_not_set_modified_rows() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + mount_submit(&server, pending_body("stmt-async-select-counter-alias")).await; + let batch = int64_batch("num_affected_rows", vec![7]); + mount_status_sequence( + &server, + "stmt-async-select-counter-alias", + vec![succeeded_inline_body( + "stmt-async-select-counter-alias", + &batch, + )], + ) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 7 AS num_affected_rows"); + let async_exec = stmt.submit().await.expect("submit"); + let mut stream = async_exec.await_result().await.expect("await result"); + + assert_eq!(async_exec.num_modified_rows(), None); + let batches = drain(&mut stream).await; + assert_eq!(batches.len(), 1); + assert_eq!( + batches[0] + .column(0) + .as_primitive::() + .value(0), + 7 + ); + + async_exec.close().await.expect("close"); +} + #[tokio::test] async fn async_await_result_failed_carries_extended_status_fields_onto_error() { // Pins the async polling path's terminal-error contract, @@ -1762,6 +1917,55 @@ async fn attach_seeds_status_and_reports_server_state() { assert!(matches!(status, StatementStatus::Running), "{status:?}"); } +#[tokio::test] +async fn attached_statement_only_uses_wire_modified_row_count() { + for (wire_count, expected) in [(None, None), (Some(11), Some(11))] { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + let batch = int64_batch("num_affected_rows", vec![7]); + Mock::given(method("GET")) + .and(path("/api/2.0/sql/statements/stmt-attached-alias")) + .respond_with(ResponseTemplate::new(200).set_body_string( + succeeded_inline_body_with_status( + "stmt-attached-alias", + &batch, + wire_count, + None, + None, + None, + ), + )) + .expect(2) + .mount(&server) + .await; + + let session = open_session(&server).await; + let attached = session + .attach_async_statement("stmt-attached-alias") + .await + .expect("attach"); + + assert_eq!(attached.num_modified_rows(), expected); + let mut stream = attached.fetch_result().await.expect("fetch result"); + let batches = drain(&mut stream).await; + assert_eq!(batches.len(), 1); + assert_eq!( + batches[0] + .column(0) + .as_primitive::() + .value(0), + 7 + ); + assert_eq!(attached.num_modified_rows(), expected); + + session.close().await.expect("session close"); + server.verify().await; + } +} + #[tokio::test] async fn attached_statement_inline_reads_use_standard_urls() { use wiremock::matchers::query_param; diff --git a/tests/v0_c_abi_canceller_wiremock.rs b/tests/v0_c_abi_canceller_wiremock.rs index 4d3df1ee..6541ca1b 100644 --- a/tests/v0_c_abi_canceller_wiremock.rs +++ b/tests/v0_c_abi_canceller_wiremock.rs @@ -66,12 +66,13 @@ use databricks_sql_kernel::c_abi::statement::{ kernel_executed_async_statement_num_modified_rows, kernel_executed_async_statement_query_id, kernel_executed_async_statement_status, kernel_executed_async_statement_t, kernel_executed_statement_close, kernel_executed_statement_get_result_stream, - 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_execute_with_timeout_ms, - kernel_statement_set_sql, kernel_statement_submit, kernel_statement_submit_with_timeout_ms, - kernel_statement_t, KernelStatementStatusKind, MAX_CLIENT_QUERY_TIMEOUT_MS, + kernel_executed_statement_num_modified_rows, 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_execute_with_timeout_ms, kernel_statement_set_sql, + kernel_statement_submit, kernel_statement_submit_with_timeout_ms, kernel_statement_t, + KernelStatementStatusKind, MAX_CLIENT_QUERY_TIMEOUT_MS, }; use databricks_sql_kernel::c_abi::KernelStatusCode; use serde_json::json; @@ -582,6 +583,64 @@ fn async_c_abi_num_modified_rows_after_materialise() { } } +#[test] +fn sync_c_abi_select_alias_is_not_a_modified_row_count() { + 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_dml_count_body("stmt-select-alias", 7)), + ) + .mount(&server) + .await; + server + }); + + unsafe { + let session = open_session_c_abi(&server.uri()); + let mut stmt = std::ptr::null_mut(); + assert_eq!( + kernel_session_new_statement(session, &mut stmt), + KernelStatusCode::Success + ); + let sql = CString::new("SELECT 7 AS num_affected_rows").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_eq!(kernel_executed_statement_num_modified_rows(exec), -1); + + let mut stream: *mut kernel_result_stream_t = std::ptr::null_mut(); + assert_eq!( + kernel_executed_statement_get_result_stream(exec, &mut stream), + KernelStatusCode::Success + ); + assert!(!stream.is_null()); + + assert_eq!( + kernel_result_stream_close(stream), + KernelStatusCode::Success + ); + 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); + } +} + /// `kernel_executed_async_statement_get_result_stream` before the statement /// reaches a terminal state must reject with `InvalidArgument` (v0 collapses /// InvalidState into that code) and write a null out-pointer. Also asserts the diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index e428abf3..66587d23 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -31,7 +31,7 @@ use arrow_ipc::writer::StreamWriter; use arrow_schema::{DataType, Field, Fields, Schema}; use base64::{engine::general_purpose::STANDARD, Engine}; use databricks_sql_kernel::{ - AuthConfig, ConnectionConfig, ErrorCode, ExecutedStatementHandle, + AuthConfig, ConnectionConfig, DirectStatement, ErrorCode, ExecutedStatementHandle, GeospatialResultRepresentation, HttpConfig, ResultBatch, ResultConfig, Session, TryNextBatch, TypedValue, MAX_CLIENT_QUERY_TIMEOUT, }; @@ -2157,6 +2157,78 @@ async fn executed_statement_status_fields_default_to_none() { exec.close().await.expect("close"); } +#[tokio::test] +async fn select_alias_matching_dml_count_does_not_set_modified_rows() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + let batch = int64_batch("num_affected_rows", vec![7]); + mount_execute( + &server, + succeeded_inline_body("stmt-select-counter-alias", &batch), + ) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 7 AS num_affected_rows"); + let mut exec = stmt.execute().await.expect("execute"); + + assert_eq!(exec.num_modified_rows(), None); + let batches = drain(exec.result_stream_mut()).await; + assert_eq!(batches.len(), 1); + assert_eq!( + batches[0] + .column(0) + .as_primitive::() + .value(0), + 7 + ); + + exec.close().await.expect("close"); +} + +#[tokio::test] +async fn execute_direct_running_select_only_uses_wire_modified_row_count() { + for (wire_count, expected) in [(None, None), (Some(11), Some(11))] { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + mount_close_any_statement(&server).await; + + mount_execute(&server, running_body("stmt-direct-select-alias")).await; + let batch = int64_batch("num_affected_rows", vec![7]); + mount_status( + &server, + "stmt-direct-select-alias", + succeeded_inline_body_with_status( + "stmt-direct-select-alias", + &batch, + wire_count, + None, + None, + None, + ), + ) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 7 AS num_affected_rows"); + let DirectStatement::Running(async_exec) = + stmt.execute_direct().await.expect("execute direct") + else { + panic!("running response must return an asynchronous handle"); + }; + + async_exec.status().await.expect("status"); + assert_eq!(async_exec.num_modified_rows(), expected); + async_exec.close().await.expect("close"); + } +} + #[tokio::test] async fn polling_path_carries_terminal_status_not_initial() { // Regression guard against the kernel surfacing the FIRST status