diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 630a04fe..cf21c688 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -160,7 +160,7 @@ fn build_execute_params( &spec.positional_params, &spec.named_params, &spec.raw_params, - 1, + ParameterScope::Statement, )?; } else { if !spec.positional_params.is_empty() @@ -174,7 +174,12 @@ fn build_execute_params( exec_params.scalar.row_limit = None; for set in &spec.parameter_sets { exec_params.parameter_sets.push(StatementParameterSet { - parameters: build_parameters(&set.positional, &set.named, &set.raw, 0)?, + parameters: build_parameters( + &set.positional, + &set.named, + &set.raw, + ParameterScope::ParameterSet, + )?, }); } } @@ -190,11 +195,38 @@ fn build_execute_params( Ok((sql, exec_params)) } +/// Where [`build_parameters`] sends a binding. +#[derive(Clone, Copy)] +enum ParameterScope { + /// The statement's own parameters, with one-based ordinals. + Statement, + /// One native parameter set, with zero-based ordinals. A typed NULL is + /// sent as VOID: the server combines the sets into one inline table, and a + /// STRING NULL would conflict with the type the other sets bind for that + /// column. + ParameterSet, +} + +impl ParameterScope { + fn ordinal_base(self) -> i32 { + match self { + Self::Statement => 1, + Self::ParameterSet => 0, + } + } + + fn encode_null(self, parameter: &mut StatementParameter, value: &TypedValue) { + if matches!(self, Self::ParameterSet) && matches!(value, TypedValue::Null) { + parameter.param_type = "VOID".to_owned(); + } + } +} + fn build_parameters( positional: &[TypedValue], named: &HashMap, raw: &[StatementParameter], - ordinal_base: i32, + scope: ParameterScope, ) -> Result> { // The server rejects mixed positional and named markers with an opaque // BAD_REQUEST; reject every mixed binding style here. @@ -214,15 +246,19 @@ fn build_parameters( let ordinal = |i: usize| { i32::try_from(i) .ok() - .and_then(|i| i.checked_add(ordinal_base)) + .and_then(|i| i.checked_add(scope.ordinal_base())) .ok_or_else(|| Error::invalid_argument().message("parameter ordinal exceeds i32")) }; let mut parameters = Vec::with_capacity(positional.len() + named.len() + raw.len()); for (i, value) in positional.iter().enumerate() { - parameters.push(typed_value_to_sea_parameter(ordinal(i)?, value)?); + let mut parameter = typed_value_to_sea_parameter(ordinal(i)?, value)?; + scope.encode_null(&mut parameter, value); + parameters.push(parameter); } for (name, value) in named { - parameters.push(named_typed_value_to_sea_parameter(name.clone(), value)?); + let mut parameter = named_typed_value_to_sea_parameter(name.clone(), value)?; + scope.encode_null(&mut parameter, value); + parameters.push(parameter); } for (i, p) in raw.iter().enumerate() { let mut param = p.clone(); @@ -1368,4 +1404,39 @@ mod tests { .message .contains("native parameter sets")); } + + #[test] + fn native_batch_sends_typed_null_as_void() { + let mut spec = StatementSpec::new(); + spec.sql("INSERT INTO t VALUES (?, ?)"); + spec.param(1, TypedValue::Int32(1)) + .unwrap() + .param(2, TypedValue::Int64(10)) + .unwrap() + .add_parameter_set(); + spec.param(1, TypedValue::Int32(2)) + .unwrap() + .param(2, TypedValue::Null) + .unwrap() + .add_parameter_set(); + let (_, params) = build_execute_params(&spec, None).unwrap(); + let null = ¶ms.parameter_sets[1].parameters[1]; + assert_eq!( + (null.param_type.as_str(), null.value.as_deref()), + ("VOID", None) + ); + + spec.sql("INSERT INTO t VALUES (:id)"); + spec.param_named("id", TypedValue::Null) + .unwrap() + .add_parameter_set(); + let (_, params) = build_execute_params(&spec, None).unwrap(); + assert_eq!(params.parameter_sets[0].parameters[0].param_type, "VOID"); + + // Ordinary statements keep the STRING NULL. + spec.sql("SELECT ?"); + spec.param(1, TypedValue::Null).unwrap(); + let (_, params) = build_execute_params(&spec, None).unwrap(); + assert_eq!(params.scalar.parameters[0].param_type, "STRING"); + } } diff --git a/src/statement/spec.rs b/src/statement/spec.rs index 4aaeb005..4ff8693a 100644 --- a/src/statement/spec.rs +++ b/src/statement/spec.rs @@ -277,6 +277,8 @@ impl StatementSpec { /// the scalar bindings. Execute sends all sets in one request. The caller /// selects eligible SQL; the server validates completeness and consistency. /// Scalar bindings left after the last snapshot are rejected at execution. + /// A [`TypedValue::Null`] in a set is sent as VOID, so it takes the type the + /// other sets bind for that column. /// /// Errors reading the batch's affected-row count are non-retryable because /// the rows may already be committed. diff --git a/tests/v0_execute_e2e.rs b/tests/v0_execute_e2e.rs index 03338866..43fcb787 100644 --- a/tests/v0_execute_e2e.rs +++ b/tests/v0_execute_e2e.rs @@ -70,16 +70,22 @@ async fn native_parameter_batch_counts_values_and_atomic_errors() { let mut statement = session.statement(); let checks = AssertUnwindSafe(async { statement.spec().sql(format!( - "CREATE TABLE {table} (id BIGINT NOT NULL) USING DELTA" + "CREATE TABLE {table} (id BIGINT NOT NULL, value BIGINT) USING DELTA" )); statement.execute().await.unwrap().close().await.unwrap(); - let insert = format!("INSERT INTO {table} VALUES (?)"); + let insert = format!("INSERT INTO {table} VALUES (?, ?)"); statement.spec().sql(&insert); - for id in [17, 29, 43] { + for (id, value) in [ + (1, TypedValue::Int64(10)), + (2, TypedValue::Null), + (3, TypedValue::Int64(30)), + ] { statement .spec() .param(1, TypedValue::Int64(id)) .unwrap() + .param(2, value) + .unwrap() .add_parameter_set(); } let executed = statement.execute().await.unwrap(); @@ -92,7 +98,13 @@ async fn native_parameter_batch_counts_values_and_atomic_errors() { TypedValue::Null, TypedValue::Int64(103), ] { - statement.spec().param(1, id).unwrap().add_parameter_set(); + statement + .spec() + .param(1, id) + .unwrap() + .param(2, TypedValue::Int64(0)) + .unwrap() + .add_parameter_set(); } let error = statement .execute() @@ -100,19 +112,33 @@ async fn native_parameter_batch_counts_values_and_atomic_errors() { .err() .expect("NOT NULL batch must fail"); assert_eq!(error.code, ErrorCode::SqlError); + // A type mismatch between sets would also fail the batch, before the + // NOT NULL check runs. + let message = error.message.to_uppercase(); + assert!( + error.sql_state.as_deref() == Some("23502") + || message.contains("NOT_NULL") + || message.contains("NOT NULL"), + "expected the NOT NULL violation: {} (SQLSTATE {:?})", + error.message, + error.sql_state + ); statement .spec() - .sql(format!("SELECT id FROM {table} ORDER BY id")); + .sql(format!("SELECT id, value FROM {table} ORDER BY id")); let mut executed = statement.execute().await.unwrap(); let stream = executed.result_stream_mut(); let mut rows = Vec::new(); while stream.next_batch().await.unwrap().is_some() { while let Some(row) = stream.next_row_in_batch() { - rows.push(row.get_i64(0).unwrap()); + rows.push((row.get_i64(0).unwrap(), row.get_i64(1).unwrap())); } } - assert_eq!(rows, vec![Some(17), Some(29), Some(43)]); + assert_eq!( + rows, + vec![(Some(1), Some(10)), (Some(2), None), (Some(3), Some(30))] + ); executed.close().await.unwrap(); }) .catch_unwind() diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index c77618d3..e276e3d8 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -3503,6 +3503,41 @@ async fn native_batch_preserves_order_and_resets_bindings() { ); } +#[tokio::test] +async fn native_batch_sends_typed_nulls_as_void() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_close_any_statement(&server).await; + let counts = native_batch_counts(vec![Some(1)], Some(vec![Some(2)])); + mount_execute(&server, succeeded_inline_body("batch-nulls", &counts)).await; + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("INSERT INTO t VALUES (?, ?)"); + stmt.spec() + .param(1, TypedValue::Int64(1)) + .unwrap() + .param(2, TypedValue::Null) + .unwrap() + .add_parameter_set(); + stmt.spec() + .param(1, TypedValue::Null) + .unwrap() + .param(2, TypedValue::Null) + .unwrap() + .add_parameter_set(); + let exec = stmt.execute().await.unwrap(); + assert_eq!(exec.num_modified_rows(), Some(2)); + let requests = native_batch_requests(&server).await; + assert_eq!(requests.len(), 1); + assert_eq!( + requests[0]["parameter_sets"], + json!([ + {"parameters": [{"ordinal":0,"type":"BIGINT","value":"1"}, {"ordinal":1,"type":"VOID","value":null}]}, + {"parameters": [{"ordinal":0,"type":"VOID","value":null}, {"ordinal":1,"type":"VOID","value":null}]} + ]) + ); +} + #[tokio::test] async fn native_batch_sends_entire_batch_and_preserves_server_limit_error() { let server = MockServer::start().await;