diff --git a/src/client/sea.rs b/src/client/sea.rs index 6c75c78e..92d5d4a2 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -446,6 +446,7 @@ impl SeaRestTransport { row_limit: params.row_limit, result_compression: Some("LZ4_FRAME".to_string()), parameters: params.parameters.clone(), + query_tags: params.query_tags.clone(), }; debug!("Executing statement at {}: {}", url, sql); diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index c6bac02f..a31ee9c9 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -62,9 +62,9 @@ use crate::session::SessionInner; use crate::statement::executed::ExecutedStatement; use crate::statement::executed_async::ExecutedAsyncStatement; use crate::statement::params::{named_typed_value_to_sea_parameter, typed_value_to_sea_parameter}; -use crate::statement::spec::{ResultFormat, StatementSpec}; +use crate::statement::spec::{deserialize_query_tags, ResultFormat, StatementSpec}; use crate::statement::validity::ValidityFlag; -use crate::types::sea::{ExecuteParams, StatementState}; +use crate::types::sea::{ExecuteParams, QueryTag, StatementState}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use tracing::Instrument; @@ -167,6 +167,15 @@ fn build_execute_params( .parameters .push(named_typed_value_to_sea_parameter(name.clone(), value)?); } + // Per-statement query tags: both `Statement::query_tags` and a raw + // `statement_conf["query_tags"]` land in the serialized conf string; + // the SEA wire wants the native `[{key, value}]` array, so convert here. + if let Some(serialized) = spec.statement_conf.get("query_tags") { + exec_params.query_tags = deserialize_query_tags(serialized) + .into_iter() + .map(|(key, value)| QueryTag { key, value }) + .collect(); + } Ok((sql, exec_params)) } @@ -816,6 +825,43 @@ mod tests { assert_eq!(params.row_limit, Some(100)); } + #[test] + fn build_execute_params_threads_query_tags_to_wire_array() { + // Per-statement query tags set via Statement::query_tags must reach + // ExecuteParams.query_tags as the native SEA {key, value} array (the + // SEA request has no conf overlay). Regression guard for the seam + // where statement_conf["query_tags"] is converted to the array. + use std::collections::HashMap; + let mut spec = StatementSpec::new(); + spec.sql("SELECT 1"); + let mut tags = HashMap::new(); + tags.insert("team".to_string(), Some("eng".to_string())); + tags.insert("prod".to_string(), None); + spec.query_tags(tags).unwrap(); + + let (_sql, params) = build_execute_params(&spec, None).unwrap(); + let got: std::collections::HashSet<(String, Option)> = params + .query_tags + .iter() + .map(|t| (t.key.clone(), t.value.clone())) + .collect(); + let expected: std::collections::HashSet<(String, Option)> = [ + ("team".to_string(), Some("eng".to_string())), + ("prod".to_string(), None), + ] + .into_iter() + .collect(); + assert_eq!(got, expected); + } + + #[test] + fn build_execute_params_no_query_tags_yields_empty_array() { + let mut spec = StatementSpec::new(); + spec.sql("SELECT 1"); + let (_sql, params) = build_execute_params(&spec, None).unwrap(); + assert!(params.query_tags.is_empty()); + } + #[test] fn build_execute_params_binds_positional_params_one_based() { let mut spec = StatementSpec::new(); diff --git a/src/statement/spec.rs b/src/statement/spec.rs index ff4ef809..d760fa85 100644 --- a/src/statement/spec.rs +++ b/src/statement/spec.rs @@ -360,6 +360,93 @@ fn serialize_query_tags(tags: &HashMap>) -> String { .join(",") } +/// Parse the comma-separated `key:value` wire shape produced by +/// [`serialize_query_tags`] back into structured `(key, value)` pairs. +/// +/// The Thrift backend sends query tags as a single `confOverlay.query_tags` +/// string, but the SEA `POST /statements` API takes them as a native +/// `[{key, value}]` array (it has no conf overlay). Both binding paths +/// (`Statement::query_tags` and a raw `statement_conf["query_tags"]`) land +/// in the same serialized string, so this is the single conversion point to +/// the structured form for the SEA wire. +/// +/// Inverse of the escaping in [`serialize_query_tags`]: a `\` escapes the +/// next character (`\\`→`\`, `\:`→`:`, `\,`→`,`); the first *unescaped* `:` +/// in a pair splits key from value; *unescaped* `,` separates pairs; a pair +/// with no unescaped `:` is a bare key (value `None`). Empty input → no tags. +pub(crate) fn deserialize_query_tags(serialized: &str) -> Vec<(String, Option)> { + if serialized.is_empty() { + return Vec::new(); + } + // Pass 1: split into pair substrings on unescaped commas, preserving + // the escape sequences for the per-pair split below. + let mut pairs: Vec = Vec::new(); + let mut current = String::new(); + let mut escaped = false; + for c in serialized.chars() { + if escaped { + current.push('\\'); + current.push(c); + escaped = false; + } else if c == '\\' { + escaped = true; + } else if c == ',' { + pairs.push(std::mem::take(&mut current)); + } else { + current.push(c); + } + } + if escaped { + current.push('\\'); // trailing lone backslash — keep verbatim + } + pairs.push(current); + + // Pass 2: split each pair on its first unescaped ':' and unescape both + // sides. Skip empty pairs (e.g. a trailing comma). + pairs + .into_iter() + .filter(|p| !p.is_empty()) + .map(|pair| { + let mut esc = false; + let mut split_at = None; + for (i, c) in pair.char_indices() { + if esc { + esc = false; + } else if c == '\\' { + esc = true; + } else if c == ':' { + split_at = Some(i); + break; + } + } + match split_at { + Some(i) => ( + unescape_query_tag(&pair[..i]), + Some(unescape_query_tag(&pair[i + 1..])), + ), + None => (unescape_query_tag(&pair), None), + } + }) + .collect() +} + +/// Resolve `\X` escape sequences to the literal `X` (used by +/// [`deserialize_query_tags`]). +fn unescape_query_tag(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars(); + while let Some(c) = chars.next() { + if c == '\\' { + if let Some(next) = chars.next() { + out.push(next); + } + } else { + out.push(c); + } + } + out +} + #[cfg(test)] mod tests { use super::*; @@ -572,4 +659,72 @@ mod tests { let pairs: std::collections::HashSet<&str> = s.split(',').collect(); assert!(pairs == ["a:1", "b"].iter().copied().collect(), "got: {s}",); } + + // ─── deserialize_query_tags (SEA native-array conversion) ───────────── + + #[test] + fn deserialize_query_tags_empty_string_yields_no_tags() { + assert!(deserialize_query_tags("").is_empty()); + } + + #[test] + fn deserialize_query_tags_single_pair() { + assert_eq!( + deserialize_query_tags("team:platform"), + vec![("team".to_string(), Some("platform".to_string()))] + ); + } + + #[test] + fn deserialize_query_tags_bare_key_is_none_value() { + assert_eq!( + deserialize_query_tags("production"), + vec![("production".to_string(), None)] + ); + } + + #[test] + fn deserialize_query_tags_unescapes_value_specials() { + // Inverse of `serialize_query_tags_matches_thrift_byte_shape_escapes`: + // wire `k:v\:1\,v\\2` → value `v:1,v\2`. + assert_eq!( + deserialize_query_tags("k:v\\:1\\,v\\\\2"), + vec![("k".to_string(), Some("v:1,v\\2".to_string()))] + ); + } + + #[test] + fn deserialize_query_tags_unescapes_key_backslash() { + // wire `k\\1:v` → key `k\1`. + assert_eq!( + deserialize_query_tags("k\\\\1:v"), + vec![("k\\1".to_string(), Some("v".to_string()))] + ); + } + + #[test] + fn deserialize_query_tags_empty_value_after_colon() { + // `key:` → an explicit empty-string value, distinct from a bare key. + assert_eq!( + deserialize_query_tags("key:"), + vec![("key".to_string(), Some(String::new()))] + ); + } + + #[test] + fn deserialize_query_tags_round_trips_serialize() { + // Round-trip a mixed map (valued tag with specials + a bare-key tag) + // through serialize → deserialize; compare order-insensitively since + // serialize follows non-deterministic HashMap order. + let mut tags = HashMap::new(); + tags.insert("team".to_string(), Some("a:b,c\\d".to_string())); + tags.insert("prod".to_string(), None); + let round_tripped: std::collections::HashSet<(String, Option)> = + deserialize_query_tags(&serialize_query_tags(&tags)) + .into_iter() + .collect(); + let expected: std::collections::HashSet<(String, Option)> = + tags.into_iter().collect(); + assert_eq!(round_tripped, expected); + } } diff --git a/src/types/sea.rs b/src/types/sea.rs index b6af8066..b4d17e19 100644 --- a/src/types/sea.rs +++ b/src/types/sea.rs @@ -298,6 +298,20 @@ pub struct StatementParameter { pub value: Option, } +/// A single per-statement query tag on the SEA `query_tags` array. +/// +/// The SEA `POST /statements` API takes query tags as a native +/// `[{ "key", "value" }]` array — *not* as a conf-overlay string (the SEA +/// request has no conf overlay, unlike Thrift's `TExecuteStatementReq. +/// confOverlay`). `value` is `None` for a bare key-only tag. This matches +/// the wire shape the pure-Python SEA backend and the ADBC C# driver send. +#[derive(Debug, Clone, Serialize)] +pub struct QueryTag { + pub key: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub value: Option, +} + /// Request body for statement execution. #[derive(Debug, Clone, Serialize)] pub struct ExecuteStatementRequest { @@ -326,6 +340,10 @@ pub struct ExecuteStatementRequest { /// Positional parameters for parameterized queries. #[serde(skip_serializing_if = "Vec::is_empty")] pub parameters: Vec, + /// Per-statement query tags, emitted as the native SEA `query_tags` + /// array (`[{key, value}]`). Empty → omitted from the request body. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub query_tags: Vec, } /// Parameters for statement execution (passed to client methods). @@ -338,6 +356,10 @@ pub struct ExecuteParams { pub row_limit: Option, /// Parameters for parameterized query execution. pub parameters: Vec, + /// Per-statement query tags, forwarded to the SEA request's native + /// `query_tags` array. Derived from `StatementSpec.statement_conf + /// ["query_tags"]` in `build_execute_params`. + pub query_tags: Vec, /// Optional sink for the server statement id, published as soon as /// the initial `POST /statements` returns it — *before* the /// sync-execute poll loop. Lets a detached canceller @@ -477,12 +499,48 @@ mod tests { row_limit: None, result_compression: None, parameters: vec![], + query_tags: vec![], }; let json = serde_json::to_string(&req).unwrap(); assert!(json.contains("\"warehouse_id\":\"abc123\"")); assert!(json.contains("\"session_id\":\"session-1\"")); assert!(!json.contains("\"catalog\"")); // None should be skipped + assert!(!json.contains("\"query_tags\"")); // empty should be skipped + } + + #[test] + fn test_execute_statement_request_serializes_query_tags_as_array() { + let req = ExecuteStatementRequest { + warehouse_id: "abc123".to_string(), + statement: "SELECT 1".to_string(), + session_id: Some("session-1".to_string()), + catalog: None, + schema: None, + disposition: "ARROW_STREAM".to_string(), + format: "ARROW_STREAM".to_string(), + wait_timeout: None, + on_wait_timeout: None, + row_limit: None, + result_compression: None, + parameters: vec![], + query_tags: vec![ + QueryTag { + key: "team".to_string(), + value: Some("eng".to_string()), + }, + QueryTag { + key: "prod".to_string(), + value: None, + }, + ], + }; + let json = serde_json::to_string(&req).unwrap(); + // Native SEA array shape: [{"key":..,"value":..}], value omitted when None. + assert!( + json.contains(r#""query_tags":[{"key":"team","value":"eng"},{"key":"prod"}]"#), + "got: {json}" + ); } #[test]