1use crate::error::{BatchUpdateError, internal_error};
16use crate::model::request_options::Priority;
17use crate::model::result_set_stats::RowCount;
18use crate::model::{ExecuteBatchDmlResponse, RequestOptions, ResultSet};
19use crate::statement::Statement;
20use crate::{Error, Result};
21use google_cloud_gax::backoff_policy::BackoffPolicyArg;
22use google_cloud_gax::error::rpc::Code;
23use google_cloud_gax::error::rpc::Status as RpcStatus;
24use google_cloud_gax::options::RequestOptions as GaxRequestOptions;
25use google_cloud_gax::retry_policy::RetryPolicyArg;
26use std::time::Duration;
27
28#[derive(Clone, Default, Debug)]
30pub struct BatchDmlBuilder {
31 statements: Vec<Statement>,
32 request_options: Option<RequestOptions>,
33 last_statements: bool,
34 gax_options: GaxRequestOptions,
35}
36
37impl BatchDmlBuilder {
38 pub fn new() -> Self {
40 BatchDmlBuilder::default()
41 }
42
43 pub fn add_statement(mut self, statement: impl Into<Statement>) -> Self {
45 self.statements.push(statement.into());
46 self
47 }
48
49 pub fn set_request_tag(mut self, tag: impl Into<String>) -> Self {
64 self.request_options
65 .get_or_insert_with(RequestOptions::default)
66 .request_tag = tag.into();
67 self
68 }
69
70 pub fn set_priority(mut self, priority: Priority) -> Self {
86 self.request_options
87 .get_or_insert_with(RequestOptions::default)
88 .priority = priority;
89 self
90 }
91
92 pub fn with_attempt_timeout(mut self, timeout: Duration) -> Self {
94 self.gax_options.set_attempt_timeout(timeout);
95 self
96 }
97
98 pub fn with_retry_policy(mut self, policy: impl Into<RetryPolicyArg>) -> Self {
100 self.gax_options.set_retry_policy(policy);
101 self
102 }
103
104 pub fn with_backoff_policy(mut self, policy: impl Into<BackoffPolicyArg>) -> Self {
106 self.gax_options.set_backoff_policy(policy);
107 self
108 }
109
110 pub fn set_last_statements(mut self, last_statements: bool) -> Self {
126 self.last_statements = last_statements;
127 self
128 }
129
130 pub fn build(self) -> BatchDml {
132 BatchDml {
133 statements: self.statements,
134 request_options: self.request_options,
135 last_statements: self.last_statements,
136 gax_options: self.gax_options,
137 }
138 }
139}
140
141#[derive(Clone, Debug)]
143pub struct BatchDml {
144 pub(crate) statements: Vec<Statement>,
145 pub(crate) request_options: Option<RequestOptions>,
146 pub(crate) last_statements: bool,
147 pub(crate) gax_options: GaxRequestOptions,
148}
149
150impl BatchDml {
151 pub fn builder() -> BatchDmlBuilder {
153 BatchDmlBuilder::new()
154 }
155}
156
157impl From<BatchDmlBuilder> for BatchDml {
158 fn from(builder: BatchDmlBuilder) -> Self {
159 builder.build()
160 }
161}
162
163impl<T: Into<Statement>> From<Vec<T>> for BatchDml {
164 fn from(statements: Vec<T>) -> Self {
165 BatchDml {
166 statements: statements.into_iter().map(Into::into).collect(),
167 request_options: None,
168 last_statements: false,
169 gax_options: GaxRequestOptions::default(),
170 }
171 }
172}
173
174fn extract_update_counts(result_sets: &[ResultSet]) -> Result<Vec<i64>> {
179 let mut update_counts = Vec::with_capacity(result_sets.len());
180 for result_set in result_sets {
181 let stats = result_set
182 .stats
183 .as_ref()
184 .ok_or_else(|| internal_error("ExecuteBatchDml ResultSet missing stats/row_count"))?;
185 let exact_count = match stats.row_count {
186 Some(RowCount::RowCountExact(count)) => count,
187 _ => {
188 return Err(internal_error(
189 "ExecuteBatchDml returned an invalid or missing row count type",
190 ));
191 }
192 };
193 update_counts.push(exact_count);
194 }
195 Ok(update_counts)
196}
197
198pub(crate) fn process_response(response: ExecuteBatchDmlResponse) -> Result<Vec<i64>> {
200 if let Some(status) = response
202 .status
203 .filter(|status| status.code != Code::Ok as i32)
204 {
205 let grpc_status = RpcStatus::default()
206 .set_code(status.code)
207 .set_message(status.message)
208 .set_details(status.details);
209 if status.code == Code::Aborted as i32 {
212 return Err(Error::service(grpc_status));
213 }
214 let update_counts = extract_update_counts(&response.result_sets)?;
215 return Err(BatchUpdateError::build_error(update_counts, grpc_status));
216 }
217
218 extract_update_counts(&response.result_sets)
219}
220
221#[cfg(test)]
222mod tests {
223 use super::*;
224 use crate::model::{ResultSet, ResultSetMetadata, ResultSetStats, Transaction};
225 use google_cloud_rpc::model::Status;
226 use static_assertions::assert_impl_all;
227
228 #[test]
229 fn auto_traits() {
230 assert_impl_all!(BatchDml: Send, Sync, Clone, std::fmt::Debug);
231 assert_impl_all!(BatchDmlBuilder: Send, Sync, Clone, std::fmt::Debug);
232 }
233
234 #[test]
235 fn builder() {
236 let stmt1 = Statement::builder("UPDATE t SET c = 1 WHERE id = 1").build();
237 let stmt2 = Statement::builder("UPDATE t SET c = 2 WHERE id = 2").build();
238
239 let batch = BatchDml::builder()
240 .add_statement(stmt1)
241 .add_statement(stmt2)
242 .set_last_statements(true)
243 .build();
244
245 assert_eq!(batch.statements.len(), 2);
246 assert_eq!(batch.statements[0].sql, "UPDATE t SET c = 1 WHERE id = 1");
247 assert_eq!(batch.statements[1].sql, "UPDATE t SET c = 2 WHERE id = 2");
248 assert!(batch.last_statements);
249 assert!(
250 batch.request_options.is_none(),
251 "Unexpected request_options set: {:#?}",
252 batch.request_options
253 );
254 }
255
256 #[test]
257 fn builder_with_gax_options() {
258 use google_cloud_gax::backoff_policy::BackoffPolicy;
259 use google_cloud_gax::retry_policy::Aip194Strict;
260 use google_cloud_gax::retry_state::RetryState;
261 use std::time::Duration;
262
263 #[derive(Debug)]
264 struct DummyBackoff;
265 impl BackoffPolicy for DummyBackoff {
266 fn on_failure(&self, _state: &RetryState) -> Duration {
267 Duration::ZERO
268 }
269 }
270
271 let stmt = Statement::builder("UPDATE t SET c = 1 WHERE id = 1").build();
272
273 let batch = BatchDml::builder()
274 .add_statement(stmt)
275 .with_attempt_timeout(Duration::from_secs(5))
276 .with_retry_policy(Aip194Strict)
277 .with_backoff_policy(DummyBackoff)
278 .build();
279
280 assert_eq!(
281 *batch.gax_options.attempt_timeout(),
282 Some(Duration::from_secs(5))
283 );
284 assert!(batch.gax_options.retry_policy().is_some());
285 assert!(batch.gax_options.backoff_policy().is_some());
286 }
287
288 #[test]
289 fn builder_with_request_tag() {
290 let stmt = Statement::builder("UPDATE t SET c = 1 WHERE id = 1").build();
291
292 let batch = BatchDml::builder()
293 .add_statement(stmt)
294 .set_request_tag("tag1")
295 .build();
296
297 assert_eq!(batch.statements.len(), 1);
298 assert_eq!(
299 batch
300 .request_options
301 .expect("request options missing")
302 .request_tag,
303 "tag1"
304 );
305 }
306
307 #[test]
308 fn builder_with_priority() {
309 let stmt = Statement::builder("UPDATE t SET c = 1 WHERE id = 1").build();
310
311 let batch = BatchDml::builder()
312 .add_statement(stmt)
313 .set_priority(Priority::High)
314 .build();
315
316 assert_eq!(batch.statements.len(), 1);
317 assert_eq!(
318 batch
319 .request_options
320 .expect("request options missing")
321 .priority,
322 Priority::High
323 );
324 }
325
326 #[test]
327 fn process_response_success() -> anyhow::Result<()> {
328 let stats1 = ResultSetStats {
329 row_count: Some(RowCount::RowCountExact(5)),
330 ..Default::default()
331 };
332 let stats2 = ResultSetStats {
333 row_count: Some(RowCount::RowCountExact(10)),
334 ..Default::default()
335 };
336
337 let result_set1 = ResultSet {
338 stats: Some(stats1),
339 ..Default::default()
340 };
341 let result_set2 = ResultSet {
342 stats: Some(stats2),
343 ..Default::default()
344 };
345
346 let response = ExecuteBatchDmlResponse {
347 result_sets: vec![result_set1, result_set2],
348 status: None,
349 ..Default::default()
350 };
351
352 let update_counts = process_response(response)?;
353 assert_eq!(
354 update_counts,
355 vec![5, 10],
356 "Expected update counts to match exact counts from result sets"
357 );
358 Ok(())
359 }
360
361 #[test]
362 fn process_response_grpc_error() {
363 let stats = ResultSetStats {
364 row_count: Some(RowCount::RowCountExact(3)),
365 ..Default::default()
366 };
367 let result_set = ResultSet {
368 stats: Some(stats),
369 ..Default::default()
370 };
371
372 let err_status = Status::default()
374 .set_code(Code::InvalidArgument as i32)
375 .set_message("Bad query");
376
377 let response = ExecuteBatchDmlResponse {
378 result_sets: vec![result_set],
379 status: Some(err_status),
380 ..Default::default()
381 };
382
383 let result = process_response(response);
384 let error = result.expect_err("should return error when response status is non-zero");
385 let batch_error =
386 BatchUpdateError::extract(&error).expect("should extract BatchUpdateError cleanly");
387
388 assert_eq!(
389 batch_error.update_counts,
390 vec![3],
391 "Update counts should contain the successful statement's count"
392 );
393 assert_eq!(
394 batch_error
395 .status
396 .status()
397 .expect("status should be available")
398 .code,
399 Code::InvalidArgument,
400 "Error code should be InvalidArgument"
401 );
402 assert_eq!(
403 batch_error
404 .status
405 .status()
406 .expect("status should be available")
407 .message,
408 "Bad query",
409 "Error message should match the server status message"
410 );
411 }
412
413 #[test]
414 fn process_response_grpc_error_empty_result_sets() {
415 let err_status = Status::default()
416 .set_code(Code::InvalidArgument as i32)
417 .set_message("Initial statement syntax error");
418
419 let response = ExecuteBatchDmlResponse {
420 result_sets: vec![],
421 status: Some(err_status),
422 ..Default::default()
423 };
424
425 let result = process_response(response);
426 let error = result.expect_err("should return error when initial statement failed");
427 let batch_error =
428 BatchUpdateError::extract(&error).expect("should extract BatchUpdateError cleanly");
429
430 assert_eq!(
431 batch_error.update_counts,
432 Vec::<i64>::new(),
433 "Update counts should be empty when the first statement failed"
434 );
435 assert_eq!(
436 batch_error
437 .status
438 .status()
439 .expect("status should be available")
440 .code,
441 Code::InvalidArgument,
442 "Error code should be InvalidArgument"
443 );
444 assert_eq!(
445 batch_error
446 .status
447 .status()
448 .expect("status should be available")
449 .message,
450 "Initial statement syntax error",
451 "Error message should match the server status message"
452 );
453 }
454
455 #[test]
456 fn process_response_metadata_with_stats_grpc_error() {
457 let stats = ResultSetStats {
458 row_count: Some(RowCount::RowCountExact(7)),
459 ..Default::default()
460 };
461 let result_set = ResultSet {
462 metadata: Some(ResultSetMetadata {
463 transaction: Some(Transaction {
464 id: vec![7, 7, 7].into(),
465 ..Default::default()
466 }),
467 ..Default::default()
468 }),
469 stats: Some(stats),
470 ..Default::default()
471 };
472
473 let err_status = Status::default()
474 .set_code(Code::InvalidArgument as i32)
475 .set_message("Second statement invalid");
476
477 let response = ExecuteBatchDmlResponse {
478 result_sets: vec![result_set],
479 status: Some(err_status),
480 ..Default::default()
481 };
482
483 let result = process_response(response);
484 let error = result.expect_err("should return error when subsequent statement fails");
485 let batch_error =
486 BatchUpdateError::extract(&error).expect("should extract BatchUpdateError cleanly");
487
488 assert_eq!(
489 batch_error.update_counts,
490 vec![7],
491 "Update counts should contain the successful first statement count"
492 );
493 assert_eq!(
494 batch_error
495 .status
496 .status()
497 .expect("status should be available")
498 .code,
499 Code::InvalidArgument,
500 "Status code should be InvalidArgument"
501 );
502 assert_eq!(
503 batch_error
504 .status
505 .status()
506 .expect("status should be available")
507 .message,
508 "Second statement invalid",
509 "Status message should match server status message"
510 );
511 }
512
513 #[test]
514 fn process_response_aborted() {
515 let stats = ResultSetStats {
516 row_count: Some(RowCount::RowCountExact(3)),
517 ..Default::default()
518 };
519 let result_set = ResultSet {
520 stats: Some(stats),
521 ..Default::default()
522 };
523
524 let err_status = Status::default()
525 .set_code(Code::Aborted as i32)
526 .set_message("transaction aborted");
527
528 let response = ExecuteBatchDmlResponse {
529 result_sets: vec![result_set],
530 status: Some(err_status),
531 ..Default::default()
532 };
533
534 let result = process_response(response);
535 let error = result.expect_err("should return error on aborted status");
536 let batch_error = BatchUpdateError::extract(&error);
537 assert!(
538 batch_error.is_none(),
539 "Unexpected BatchUpdateError on Aborted status: {batch_error:?}"
540 );
541 assert_eq!(
542 error.status().expect("status should be present").code,
543 Code::Aborted,
544 "Service error code should be Aborted"
545 );
546 assert_eq!(
547 error.status().expect("status should be present").message,
548 "transaction aborted",
549 "Service error message should match aborted message"
550 );
551 }
552
553 fn assert_process_response_fails(
554 response: ExecuteBatchDmlResponse,
555 expected_error_substring: &str,
556 failure_description: &'static str,
557 ) {
558 let result = process_response(response);
559 let error = result.expect_err(failure_description);
560 assert!(
561 error.to_string().contains(expected_error_substring),
562 "Expected error containing '{expected_error_substring}', got: {error}"
563 );
564 }
565
566 #[test]
567 fn process_response_missing_stats() {
568 let result_set = ResultSet {
569 stats: None,
570 ..Default::default()
571 };
572
573 let response = ExecuteBatchDmlResponse {
574 result_sets: vec![result_set],
575 ..Default::default()
576 };
577
578 assert_process_response_fails(
579 response,
580 "ExecuteBatchDml ResultSet missing stats/row_count",
581 "should fail when ResultSet is missing stats",
582 );
583 }
584
585 #[test]
586 fn process_response_subsequent_result_set_missing_stats() {
587 let stats = ResultSetStats {
588 row_count: Some(RowCount::RowCountExact(5)),
589 ..Default::default()
590 };
591 let result_set1 = ResultSet {
592 stats: Some(stats),
593 ..Default::default()
594 };
595 let result_set2 = ResultSet {
596 stats: None,
597 ..Default::default()
598 };
599
600 let response = ExecuteBatchDmlResponse {
601 result_sets: vec![result_set1, result_set2],
602 ..Default::default()
603 };
604
605 assert_process_response_fails(
606 response,
607 "ExecuteBatchDml ResultSet missing stats/row_count",
608 "should fail when subsequent ResultSet is missing stats",
609 );
610 }
611
612 #[test]
613 fn process_response_grpc_error_with_missing_stats() {
614 let result_set = ResultSet {
615 metadata: Some(ResultSetMetadata {
616 transaction: Some(Transaction {
617 id: vec![7, 7, 7].into(),
618 ..Default::default()
619 }),
620 ..Default::default()
621 }),
622 stats: None,
623 ..Default::default()
624 };
625
626 let error_status = Status::default()
627 .set_code(Code::InvalidArgument as i32)
628 .set_message("Table not found or syntax invalid");
629
630 let response = ExecuteBatchDmlResponse {
631 result_sets: vec![result_set],
632 status: Some(error_status),
633 ..Default::default()
634 };
635
636 assert_process_response_fails(
637 response,
638 "ExecuteBatchDml ResultSet missing stats/row_count",
639 "should fail with internal error when stats are missing, even if grpc error status is present",
640 );
641 }
642
643 #[test]
644 fn process_response_grpc_error_with_invalid_row_count_type() {
645 let stats = ResultSetStats {
646 row_count: Some(RowCount::RowCountLowerBound(10)),
647 ..Default::default()
648 };
649 let result_set = ResultSet {
650 stats: Some(stats),
651 ..Default::default()
652 };
653
654 let error_status = Status::default()
655 .set_code(Code::InvalidArgument as i32)
656 .set_message("syntax error on subsequent statement");
657
658 let response = ExecuteBatchDmlResponse {
659 result_sets: vec![result_set],
660 status: Some(error_status),
661 ..Default::default()
662 };
663
664 assert_process_response_fails(
665 response,
666 "invalid or missing row count type",
667 "should fail with internal error when row count type is invalid, even with grpc error status",
668 );
669 }
670
671 #[test]
672 fn process_response_status_ok_code() -> anyhow::Result<()> {
673 let stats = ResultSetStats {
674 row_count: Some(RowCount::RowCountExact(4)),
675 ..Default::default()
676 };
677 let result_set = ResultSet {
678 stats: Some(stats),
679 ..Default::default()
680 };
681 let ok_status = Status::default().set_code(Code::Ok as i32);
682 let response = ExecuteBatchDmlResponse {
683 result_sets: vec![result_set],
684 status: Some(ok_status),
685 ..Default::default()
686 };
687
688 let update_counts = process_response(response)?;
689 assert_eq!(
690 update_counts,
691 vec![4],
692 "Expected update counts when status code is explicitly Ok"
693 );
694 Ok(())
695 }
696
697 #[test]
698 fn process_response_status_ok_code_missing_stats() {
699 let result_set = ResultSet {
700 stats: None,
701 ..Default::default()
702 };
703 let ok_status = Status::default().set_code(Code::Ok as i32);
704 let response = ExecuteBatchDmlResponse {
705 result_sets: vec![result_set],
706 status: Some(ok_status),
707 ..Default::default()
708 };
709
710 assert_process_response_fails(
711 response,
712 "ExecuteBatchDml ResultSet missing stats/row_count",
713 "should fail when status is Ok but ResultSet is missing stats",
714 );
715 }
716
717 #[test]
718 fn process_response_aborted_empty_result_sets() {
719 let err_status = Status::default()
720 .set_code(Code::Aborted as i32)
721 .set_message("transaction aborted on first statement");
722
723 let response = ExecuteBatchDmlResponse {
724 result_sets: vec![],
725 status: Some(err_status),
726 ..Default::default()
727 };
728
729 let result = process_response(response);
730 let error = result
731 .expect_err("should return service error on aborted status with empty result sets");
732 assert_eq!(
733 error.status().expect("status should be present").code,
734 Code::Aborted,
735 "Service error code should be Aborted"
736 );
737 assert_eq!(
738 error.status().expect("status should be present").message,
739 "transaction aborted on first statement",
740 "Service error message should match aborted message"
741 );
742 }
743
744 #[test]
745 fn process_response_aborted_with_missing_stats() {
746 let result_set = ResultSet {
747 stats: None,
748 ..Default::default()
749 };
750 let err_status = Status::default()
751 .set_code(Code::Aborted as i32)
752 .set_message("transaction aborted");
753
754 let response = ExecuteBatchDmlResponse {
755 result_sets: vec![result_set],
756 status: Some(err_status),
757 ..Default::default()
758 };
759
760 let result = process_response(response);
761 let error = result
762 .expect_err("abort status should take precedence over missing stats in result set");
763 assert_eq!(
764 error.status().expect("status should be present").code,
765 Code::Aborted,
766 "Service error code should be Aborted"
767 );
768 assert_eq!(
769 error.status().expect("status should be present").message,
770 "transaction aborted",
771 "Service error message should match aborted message"
772 );
773 }
774
775 #[test]
776 fn process_response_empty_result_sets_success() -> anyhow::Result<()> {
777 let response = ExecuteBatchDmlResponse {
778 result_sets: vec![],
779 status: None,
780 ..Default::default()
781 };
782
783 let update_counts = process_response(response)?;
784 assert_eq!(
785 update_counts,
786 Vec::<i64>::new(),
787 "Expected empty update counts when result_sets is empty and status is None"
788 );
789 Ok(())
790 }
791
792 #[test]
793 fn process_response_missing_row_count_type() {
794 let stats = ResultSetStats {
795 row_count: None,
796 ..Default::default()
797 };
798
799 let result_set = ResultSet {
800 stats: Some(stats),
801 ..Default::default()
802 };
803
804 let response = ExecuteBatchDmlResponse {
805 result_sets: vec![result_set],
806 ..Default::default()
807 };
808
809 assert_process_response_fails(
810 response,
811 "invalid or missing row count type",
812 "should fail when row count is missing in stats",
813 );
814 }
815
816 #[test]
817 fn process_response_row_count_lower_bound() {
818 let stats = ResultSetStats {
819 row_count: Some(RowCount::RowCountLowerBound(42)),
820 ..Default::default()
821 };
822
823 let result_set = ResultSet {
824 stats: Some(stats),
825 ..Default::default()
826 };
827
828 let response = ExecuteBatchDmlResponse {
829 result_sets: vec![result_set],
830 ..Default::default()
831 };
832
833 assert_process_response_fails(
834 response,
835 "invalid or missing row count type",
836 "RowCountLowerBound is not valid for Batch DML",
837 );
838 }
839
840 #[test]
841 fn from_vector_of_strings() {
842 let statements = vec!["UPDATE table SET col = 1", "UPDATE table SET col = 2"];
843 let batch: BatchDml = statements.into();
844 assert_eq!(
845 batch.statements.len(),
846 2,
847 "Expected exactly 2 statements converted from strings"
848 );
849 assert_eq!(batch.statements[0].sql, "UPDATE table SET col = 1");
850 assert_eq!(batch.statements[1].sql, "UPDATE table SET col = 2");
851 }
852
853 #[test]
854 fn from_vector_of_statements() {
855 let statement1 = Statement::builder("UPDATE table SET col = 1").build();
856 let statement2 = Statement::builder("UPDATE table SET col = 2").build();
857 let statements = vec![statement1, statement2];
858 let batch: BatchDml = statements.into();
859 assert_eq!(
860 batch.statements.len(),
861 2,
862 "Expected exactly 2 statements converted from Statement objects"
863 );
864 assert_eq!(batch.statements[0].sql, "UPDATE table SET col = 1");
865 assert_eq!(batch.statements[1].sql, "UPDATE table SET col = 2");
866 }
867
868 #[test]
869 fn from_builder() {
870 let builder = BatchDml::builder().add_statement("UPDATE table SET col = 1");
871 let batch: BatchDml = builder.into();
872 assert_eq!(
873 batch.statements.len(),
874 1,
875 "Expected 1 statement built from builder"
876 );
877 assert_eq!(batch.statements[0].sql, "UPDATE table SET col = 1");
878 }
879}