Skip to main content

dynoxide/actions/
execute_statement.rs

1use crate::errors::{DynoxideError, Result};
2use crate::partiql;
3use crate::storage_backend::StorageBackend;
4use crate::types::{AttributeValue, Item};
5use serde::{Deserialize, Serialize};
6
7#[derive(Debug, Default, Deserialize)]
8pub struct ExecuteStatementRequest {
9    #[serde(rename = "Statement")]
10    pub statement: String,
11    #[serde(rename = "Parameters", default)]
12    pub parameters: Option<Vec<AttributeValue>>,
13    #[serde(rename = "Limit", default)]
14    pub limit: Option<usize>,
15    #[serde(rename = "NextToken", default)]
16    pub next_token: Option<String>,
17    /// Accepted for API compatibility. Has no behavioural effect — SQLite
18    /// reads are always consistent.
19    #[serde(rename = "ConsistentRead", default)]
20    pub consistent_read: Option<bool>,
21    #[serde(rename = "ReturnConsumedCapacity", default)]
22    pub return_consumed_capacity: Option<String>,
23}
24
25#[derive(Debug, Default, Serialize)]
26pub struct ExecuteStatementResponse {
27    #[serde(rename = "Items", skip_serializing_if = "Option::is_none")]
28    pub items: Option<Vec<Item>>,
29    #[serde(rename = "NextToken", skip_serializing_if = "Option::is_none")]
30    pub next_token: Option<String>,
31    #[serde(rename = "ConsumedCapacity", skip_serializing_if = "Option::is_none")]
32    pub consumed_capacity: Option<crate::types::ConsumedCapacity>,
33}
34
35pub async fn execute<S: StorageBackend>(
36    storage: &S,
37    request: ExecuteStatementRequest,
38) -> Result<ExecuteStatementResponse> {
39    // Limit is checked before the statement is parsed. A zero limit would
40    // otherwise read nothing and mint no token, silently ending a paginated
41    // walk. The wording follows Scan's shape (value kept, lowercase 'limit'),
42    // not Query's, matching what ExecuteStatement itself returns (captured
43    // eu-west-2, 2026-07-29).
44    if request.limit == Some(0) {
45        return Err(DynoxideError::ValidationException(
46            crate::validation::envelope_message(
47                "Value '0' at 'limit' failed to satisfy constraint: \
48                 Member must have value greater than or equal to 1",
49            ),
50        ));
51    }
52
53    // A COUNT projection is rejected before parsing, with DynamoDB's bare
54    // message rather than the wasn't-well-formed wrapper the parse errors
55    // below carry. ExecuteStatement is the captured surface for this shape.
56    if let Some(msg) = partiql::parser::count_projection_rejection(&request.statement) {
57        return Err(DynoxideError::ValidationException(msg));
58    }
59
60    let stmt = partiql::parser::parse(&request.statement).map_err(|e| {
61        DynoxideError::ValidationException(format!(
62            "Statement wasn't well formed, can't be processed: {e}"
63        ))
64    })?;
65
66    let params = request.parameters.unwrap_or_default();
67    let page = partiql::executor::execute_page(
68        storage,
69        &stmt,
70        &params,
71        request.limit,
72        request.next_token.as_deref(),
73    )
74    .await?;
75    let partiql::executor::StatementPage {
76        items,
77        size,
78        next_token,
79        ..
80    } = page;
81
82    // ConsumedCapacity is returned whenever ReturnConsumedCapacity is requested,
83    // unlike some emulators that omit it. A SELECT is charged read units (an
84    // eventually consistent read unless ConsistentRead is set); INSERT, UPDATE
85    // and DELETE are charged write units. The unit (single object, not an array)
86    // comes from the shared `types.rs` helpers.
87    let consumed_capacity = partiql::parser::table_name(&stmt).and_then(|table| {
88        let units = if matches!(stmt, partiql::parser::Statement::Select { .. }) {
89            crate::types::read_capacity_units_with_consistency(
90                size,
91                request.consistent_read.unwrap_or(false),
92            )
93        } else {
94            crate::types::write_capacity_units(size)
95        };
96        crate::types::consumed_capacity(table, units, &request.return_consumed_capacity)
97    });
98
99    Ok(ExecuteStatementResponse {
100        items,
101        next_token,
102        consumed_capacity,
103    })
104}