1use crate::actions::helpers;
2use crate::errors::{CancellationReason, DynoxideError, Result};
3use crate::partiql;
4use crate::storage_backend::StorageBackend;
5use crate::types::{AttributeValue, Item};
6use serde::{Deserialize, Serialize};
7
8#[derive(Debug, Clone, Default, Deserialize)]
9pub struct ExecuteTransactionRequest {
10 #[serde(rename = "TransactStatements")]
11 pub transact_statements: Vec<ParameterizedStatement>,
12 #[serde(rename = "ClientRequestToken", default)]
13 pub client_request_token: Option<String>,
14 #[serde(rename = "ReturnConsumedCapacity", default)]
15 pub return_consumed_capacity: Option<String>,
16}
17
18#[derive(Debug, Clone, Default, Deserialize, Serialize)]
22pub struct ParameterizedStatement {
23 #[serde(rename = "Statement")]
24 pub statement: String,
25 #[serde(rename = "Parameters", default)]
26 pub parameters: Option<Vec<AttributeValue>>,
27}
28
29#[derive(Debug, Clone, Default, Serialize)]
32pub struct ExecuteTransactionResponse {
33 #[serde(rename = "Responses", skip_serializing_if = "Option::is_none")]
34 pub responses: Option<Vec<ItemResponse>>,
35 #[serde(rename = "ConsumedCapacity", skip_serializing_if = "Option::is_none")]
36 pub consumed_capacity: Option<Vec<crate::types::ConsumedCapacity>>,
37}
38
39#[derive(Debug, Clone, Default, Serialize)]
40pub struct ItemResponse {
41 #[serde(rename = "Item", skip_serializing_if = "Option::is_none")]
42 pub item: Option<Item>,
43}
44
45pub async fn execute<S: StorageBackend>(
46 storage: &S,
47 request: ExecuteTransactionRequest,
48) -> Result<ExecuteTransactionResponse> {
49 let statements = &request.transact_statements;
50
51 if statements.is_empty() {
53 return Err(DynoxideError::ValidationException(
54 "1 validation error detected: Value at 'transactStatements' failed to satisfy constraint: Member must have length greater than or equal to 1".to_string(),
55 ));
56 }
57 if statements.len() > 100 {
58 return Err(DynoxideError::ValidationException(
59 "Member must have length less than or equal to 100".to_string(),
60 ));
61 }
62
63 let mut parsed = Vec::with_capacity(statements.len());
65 for stmt in statements {
66 let ast = partiql::parser::parse(&stmt.statement).map_err(|e| {
67 DynoxideError::ValidationException(format!(
68 "Statement wasn't well formed, got error: {e}"
69 ))
70 })?;
71 let params = stmt.parameters.clone().unwrap_or_default();
72 parsed.push((ast, params));
73 }
74
75 let responses =
77 helpers::with_write_transaction(storage, execute_within_transaction(storage, &parsed))
78 .await?;
79
80 let builder = if is_read_set(&parsed) {
88 crate::types::transactional_read_capacity
89 } else {
90 crate::types::transactional_write_capacity
91 };
92 let consumed_capacity = crate::types::build_transactional_capacity(
93 &statement_table_units(parsed.iter().map(|(stmt, _)| stmt)),
94 &request.return_consumed_capacity,
95 builder,
96 );
97
98 Ok(ExecuteTransactionResponse {
99 responses: Some(responses),
100 consumed_capacity,
101 })
102}
103
104fn is_read_set(parsed: &[(partiql::parser::Statement, Vec<AttributeValue>)]) -> bool {
111 parsed
112 .iter()
113 .all(|(stmt, _)| matches!(stmt, partiql::parser::Statement::Select { .. }))
114}
115
116fn statement_table_units<'a>(
121 statements: impl Iterator<Item = &'a partiql::parser::Statement>,
122) -> std::collections::HashMap<String, f64> {
123 let mut table_units: std::collections::HashMap<String, f64> = std::collections::HashMap::new();
124 for stmt in statements {
125 if let Some(tbl) = partiql::parser::table_name(stmt) {
126 *table_units.entry(tbl.to_string()).or_default() +=
127 crate::types::TRANSACTIONAL_CAPACITY_FACTOR;
128 }
129 }
130 table_units
131}
132
133pub(crate) fn replay_response(
142 statements: &[ParameterizedStatement],
143 mode: &Option<String>,
144 cached_responses: Option<Vec<ItemResponse>>,
145) -> ExecuteTransactionResponse {
146 let parsed: Vec<partiql::parser::Statement> = statements
147 .iter()
148 .filter_map(|s| partiql::parser::parse(&s.statement).ok())
149 .collect();
150 ExecuteTransactionResponse {
151 responses: cached_responses,
152 consumed_capacity: crate::types::build_transactional_capacity(
153 &statement_table_units(parsed.iter()),
154 mode,
155 crate::types::transactional_read_capacity,
156 ),
157 }
158}
159
160async fn execute_within_transaction<S: StorageBackend>(
161 storage: &S,
162 parsed: &[(partiql::parser::Statement, Vec<AttributeValue>)],
163) -> Result<Vec<ItemResponse>> {
164 let mut responses = Vec::with_capacity(parsed.len());
165 let mut cancellation_reasons: Vec<CancellationReason> = Vec::with_capacity(parsed.len());
166
167 for (stmt, params) in parsed {
168 match partiql::executor::execute(storage, stmt, params, None).await {
169 Ok(result) => {
170 let item = result.and_then(|items| items.into_iter().next());
171 responses.push(ItemResponse { item });
172 cancellation_reasons.push(CancellationReason {
173 code: "None".to_string(),
174 message: None,
175 item: None,
176 });
177 }
178 Err(e) => {
179 let message = Some(e.to_string());
181 let (code, item) = match e {
182 DynoxideError::ConditionalCheckFailedException(_, item) => {
183 ("ConditionalCheckFailed".to_string(), item)
184 }
185 DynoxideError::DuplicateItemException(_) => ("DuplicateItem".to_string(), None),
186 DynoxideError::ValidationException(_)
190 | DynoxideError::KeyEmptyValueValidation(_) => {
191 ("ValidationError".to_string(), None)
192 }
193 _ => ("InternalError".to_string(), None),
194 };
195 responses.push(ItemResponse { item: None });
196 cancellation_reasons.push(CancellationReason {
197 code,
198 message,
199 item,
200 });
201
202 for _ in responses.len()..parsed.len() {
205 responses.push(ItemResponse { item: None });
206 cancellation_reasons.push(CancellationReason {
207 code: "None".to_string(),
208 message: None,
209 item: None,
210 });
211 }
212
213 let codes: Vec<&str> = cancellation_reasons
214 .iter()
215 .map(|r| r.code.as_str())
216 .collect();
217 let message = format!(
218 "Transaction cancelled, please refer cancellation reasons for specific reasons [{}]",
219 codes.join(", ")
220 );
221 return Err(DynoxideError::TransactionCanceledException(
222 message,
223 cancellation_reasons,
224 ));
225 }
226 }
227 }
228
229 Ok(responses)
230}