Light, fluffy, and always free - The AWS Local Emulator alternative
fix(dynamodb): add missing ConsumedCapacity for PartiQL's ExecuteStatement and BatchExecuteStatement (#4165)
TATSUNO “Taz” Yasuhiro65b2b13f5c3f
diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.javaindex 5a1d6fdfa6..0e5ee42f5d 100644--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java@@ -1776,6 +1776,12 @@ public class DynamoDbJsonHandler {}}+ private static void requireValidReturnConsumedCapacity(JsonNode request) {+ List<String> validationErrors = new ArrayList<>();+ addReturnConsumedCapacityError(request, validationErrors);+ throwValidationErrors(validationErrors);+ }+private static void throwValidationErrors(List<String> validationErrors) {if (validationErrors.isEmpty()) {return;@@ -2273,7 +2279,7 @@ public class DynamoDbJsonHandler {* Half a read unit per 4KB read, doubled for a strongly consistent read, with the* half-unit minimum DynamoDB charges even when nothing is found.*/- private static double readCapacityUnits(long bytes, boolean consistentRead) {+ static double readCapacityUnits(long bytes, boolean consistentRead) {var units = Math.max(1, (bytes + 4095) / 4096) * 0.5;return consistentRead ? units * 2 : units;}@@ -2714,6 +2720,7 @@ public class DynamoDbJsonHandler {}private Response handleExecuteStatement(JsonNode request, String region) {+ requireValidReturnConsumedCapacity(request);String statement = request.path("Statement").asText();List<JsonNode> parameters = toPartiQLParams(request.path("Parameters"));DynamoDbPartiQLParser.Stmt stmt = DynamoDbPartiQLParser.parse(statement, parameters);@@ -2722,8 +2729,14 @@ public class DynamoDbJsonHandler {.nextToken(request.has("NextToken") ? request.get("NextToken").asText() : null).consistentRead(request.path("ConsistentRead").asBoolean(false)).tokenBinding(partiQLHandler.tokenBinding(statement, parameters));- JsonNode result = partiQLHandler.execute(stmt, ctx, region);- return Response.ok(result).build();+ DynamoDbPartiQLHandler.Result result = partiQLHandler.execute(stmt, ctx, region);+ ObjectNode response = result.body();+ String returnCC = request.path("ReturnConsumedCapacity").asText("NONE");+ if (!"NONE".equals(returnCC)) {+ response.set("ConsumedCapacity",+ writeCapacityNode(stmt.table(), result.capacity(), "INDEXES".equals(returnCC)));+ }+ return Response.ok(response).build();}private Response handleExecuteTransaction(JsonNode request, String region) {@@ -2853,20 +2866,24 @@ public class DynamoDbJsonHandler {}private Response handleBatchExecuteStatement(JsonNode request, String region) {+ requireValidReturnConsumedCapacity(request);JsonNode stmts = request.path("Statements");if (stmts.isMissingNode() || !stmts.isArray() || stmts.isEmpty()) {throw new AwsException("ValidationException", "Statements must not be empty", 400);}ArrayNode responses = objectMapper.createArrayNode();+ Map<String, DynamoDbWriteCapacity.Cost> capacity = new LinkedHashMap<>();for (JsonNode s : stmts) {- responses.add(batchMemberResponse(s, region));+ responses.add(batchMemberResponse(s, region, capacity));}ObjectNode resp = objectMapper.createObjectNode();resp.set("Responses", responses);+ addPerTableConsumedCapacity(resp, request, capacity, null);return Response.ok(resp).build();}- private ObjectNode batchMemberResponse(JsonNode statement, String region) {+ private ObjectNode batchMemberResponse(JsonNode statement, String region,+ Map<String, DynamoDbWriteCapacity.Cost> capacity) {ObjectNode slot = objectMapper.createObjectNode();String tableName = null;try {@@ -2875,13 +2892,14 @@ public class DynamoDbJsonHandler {if (stmt instanceof DynamoDbPartiQLParser.Stmt.Select select) {requireBatchSelectReadsByKey(select, region);}- JsonNode result = partiQLHandler.execute(stmt, PartiQLExecuteContext.builder()+ DynamoDbPartiQLHandler.Result result = partiQLHandler.execute(stmt, PartiQLExecuteContext.builder().consistentRead(statement.path("ConsistentRead").asBoolean(false)), region);- JsonNode firstItem = result.path("Items").path(0);+ JsonNode firstItem = result.body().path("Items").path(0);if (!firstItem.isMissingNode()) {slot.set("Item", firstItem);}slot.put("TableName", tableName);+ capacity.merge(tableName, result.capacity(), DynamoDbWriteCapacity.Cost::plus);} catch (AwsException e) {ObjectNode err = objectMapper.createObjectNode();err.put("Code", batchMemberErrorCode(e.getErrorCode()));diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbPartiQLHandler.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbPartiQLHandler.javaindex 916ec81f4a..b632edbcbb 100644--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbPartiQLHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbPartiQLHandler.java@@ -29,7 +29,9 @@ class DynamoDbPartiQLHandler {this.mapper = mapper;}- JsonNode execute(Stmt stmt, PartiQLExecuteContext ctx, String region) {+ record Result(ObjectNode body, DynamoDbWriteCapacity.Cost capacity) {}++ Result execute(Stmt stmt, PartiQLExecuteContext ctx, String region) {return switch (stmt) {case Stmt.Select s -> executeSelect(s, ctx, region);case Stmt.Insert s -> executeInsert(s, region);@@ -42,7 +44,7 @@ class DynamoDbPartiQLHandler {// --- SELECT ---- private JsonNode executeSelect(Stmt.Select stmt, PartiQLExecuteContext ctx, String region) {+ private Result executeSelect(Stmt.Select stmt, PartiQLExecuteContext ctx, String region) {TableDefinition table = service.describeTable(stmt.table(), region);// ExecuteStatement omits the index name from the missing-index message,// unlike Query/Scan (characterised on real AWS, eu-west-1, 2026-09-02).@@ -118,7 +120,40 @@ class DynamoDbPartiQLHandler {if (lastEvaluatedKey != null) {resp.put("NextToken", encodeNextToken(lastEvaluatedKey, ctx.tokenBinding()));}- return resp;+ return new Result(resp, readCapacity(stmt, table, accessPath, page, ctx.consistentRead()));+ }++ private static DynamoDbWriteCapacity.Cost readCapacity(Stmt.Select stmt, TableDefinition table,+ DynamoDbAccessPath accessPath, Page page,+ boolean consistentRead) {+ double units = DynamoDbJsonHandler.readCapacityUnits(page.scannedBytes(), consistentRead);+ if (!accessPath.isIndex()) {+ return new DynamoDbWriteCapacity.Cost(units, Map.of(), Map.of());+ }+ double tableUnits = 0;+ if (fetchesFromTable(stmt, table, accessPath)) {+ for (JsonNode item : page.scannedItems()) {+ tableUnits += DynamoDbJsonHandler.readCapacityUnits(+ DynamoDbItemSize.calculateItemSize(item), consistentRead);+ }+ }+ Map<String, Double> indexUnits = Map.of(accessPath.indexName(), units);+ return accessPath.isGlobalSecondaryIndex()+ ? new DynamoDbWriteCapacity.Cost(tableUnits, indexUnits, Map.of())+ : new DynamoDbWriteCapacity.Cost(tableUnits, Map.of(), indexUnits);+ }++ // An LSI read that selects an attribute the index does not project fetches every row it+ // walks from the base table, and each fetch is charged on its own.+ private static boolean fetchesFromTable(Stmt.Select stmt, TableDefinition table,+ DynamoDbAccessPath accessPath) {+ if (accessPath.isGlobalSecondaryIndex() || "ALL".equals(accessPath.projectionType())) {+ return false;+ }+ Set<String> projected = accessPath.projectedAttributeNames(table);+ return stmt.columns().stream()+ .map(Path::root)+ .anyMatch(column -> !projected.contains(column));}private record Routing(Cond.Eq pkEq, Cond skCond, List<Cond> filterConds, PVal partition) {}@@ -146,7 +181,8 @@ class DynamoDbPartiQLHandler {return new Routing(pkEq, skCond, filterConds, null);}- private record Page(List<JsonNode> items, JsonNode lastEvaluatedKey) {}+ private record Page(List<JsonNode> items, JsonNode lastEvaluatedKey, long scannedBytes,+ List<JsonNode> scannedItems) {}private Page readPage(Stmt.Select stmt, TableDefinition table, DynamoDbAccessPath accessPath,Routing routing, Supplier<JsonNode> startKey, Integer limit, String region) {@@ -177,14 +213,17 @@ class DynamoDbPartiQLHandler {ean.isEmpty() ? null : ean.toNode(mapper),eav.isEmpty() ? null : eav.toNode(mapper),null, limit, exclusiveStartKey, accessPath.indexName(), region);- return new Page(result.items(), result.lastEvaluatedKey());+ return new Page(result.items(), result.lastEvaluatedKey(), result.scannedBytes(), result.scannedItems());}if (accessPath.kind() == DynamoDbAccessPath.Kind.TABLE && skName == null&& skCond == null && filterConds.isEmpty()) {ObjectNode key = mapper.createObjectNode();key.set(pkName, toTypedNode(pkEq.val()));JsonNode item = service.getItem(stmt.table(), key, region);- return new Page(item != null ? List.of(item) : Collections.emptyList(), null);+ if (item == null) {+ return new Page(Collections.emptyList(), null, 0, List.of());+ }+ return new Page(List.of(item), null, DynamoDbItemSize.calculateItemSize(item), List.of(item));}ExprAttrBuilder eav = new ExprAttrBuilder();ExprAttrNameBuilder ean = new ExprAttrNameBuilder();@@ -196,7 +235,7 @@ class DynamoDbPartiQLHandler {stmt.table(), null, eav.toNode(mapper), kce, fe,limit, null, accessPath.indexName(), exclusiveStartKey,ean.isEmpty() ? null : ean.toNode(mapper), region);- return new Page(result.items(), result.lastEvaluatedKey());+ return new Page(result.items(), result.lastEvaluatedKey(), result.scannedBytes(), result.scannedItems());}private Page readPartition(Stmt.Select stmt, TableDefinition table, DynamoDbAccessPath accessPath,@@ -216,18 +255,22 @@ class DynamoDbPartiQLHandler {List<JsonNode> matching = result.items().stream().filter(item -> ExpressionEvaluator.evaluate(filter, item, names, values)).toList();- return new Page(matching, result.lastEvaluatedKey());+ return new Page(matching, result.lastEvaluatedKey(), result.scannedBytes(), result.items());}private Page readOrdered(Stmt.Select stmt, TableDefinition table, DynamoDbAccessPath accessPath,Routing routing, JsonNode after, Integer limit, String region) {requireOrderByShape(stmt, accessPath);List<JsonNode> rows = new ArrayList<>();+ long scannedBytes = 0;+ List<JsonNode> scannedItems = new ArrayList<>();JsonNode lastKey = null;do {JsonNode from = lastKey;Page page = readPage(stmt, table, accessPath, routing, () -> from, null, region);rows.addAll(page.items());+ scannedBytes += page.scannedBytes();+ scannedItems.addAll(page.scannedItems());lastKey = page.lastEvaluatedKey();} while (lastKey != null);@@ -241,7 +284,7 @@ class DynamoDbPartiQLHandler {}int end = limit == null ? rows.size() : Math.min(rows.size(), start + limit);JsonNode resumeAfter = start < end && end < rows.size() ? orderingKey(rows.get(end - 1), accessPath, table) : null;- return new Page(new ArrayList<>(rows.subList(start, end)), resumeAfter);+ return new Page(new ArrayList<>(rows.subList(start, end)), resumeAfter, scannedBytes, scannedItems);}private static void requireOrderByShape(Stmt.Select stmt, DynamoDbAccessPath accessPath) {@@ -473,24 +516,26 @@ class DynamoDbPartiQLHandler {// --- INSERT ---- private JsonNode executeInsert(Stmt.Insert stmt, String region) {+ private Result executeInsert(Stmt.Insert stmt, String region) {TableDefinition table = service.describeTable(stmt.table(), region);String pkName = table.getPartitionKeyName();ObjectNode item = mapper.createObjectNode();stmt.item().forEach((k, v) -> item.set(k, toTypedNode(v)));+ JsonNode previousItem;try {- service.putItem(stmt.table(), item, "attribute_not_exists(" + pkName + ")", null, null, region, "NONE");+ previousItem = service.putItem(stmt.table(), item, "attribute_not_exists(" + pkName + ")",+ null, null, region, "NONE");} catch (ConditionalCheckFailedException e) {throw new AwsException("DuplicateItemException", "Duplicate primary key exists in table", 400);}- return itemsResponse(null);+ return new Result(itemsResponse(null), writeCapacity(table, previousItem, item));}// --- UPDATE ---- private JsonNode executeUpdate(Stmt.Update stmt, String region) {+ private Result executeUpdate(Stmt.Update stmt, String region) {requireNoIndexQualifier(stmt.index());TableDefinition table = service.describeTable(stmt.table(), region);requireOneValuePerKey(table, stmt.where());@@ -506,7 +551,14 @@ class DynamoDbPartiQLHandler {ean.isEmpty() ? null : ean.toNode(mapper),eav.isEmpty() ? null : eav.toNode(mapper), returnValues, ce, region, "NONE",UpdateSizeRule.FINISHED_ITEM);- return itemsResponse(returnedAttributes(stmt.returning(), result));+ return new Result(itemsResponse(returnedAttributes(stmt.returning(), result)),+ writeCapacity(table, result.oldItem(), result.newItem()));+ }++ private static DynamoDbWriteCapacity.Cost writeCapacity(TableDefinition table, JsonNode oldItem,+ JsonNode newItem) {+ return DynamoDbWriteCapacity.forWrite(table, oldItem,+ newItem != null ? DynamoDbNumberUtils.normalizeNumbersInItem(newItem) : null);}private static void requireNoIndexQualifier(String index) {@@ -538,7 +590,7 @@ class DynamoDbPartiQLHandler {// --- DELETE ---- private JsonNode executeDelete(Stmt.Delete stmt, String region) {+ private Result executeDelete(Stmt.Delete stmt, String region) {requireNoIndexQualifier(stmt.index());TableDefinition table = service.describeTable(stmt.table(), region);requireOneValuePerKey(table, stmt.where());@@ -551,7 +603,8 @@ class DynamoDbPartiQLHandler {JsonNode oldItem = service.deleteItem(stmt.table(), key, ce,ean.isEmpty() ? null : ean.toNode(mapper),eav.isEmpty() ? null : eav.toNode(mapper), region, "NONE");- return itemsResponse(stmt.returning() == Returning.ALL_OLD ? oldItem : null);+ return new Result(itemsResponse(stmt.returning() == Returning.ALL_OLD ? oldItem : null),+ writeCapacity(table, oldItem, null));}// --- Transaction item builder ---diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.javaindex a8693b8c9f..4806df5a86 100644--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java@@ -1035,7 +1035,7 @@ public class DynamoDbService implements ResourceProvider {List<String> sortKeyNames = accessPath.sortKeyNames();var items = itemsByTable.get(scopedItemsKey(storageKey));- if (items == null) return new QueryResult(List.of(), 0, 0, null);+ if (items == null) return new QueryResult(List.of(), 0, 0, null, List.of());List<JsonNode> results = new ArrayList<>();@@ -1154,6 +1154,7 @@ public class DynamoDbService implements ResourceProvider {}int scannedCount = evaluatedItems.size();+ List<JsonNode> scannedItems = evaluatedItems;if (filterExpression != null) {evaluatedItems = evaluatedItems.stream()@@ -1164,7 +1165,7 @@ public class DynamoDbService implements ResourceProvider {LOG.tracev("Query on {0}: returned={1} scanned={2}",canonicalTableName, evaluatedItems.size(), scannedCount);- return new QueryResult(evaluatedItems, scannedCount, accSize, lastEvaluatedKey);+ return new QueryResult(evaluatedItems, scannedCount, accSize, lastEvaluatedKey, scannedItems);}public ScanResult scan(String tableName, String filterExpression,@@ -1194,7 +1195,7 @@ public class DynamoDbService implements ResourceProvider {DynamoDbAccessPath accessPath = DynamoDbAccessPath.resolve(table, indexName);var items = itemsByTable.get(scopedItemsKey(storageKey));- if (items == null) return new ScanResult(List.of(), 0, 0, null);+ if (items == null) return new ScanResult(List.of(), 0, 0, null, List.of());// ConcurrentSkipListMap keeps items sorted by base item key — no sort needed.// Use tailMap for O(log n) pagination instead of O(n) linear search.@@ -1220,6 +1221,7 @@ public class DynamoDbService implements ResourceProvider {int totalScanned = 0;int accSize = 0;List<JsonNode> results = new ArrayList<>();+ List<JsonNode> scannedItems = new ArrayList<>();JsonNode lastEvaluatedKey = null;JsonNode lastScanned = null;for (JsonNode item : source) {@@ -1251,6 +1253,7 @@ public class DynamoDbService implements ResourceProvider {}accSize += sz;totalScanned++;+ scannedItems.add(item);lastScanned = item;if (!isExpired(item, table)) {boolean matched = (filterExpression == null@@ -1271,7 +1274,7 @@ public class DynamoDbService implements ResourceProvider {LOG.tracev("Scan on {0}: returned={1} scanned={2}",canonicalTableName, results.size(), totalScanned);- return new ScanResult(results, totalScanned, accSize, lastEvaluatedKey);+ return new ScanResult(results, totalScanned, accSize, lastEvaluatedKey, scannedItems);}// A read served by a KEYS_ONLY or INCLUDE index is sized on the projection the@@ -3907,8 +3910,10 @@ public class DynamoDbService implements ResourceProvider {// scannedBytes carries the pre-filter size of the read items: DynamoDB bills a// Query or Scan on what it read, not on what survived the filter or projection.- public record ScanResult(List<JsonNode> items, int scannedCount, long scannedBytes, JsonNode lastEvaluatedKey) {}- public record QueryResult(List<JsonNode> items, int scannedCount, long scannedBytes, JsonNode lastEvaluatedKey) {}+ public record ScanResult(List<JsonNode> items, int scannedCount, long scannedBytes, JsonNode lastEvaluatedKey,+ List<JsonNode> scannedItems) {}+ public record QueryResult(List<JsonNode> items, int scannedCount, long scannedBytes, JsonNode lastEvaluatedKey,+ List<JsonNode> scannedItems) {}// --- Export Operations ---diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbPartiQLConsumedCapacityIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbPartiQLConsumedCapacityIntegrationTest.javanew file mode 100644index 0000000000..5da4fe343a--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbPartiQLConsumedCapacityIntegrationTest.java@@ -0,0 +1,290 @@+package io.github.hectorvent.floci.services.dynamodb;++import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.RestAssured;+import io.restassured.response.ValidatableResponse;+import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.*;++@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class DynamoDbPartiQLConsumedCapacityIntegrationTest {++ private static final String CT = "application/x-amz-json-1.0";+ private static final String TABLE = "PartiQLCapacityTable";+ private static int testPort;++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ @Order(1)+ void createTable() {+ testPort = RestAssured.port;+ send("CreateTable", """+ {+ "TableName": "%s",+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],+ "AttributeDefinitions": [+ {"AttributeName": "pk", "AttributeType": "S"},+ {"AttributeName": "gsiPk", "AttributeType": "S"},+ {"AttributeName": "gsi2Pk", "AttributeType": "S"}+ ],+ "GlobalSecondaryIndexes": [{+ "IndexName": "gsi1",+ "KeySchema": [{"AttributeName": "gsiPk", "KeyType": "HASH"}],+ "Projection": {"ProjectionType": "ALL"}+ }, {+ "IndexName": "gsi2",+ "KeySchema": [{"AttributeName": "gsi2Pk", "KeyType": "HASH"}],+ "Projection": {"ProjectionType": "KEYS_ONLY"}+ }],+ "BillingMode": "PAY_PER_REQUEST"+ }+ """.formatted(TABLE));+ }++ @Test+ @Order(2)+ void executeStatementReadsAreChargedLikeGetItemWithNoSplit() {+ send("PutItem", """+ {"TableName": "%s", "Item": {"pk": {"S": "cc-pq"}, "data": {"S": "x"}}}+ """.formatted(TABLE));+ send("ExecuteStatement", """+ {"Statement": "SELECT * FROM \\"%s\\" WHERE pk = 'cc-pq'", "ReturnConsumedCapacity": "TOTAL"}+ """.formatted(TABLE))+ .body("ConsumedCapacity.TableName", equalTo(TABLE))+ .body("ConsumedCapacity.CapacityUnits", equalTo(0.5f))+ .body("ConsumedCapacity.ReadCapacityUnits", nullValue())+ .body("ConsumedCapacity.Table", nullValue());+ send("ExecuteStatement", """+ {+ "Statement": "SELECT * FROM \\"%s\\" WHERE pk = 'cc-pq-missing'",+ "ConsistentRead": true,+ "ReturnConsumedCapacity": "INDEXES"+ }+ """.formatted(TABLE))+ .body("ConsumedCapacity.CapacityUnits", equalTo(1.0f))+ .body("ConsumedCapacity.Table.CapacityUnits", equalTo(1.0f));+ }++ @Test+ @Order(3)+ void executeStatementOnAGsiChargesOnlyTheIndex() {+ send("PutItem", """+ {"TableName": "%s", "Item": {"pk": {"S": "cc-pq-gsi"}, "gsiPk": {"S": "q1"}}}+ """.formatted(TABLE));+ send("ExecuteStatement", """+ {+ "Statement": "SELECT pk FROM \\"%s\\".\\"gsi1\\" WHERE gsiPk = 'q1'",+ "ReturnConsumedCapacity": "INDEXES"+ }+ """.formatted(TABLE))+ .body("ConsumedCapacity.CapacityUnits", equalTo(0.5f))+ .body("ConsumedCapacity.Table.CapacityUnits", equalTo(0.0f))+ .body("ConsumedCapacity.GlobalSecondaryIndexes.gsi1.CapacityUnits", equalTo(0.5f));+ }++ @Test+ @Order(4)+ void executeStatementWritesAreChargedLikeSingleItemWrites() {+ send("ExecuteStatement", """+ {+ "Statement": "INSERT INTO \\"%s\\" VALUE {'pk': 'cc-pq-ins', 'gsiPk': 'i1', 'gsi2Pk': 'i2'}",+ "ReturnConsumedCapacity": "INDEXES"+ }+ """.formatted(TABLE))+ .body("ConsumedCapacity.CapacityUnits", equalTo(3.0f))+ .body("ConsumedCapacity.WriteCapacityUnits", nullValue())+ .body("ConsumedCapacity.Table.CapacityUnits", equalTo(1.0f))+ .body("ConsumedCapacity.GlobalSecondaryIndexes.gsi1.CapacityUnits", equalTo(1.0f))+ .body("ConsumedCapacity.GlobalSecondaryIndexes.gsi2.CapacityUnits", equalTo(1.0f));+ send("ExecuteStatement", """+ {"Statement": "DELETE FROM \\"%s\\" WHERE pk = 'cc-pq-absent'", "ReturnConsumedCapacity": "TOTAL"}+ """.formatted(TABLE))+ .body("ConsumedCapacity.CapacityUnits", equalTo(1.0f));+ }++ @Test+ @Order(5)+ void executeStatementOnAKeysOnlyLsiChargesEachBaseTableFetch() {+ send("CreateTable", """+ {+ "TableName": "PartiQLCapacityLsiTable",+ "KeySchema": [+ {"AttributeName": "pk", "KeyType": "HASH"},+ {"AttributeName": "sk", "KeyType": "RANGE"}+ ],+ "AttributeDefinitions": [+ {"AttributeName": "pk", "AttributeType": "S"},+ {"AttributeName": "sk", "AttributeType": "S"},+ {"AttributeName": "lsiSk", "AttributeType": "S"}+ ],+ "LocalSecondaryIndexes": [{+ "IndexName": "lsi-keys",+ "KeySchema": [+ {"AttributeName": "pk", "KeyType": "HASH"},+ {"AttributeName": "lsiSk", "KeyType": "RANGE"}+ ],+ "Projection": {"ProjectionType": "KEYS_ONLY"}+ }],+ "BillingMode": "PAY_PER_REQUEST"+ }+ """);+ for (int i = 1; i <= 3; i++) {+ send("PutItem", """+ {+ "TableName": "PartiQLCapacityLsiTable",+ "Item": {"pk": {"S": "p"}, "sk": {"S": "%1$d"}, "lsiSk": {"S": "l%1$d"}, "nonproj": {"S": "n"}}+ }+ """.formatted(i));+ }+ String fetch = """+ {+ "Statement": "SELECT nonproj FROM \\"PartiQLCapacityLsiTable\\".\\"lsi-keys\\" WHERE pk = 'p'",+ "ReturnConsumedCapacity": "INDEXES"%s+ }+ """;+ send("ExecuteStatement", fetch.formatted(""))+ .body("ConsumedCapacity.CapacityUnits", equalTo(2.0f))+ .body("ConsumedCapacity.Table.CapacityUnits", equalTo(1.5f))+ .body("ConsumedCapacity.LocalSecondaryIndexes.'lsi-keys'.CapacityUnits", equalTo(0.5f));+ send("ExecuteStatement", fetch.formatted(", \"Limit\": 1"))+ .body("ConsumedCapacity.Table.CapacityUnits", equalTo(0.5f));+ send("ExecuteStatement", """+ {+ "Statement": "SELECT lsiSk FROM \\"PartiQLCapacityLsiTable\\".\\"lsi-keys\\" WHERE pk = 'p'",+ "ReturnConsumedCapacity": "INDEXES"+ }+ """)+ .body("ConsumedCapacity.CapacityUnits", equalTo(0.5f))+ .body("ConsumedCapacity.Table.CapacityUnits", equalTo(0.0f));+ send("ExecuteStatement", """+ {+ "Statement": "SELECT nonproj FROM \\"PartiQLCapacityLsiTable\\".\\"lsi-keys\\"",+ "ReturnConsumedCapacity": "INDEXES"+ }+ """)+ .body("ConsumedCapacity.Table.CapacityUnits", equalTo(1.5f))+ .body("ConsumedCapacity.LocalSecondaryIndexes.'lsi-keys'.CapacityUnits", equalTo(0.5f));+ send("ExecuteStatement", """+ {+ "Statement": "SELECT lsiSk FROM \\"PartiQLCapacityLsiTable\\".\\"lsi-keys\\"",+ "ReturnConsumedCapacity": "INDEXES"+ }+ """)+ .body("ConsumedCapacity.Table.CapacityUnits", equalTo(0.0f));+ send("DeleteTable", """+ {"TableName": "PartiQLCapacityLsiTable"}+ """);+ }++ @Test+ @Order(6)+ void batchExecuteStatementChargesOnlyTheMembersThatSucceed() {+ send("BatchExecuteStatement", """+ {+ "Statements": [+ {"Statement": "SELECT * FROM \\"%1$s\\" WHERE pk = 'cc-pq'", "ConsistentRead": true},+ {"Statement": "SELECT * FROM \\"%1$s\\" WHERE pk = 'cc-pq-missing'"},+ {"Statement": "SELECT * FROM \\"%1$s\\" WHERE data = 'x'"}+ ],+ "ReturnConsumedCapacity": "INDEXES"+ }+ """.formatted(TABLE))+ .body("Responses[2].Error.Code", equalTo("ValidationError"))+ .body("ConsumedCapacity", hasSize(1))+ .body("ConsumedCapacity[0].TableName", equalTo(TABLE))+ .body("ConsumedCapacity[0].CapacityUnits", equalTo(1.5f))+ .body("ConsumedCapacity[0].ReadCapacityUnits", nullValue())+ .body("ConsumedCapacity[0].Table.CapacityUnits", equalTo(1.5f));+ send("BatchExecuteStatement", """+ {+ "Statements": [{"Statement": "INSERT INTO \\"%s\\" VALUE {'pk': 'cc-pq'}"}],+ "ReturnConsumedCapacity": "TOTAL"+ }+ """.formatted(TABLE))+ .body("Responses[0].Error.Code", equalTo("DuplicateItem"))+ .body("ConsumedCapacity", nullValue());+ }++ @Test+ @Order(7)+ void statementsRejectAnInvalidReturnConsumedCapacityBeforeRunning() {+ String invalid = "1 validation error detected: Value 'INVALID' at 'returnConsumedCapacity' failed to "+ + "satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]";+ rejected("ExecuteStatement", """+ {+ "Statement": "INSERT INTO \\"%s\\" VALUE {'pk': 'cc-pq-rcc'}",+ "ReturnConsumedCapacity": "INVALID"+ }+ """.formatted(TABLE))+ .body("message", equalTo(invalid));+ rejected("BatchExecuteStatement", """+ {+ "Statements": [{"Statement": "INSERT INTO \\"%s\\" VALUE {'pk': 'cc-pq-rcc-batch'}"}],+ "ReturnConsumedCapacity": "INVALID"+ }+ """.formatted(TABLE))+ .body("message", equalTo(invalid));++ send("BatchExecuteStatement", """+ {+ "Statements": [+ {"Statement": "SELECT * FROM \\"%1$s\\" WHERE pk = 'cc-pq-rcc'"},+ {"Statement": "SELECT * FROM \\"%1$s\\" WHERE pk = 'cc-pq-rcc-batch'"}+ ]+ }+ """.formatted(TABLE))+ .body("Responses[0].Item", nullValue())+ .body("Responses[1].Item", nullValue());+ }++ private static ValidatableResponse rejected(String operation, String body) {+ return given()+ .header("X-Amz-Target", "DynamoDB_20120810." + operation)+ .contentType(CT)+ .body(body)+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"));+ }++ private static ValidatableResponse send(String operation, String body) {+ return given()+ .header("X-Amz-Target", "DynamoDB_20120810." + operation)+ .contentType(CT)+ .body(body)+ .when()+ .post("/")+ .then()+ .statusCode(200);+ }++ @AfterAll+ static void cleanup() {+ given()+ .port(testPort)+ .header("X-Amz-Target", "DynamoDB_20120810.DeleteTable")+ .contentType(CT)+ .body("""+ {"TableName": "%s"}+ """.formatted(TABLE))+ .when()+ .post("/")+ .then()+ .statusCode(200);+ }+}