feat(dynamodb): improve PartiQL grammar coverage (#3798)

* feat(dynamodb): improve PartiQL grammar coverage

An attribute reference is now a path, so a.b and a[0] work in SELECT columns,
WHERE conditions and UPDATE SET and REMOVE targets. SELECT reports a path from
its last named component on, so SELECT a.b[0] answers b[0].

Values take map, list and set literals, exponent numbers and a doubled single
quote. An empty set, a mixed set and a set with a repeated member are refused
in the AWS words.

WHERE takes OR, NOT, parentheses, IN with a list literal, IS MISSING and IS
NULL with their negations, and the contains, attribute_type and size
functions. Each becomes the matching filter or condition expression, so the
existing evaluator does the work.

UPDATE SET takes a sum or difference, list_append, set_add and set_delete. A
predicate beside the key equality becomes a condition on the write, so a false
one answers ConditionalCheckFailedException and leaves the item. UPDATE is not
an upsert and needs the key to hold an item already, while a DELETE on a key
holding no item stays a no-op. A clause omitting a key attribute says so.

RETURNING runs all four variants on UPDATE and ALL OLD * on DELETE. It answers
one row on Items, and no row when the projection is empty. DELETE refuses the
other three and ExecuteTransaction refuses the clause outright.

SELECT takes ORDER BY on the key, pages the sorted rows, and refuses the shapes
AWS refuses. A FROM path takes at most two components and no empty one. INSERT
refuses an index qualifier as a parse error, UPDATE and DELETE refuse the
operation on an index, and a keyed read filtering on an attribute the index
does not project is refused.

ExecuteTransaction runs a transaction of nothing but SELECT as a read, runs
EXISTS as a condition check, refuses a mix of reads and writes, and no longer
applies twice on a replayed ClientRequestToken. A BatchExecuteStatement member
carries the short error code and echoes TableName when it reached its table.

Two update engine bugs came out of this and are fixed for UpdateItem as well.
list_append on a nested path wrote a new top-level attribute, and ADD or DELETE
with an operand of another type replaced or ignored the stored value.

* fix(dynamodb): read key equalities inside a grouped AND in PartiQL

* fix(dynamodb): subtract without spaces and refuse trailing tokens in PartiQL

* fix(dynamodb): refuse a negative list index in PartiQL

* fix(dynamodb): refuse a non-string type in PartiQL attribute_type

* fix(dynamodb): refuse a value that is not a set in PartiQL set_add and set_delete

* fix(dynamodb): refuse duplicate members in a PartiQL bag

* fix(dynamodb): check PartiQL parameters before reading the statement

* fix(dynamodb): refuse two PartiQL reads of one item in a transaction

* fix(dynamodb): read only by the key in a PartiQL transaction SELECT

* fix(dynamodb): check unprojected attributes inside grouped PartiQL conditions

* fix(dynamodb): refuse an ADD or DELETE operand type before reading the item

* fix(dynamodb): skip line and block comments in PartiQL

* fix(dynamodb): apply a sign to a PartiQL number literal

* fix(dynamodb): refuse a parameter inside a PartiQL collection literal

* test(dynamodb): read a parameter in IN on a non-key attribute

* fix(dynamodb): refuse a PartiQL list index above the integer range

* fix(dynamodb): refuse a PartiQL literal nested 32 levels deep

* fix(dynamodb): refuse a non-number literal in PartiQL arithmetic

* feat(dynamodb): read attribute_exists and attribute_not_exists in PartiQL

* feat(dynamodb): compare a PartiQL condition with a boolean

* fix(dynamodb): match nothing when ordering a value against another type

* fix(dynamodb): read PartiQL key conditions spread over OR and IN like AWS

* fix(dynamodb): read a PartiQL transaction or batch SELECT only by its key

* fix(dynamodb): refuse two values for one key on a PartiQL write

* fix(dynamodb): cancel a PartiQL transaction that names a missing table

* fix(dynamodb): cancel a PartiQL transaction whose statement does not name one item

* fix(dynamodb): refuse a write that leaves an item nested too deep

* fix(dynamodb): refuse a PartiQL parameter only past the nesting limit AWS uses

* chore(dynamodb): drop comments that restate the code or a test

* perf(dynamodb): work out each PartiQL key branch once and cap how far it spreads

* chore(dynamodb): share one first key value helper across PartiQL key checks

* chore(dynamodb): throw the ADD or DELETE operand error and merge member loops

* chore(dynamodb): track PartiQL literal depth in one place and share truth helpers

* test(dynamodb): name the quoted table once and add statement and putItem overloads

* fix(dynamodb): cap IN operands and decomposed reads in PartiQL
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-09-18 21:04:16 -05:00
1 parent 0142d443ac
commit 82a3c1dbac
16 files changed
+3700 -285

No files matched your search

@@ -306,7 +306,7 @@ final class DynamoDbAccessPathValidator {
validateCompositeSortKeyConditions(sortKeys, sortKeyEqualities);
}
private static String attributeType(TableDefinition table, String attribute) {
static String attributeType(TableDefinition table, String attribute) {
List<AttributeDefinition> definitions = table.getAttributeDefinitions();
if (definitions == null) {
throw validationException(KEY_TYPE_MISMATCH);
@@ -53,13 +53,11 @@ final class DynamoDbAttributeValueValidator {
}
}
// PartiQL reports the limit with this short wording, and a transaction turns it into a
// cancellation reason.
static final String NESTING_EXCEEDED = "Nesting Levels have exceeded supported limits";
static void requireParameterNestingWithinLimit(JsonNode value) {
if (!valueNestingWithinLimit(value)) {
throw validationEx(NESTING_EXCEEDED);
if (depthOf(value) > MAX_NESTING_LEVELS + 1) {
throw validationEx(NESTING_EXCEEDED + ": Attributes in the item have nested levels beyond supported limit");
}
}
@@ -15,6 +15,7 @@ import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import java.util.*;
import java.util.function.Supplier;
/**
* DynamoDB JSON protocol handler.
@@ -676,6 +677,7 @@ public class DynamoDbJsonHandler {
checkUnusedEan(exprAttrNames, hashTokens);
Set<String> colonTokensAll = extractColonTokens(updateExpression, conditionExpression);
checkUnusedEav(exprAttrValues, colonTokensAll);
dynamoDbService.requireAddOrDeleteOperandTypes(updateExpression, exprAttrValues, true);
}
if (expectedUpd != null) {
@@ -1696,6 +1698,8 @@ public class DynamoDbJsonHandler {
op.get("ExpressionAttributeNames"),
op.get("ExpressionAttributeValues"));
DynamoDbAttributeValueValidator.requireNestingWithinLimit(op.get("Item"), false);
dynamoDbService.requireAddOrDeleteOperandTypes(op.path("UpdateExpression").textValue(),
op.get("ExpressionAttributeValues"), false);
}
}
@@ -2674,15 +2678,32 @@ public class DynamoDbJsonHandler {
if (stmts.isMissingNode() || !stmts.isArray() || stmts.isEmpty()) {
throw new AwsException("ValidationException", "TransactStatements must not be empty", 400);
}
List<JsonNode> transactItems = new ArrayList<>();
try {
cancelOnTooDeepParameters(stmts);
for (JsonNode s : stmts) {
DynamoDbPartiQLParser.Stmt stmt = DynamoDbPartiQLParser.parse(
s.path("Statement").asText(), toPartiQLParams(s.path("Parameters")));
transactItems.add(partiQLHandler.toTransactItem(stmt, region));
List<DynamoDbPartiQLParser.Stmt> statements = new ArrayList<>();
for (int i = 0; i < stmts.size(); i++) {
JsonNode s = stmts.get(i);
List<JsonNode> parameters = toPartiQLParams(s.path("Parameters"));
statements.add(inTransactStatement(i,
() -> DynamoDbPartiQLParser.parse(s.path("Statement").asText(), parameters)));
}
dynamoDbService.transactWriteItems(transactItems, region);
long reads = statements.stream().filter(DynamoDbPartiQLParser.Stmt.Select.class::isInstance).count();
if (reads > 0 && reads < statements.size()) {
throw new AwsException("ValidationException",
"ExecuteTransaction API does not support both read and write operations in the same request.", 400);
}
if (reads == statements.size()) {
return executeTransactionReads(statements.stream()
.map(DynamoDbPartiQLParser.Stmt.Select.class::cast)
.toList(), region);
}
List<DynamoDbPartiQLHandler.TransactMember> members = new ArrayList<>();
for (int i = 0; i < statements.size(); i++) {
DynamoDbPartiQLParser.Stmt stmt = statements.get(i);
members.add(inTransactStatement(i, () -> partiQLHandler.toTransactItem(stmt, region)));
}
List<JsonNode> transactItems = cancelOnMemberReasons(members);
dynamoDbService.transactWriteItems(transactItems, region,
request.path("ClientRequestToken").asText(null), request);
ObjectNode resp = objectMapper.createObjectNode();
resp.set("Responses", objectMapper.createArrayNode());
return Response.ok(resp).build();
@@ -2694,8 +2715,9 @@ public class DynamoDbJsonHandler {
for (TransactionCanceledException.CancellationReason reason : e.getCancellationReasons()) {
ObjectNode r = objectMapper.createObjectNode();
r.put("Code", reason.code().isEmpty() ? "None" : reason.code());
r.put("Message", reason.code().isEmpty() ? ""
: reason.message() != null ? reason.message() : "The conditional request failed");
if (!reason.code().isEmpty()) {
r.put("Message", reason.message() != null ? reason.message() : "The conditional request failed");
}
if (reason.item() != null) {
r.set("Item", reason.item());
}
@@ -2705,24 +2727,69 @@ public class DynamoDbJsonHandler {
}
}
// AWS cancels the transaction, with that statement's reason, when a parameter is too deep.
private void cancelOnTooDeepParameters(JsonNode stmts) {
var reasons = new ArrayList<TransactionCanceledException.CancellationReason>();
var cancelled = false;
for (JsonNode s : stmts) {
var tooDeep = false;
for (var parameter : s.path("Parameters")) {
tooDeep |= !DynamoDbAttributeValueValidator.valueNestingWithinLimit(parameter);
private Response executeTransactionReads(List<DynamoDbPartiQLParser.Stmt.Select> selects, String region) {
List<DynamoDbPartiQLHandler.TransactMember> members = new ArrayList<>();
for (int i = 0; i < selects.size(); i++) {
DynamoDbPartiQLParser.Stmt.Select select = selects.get(i);
members.add(inTransactStatement(i, () -> partiQLHandler.toTransactGetItem(select, region)));
}
List<JsonNode> getItems = cancelOnMemberReasons(members);
List<JsonNode> results = dynamoDbService.transactGetItems(getItems, region);
requireOneReadPerItem(getItems, region);
ArrayNode responses = objectMapper.createArrayNode();
for (int i = 0; i < results.size(); i++) {
JsonNode item = partiQLHandler.projectSelected(selects.get(i), results.get(i));
ObjectNode entry = objectMapper.createObjectNode();
if (item != null) {
entry.set("Item", item);
}
cancelled |= tooDeep;
reasons.add(tooDeep
? new TransactionCanceledException.CancellationReason("ValidationError", null,
DynamoDbAttributeValueValidator.NESTING_EXCEEDED)
: new TransactionCanceledException.CancellationReason("", null));
responses.add(entry);
}
ObjectNode resp = objectMapper.createObjectNode();
resp.set("Responses", responses);
return Response.ok(resp).build();
}
private static List<JsonNode> cancelOnMemberReasons(List<DynamoDbPartiQLHandler.TransactMember> members) {
List<JsonNode> items = new ArrayList<>();
List<TransactionCanceledException.CancellationReason> reasons = new ArrayList<>();
boolean cancelled = false;
for (DynamoDbPartiQLHandler.TransactMember member : members) {
cancelled |= member.reason() != null;
items.add(member.item());
reasons.add(member.reason() != null ? member.reason() : new TransactionCanceledException.CancellationReason("", null));
}
if (cancelled) {
throw new TransactionCanceledException(reasons);
}
return items;
}
private void requireOneReadPerItem(List<JsonNode> getItems, String region) {
Set<List<String>> items = new HashSet<>();
for (JsonNode getItem : getItems) {
JsonNode get = getItem.path("Get");
String tableName = get.path("TableName").asText();
TableDefinition table = dynamoDbService.findTable(tableName, region).orElseThrow();
String itemKey = dynamoDbService.buildItemKey(table, get.path("Key"), true);
if (!items.add(List.of(tableName, itemKey))) {
throw new AwsException("ValidationException",
"Transaction request cannot include multiple operations on one item", 400);
}
}
}
private <T> T inTransactStatement(int index, Supplier<T> member) {
try {
return member.get();
} catch (AwsException e) {
if (!"ValidationException".equals(e.getErrorCode())) {
throw e;
}
throw new AwsException("ValidationException",
"Validation failed in TransactStatements[" + index + "]: " + e.getMessage(), 400);
}
}
private Response handleBatchExecuteStatement(JsonNode request, String region) {
@@ -2732,60 +2799,79 @@ public class DynamoDbJsonHandler {
}
ArrayNode responses = objectMapper.createArrayNode();
for (JsonNode s : stmts) {
try {
DynamoDbPartiQLParser.Stmt stmt = DynamoDbPartiQLParser.parse(
s.path("Statement").asText(), toPartiQLParams(s.path("Parameters")));
if (stmt instanceof DynamoDbPartiQLParser.Stmt.Select select
&& !batchSelectResolvesThroughPrimaryKey(select, region)) {
throw new AwsException("ValidationError",
"Select statements within BatchExecuteStatement must specify the primary key "
+ "in the where clause.", 400);
}
JsonNode result = partiQLHandler.execute(stmt, PartiQLExecuteContext.builder()
.consistentRead(s.path("ConsistentRead").asBoolean(false)), region);
ObjectNode slot = objectMapper.createObjectNode();
JsonNode firstItem = result.path("Items").path(0);
if (!firstItem.isMissingNode()) {
slot.set("Item", firstItem);
}
responses.add(slot);
} catch (AwsException e) {
ObjectNode slot = objectMapper.createObjectNode();
ObjectNode err = objectMapper.createObjectNode();
err.put("Code", e.getErrorCode());
err.put("Message", e.getMessage());
slot.set("Error", err);
responses.add(slot);
}
responses.add(batchMemberResponse(s, region));
}
ObjectNode resp = objectMapper.createObjectNode();
resp.set("Responses", responses);
return Response.ok(resp).build();
}
private ObjectNode batchMemberResponse(JsonNode statement, String region) {
ObjectNode slot = objectMapper.createObjectNode();
String tableName = null;
try {
DynamoDbPartiQLParser.Stmt stmt = parsePartiQLStatement(statement);
tableName = stmt.table();
if (stmt instanceof DynamoDbPartiQLParser.Stmt.Select select) {
requireBatchSelectReadsByKey(select, region);
}
JsonNode result = partiQLHandler.execute(stmt, PartiQLExecuteContext.builder()
.consistentRead(statement.path("ConsistentRead").asBoolean(false)), region);
JsonNode firstItem = result.path("Items").path(0);
if (!firstItem.isMissingNode()) {
slot.set("Item", firstItem);
}
slot.put("TableName", tableName);
} catch (AwsException e) {
ObjectNode err = objectMapper.createObjectNode();
err.put("Code", batchMemberErrorCode(e.getErrorCode()));
err.put("Message", e.getMessage());
slot.set("Error", err);
if (tableName != null && batchMemberReachedItsTable(e)) {
slot.put("TableName", tableName);
}
}
return slot;
}
private static String batchMemberErrorCode(String errorCode) {
if ("ValidationException".equals(errorCode)) {
return "ValidationError";
}
return errorCode.endsWith("Exception")
? errorCode.substring(0, errorCode.length() - "Exception".length())
: errorCode;
}
private static boolean batchMemberReachedItsTable(AwsException e) {
return e instanceof ItemNestingExceededException
|| "ConditionalCheckFailedException".equals(e.getErrorCode())
|| "DuplicateItemException".equals(e.getErrorCode());
}
// BatchExecuteStatement only runs SELECT statements that resolve through
// the table's primary key: index-qualified statements and partial-key
// WHERE clauses are rejected per statement (characterised on real AWS,
// eu-west-1, 2026-09-02).
private boolean batchSelectResolvesThroughPrimaryKey(DynamoDbPartiQLParser.Stmt.Select select, String region) {
private void requireBatchSelectReadsByKey(DynamoDbPartiQLParser.Stmt.Select select, String region) {
if (select.index() != null) {
return false;
throw batchSelectNeedsKey();
}
TableDefinition table = dynamoDbService.describeTable(select.table(), region);
String pkName = table.getPartitionKeyName();
String skName = table.getSortKeyName();
boolean pkEq = false;
boolean skEq = skName == null;
for (DynamoDbPartiQLParser.Cond c : select.where()) {
if (c instanceof DynamoDbPartiQLParser.Cond.Eq eq) {
if (eq.attr().equals(pkName)) {
pkEq = true;
} else if (skName != null && eq.attr().equals(skName)) {
skEq = true;
}
}
DynamoDbPartiQLHandler.requireReadsWithinLimit(table, select.where());
if (!DynamoDbPartiQLHandler.namesOnlyTheKey(table, select.where())) {
throw batchSelectNeedsKey();
}
return pkEq && skEq;
}
private static AwsException batchSelectNeedsKey() {
return new AwsException("ValidationException",
"Select statements within BatchExecuteStatement must specify the primary key in the where clause.", 400);
}
private DynamoDbPartiQLParser.Stmt parsePartiQLStatement(JsonNode statement) {
return DynamoDbPartiQLParser.parse(statement.path("Statement").asText(),
toPartiQLParams(statement.path("Parameters")));
}
private List<JsonNode> toPartiQLParams(JsonNode node) {
@@ -2793,7 +2879,11 @@ public class DynamoDbJsonHandler {
return Collections.emptyList();
}
List<JsonNode> params = new ArrayList<>();
node.forEach(params::add);
for (JsonNode parameter : node) {
DynamoDbAttributeValueValidator.requireParameterNestingWithinLimit(parameter);
checkAttrSets(parameter);
params.add(parameter);
}
return params;
}
}
@@ -8,6 +8,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbPartiQLParser.*;
import io.github.hectorvent.floci.services.dynamodb.model.ConditionalCheckFailedException;
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
import java.nio.charset.StandardCharsets;
@@ -15,6 +16,8 @@ import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.Base64;
import java.util.function.Supplier;
import java.util.stream.Collectors;
class DynamoDbPartiQLHandler {
@@ -32,6 +35,8 @@ class DynamoDbPartiQLHandler {
case Stmt.Insert s -> executeInsert(s, region);
case Stmt.Update s -> executeUpdate(s, region);
case Stmt.Delete s -> executeDelete(s, region);
case Stmt.Exists ignored -> throw new AwsException("ValidationException",
"EXISTS can only be used in ExecuteTransaction write requests.", 400);
};
}
@@ -56,9 +61,11 @@ class DynamoDbPartiQLHandler {
// projects; the message preserves statement order (characterised on
// real AWS, eu-west-1, 2026-09-02). An LSI read reaches the co-located
// base item, so non-projected columns stay legal there.
if (accessPath.isGlobalSecondaryIndex() && !"ALL".equals(accessPath.projectionType())) {
if (accessPath.isGlobalSecondaryIndex() && !"ALL".equals(accessPath.projectionType())
&& !stmt.columns().isEmpty()) {
Set<String> projected = accessPath.projectedAttributeNames(table);
List<String> unprojected = stmt.columns().stream()
.map(Path::root)
.filter(c -> !"*".equals(c))
.filter(c -> !projected.contains(c))
.toList();
@@ -70,84 +77,27 @@ class DynamoDbPartiQLHandler {
}
}
String pkName = accessPath.partitionKeyName();
String skName = accessPath.sortKeyName();
DynamoDbPartiQLKeyPlan keys = new DynamoDbPartiQLKeyPlan(stmt.where(), accessPath, table);
keys.requireKeyTypesMatchSchema();
keys.requireNoOverlap();
keys.requireReadsWithinLimit();
requireFilterAttributesProjected(keys, accessPath, table);
Cond.Eq pkEq = null;
Cond skCond = null;
List<Cond> filterConds = new ArrayList<>();
for (Cond c : stmt.where()) {
String attr = condAttr(c);
if (pkName.equals(attr)) {
if (c instanceof Cond.Eq eq) {
pkEq = eq;
} else {
filterConds.add(c);
}
} else if (skName != null && skName.equals(attr)) {
skCond = c;
} else {
filterConds.add(c);
}
}
List<JsonNode> items;
JsonNode lastEvaluatedKey = null;
if (pkEq == null) {
// No equality on the selected source's partition key: AWS performs
// a full scan of the table or index and applies the remaining
// conditions as a filter (characterised on real AWS, eu-west-1,
// 2026-09-02).
ExprAttrBuilder eav = new ExprAttrBuilder();
ExprAttrNameBuilder ean = new ExprAttrNameBuilder();
List<Cond> scanFilters = new ArrayList<>(filterConds);
if (skCond != null) {
scanFilters.add(skCond);
}
String fe = buildFe(scanFilters, eav, ean);
JsonNode exclusiveStartKey = decodeNextToken(ctx.nextToken(), ctx.tokenBinding());
DynamoDbAccessPathValidator.validateExclusiveStartKey(exclusiveStartKey, table, accessPath, true);
DynamoDbService.ScanResult result = service.scan(stmt.table(), fe,
ean.isEmpty() ? null : ean.toNode(mapper),
eav.isEmpty() ? null : eav.toNode(mapper),
null, ctx.limit(), exclusiveStartKey, accessPath.indexName(), region);
items = result.items();
lastEvaluatedKey = result.lastEvaluatedKey();
} else 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);
items = item != null ? List.of(item) : Collections.emptyList();
} else {
ExprAttrBuilder eav = new ExprAttrBuilder();
ExprAttrNameBuilder ean = new ExprAttrNameBuilder();
String kce = buildKce(pkEq, skCond, pkName, skName, eav, ean);
String fe = buildFe(filterConds, eav, ean);
JsonNode exclusiveStartKey = decodeNextToken(ctx.nextToken(), ctx.tokenBinding());
DynamoDbAccessPathValidator.validateExclusiveStartKey(exclusiveStartKey, table, accessPath, false);
DynamoDbService.QueryResult result = service.query(
stmt.table(), null, eav.toNode(mapper), kce, fe,
ctx.limit(), null, accessPath.indexName(), exclusiveStartKey,
ean.isEmpty() ? null : ean.toNode(mapper), region);
items = result.items();
lastEvaluatedKey = result.lastEvaluatedKey();
}
Routing routing = routingOf(stmt.where(), keys, accessPath.partitionKeyName(), accessPath.sortKeyName());
Supplier<JsonNode> startKey = () -> decodeNextToken(ctx.nextToken(), ctx.tokenBinding());
Page page = stmt.orderBy().isEmpty()
? readPage(stmt, table, accessPath, routing, startKey, ctx.limit(), region)
: readOrdered(stmt, table, accessPath, routing, startKey.get(), ctx.limit(), region);
List<JsonNode> items = page.items();
JsonNode lastEvaluatedKey = page.lastEvaluatedKey();
// Apply column projection for non-* SELECT. Projects against the full
// item: an LSI read can reach attributes outside the index projection
// (characterised on real AWS, eu-west-1, 2026-09-02).
if (!stmt.columns().isEmpty()) {
ExprAttrNameBuilder projEan = new ExprAttrNameBuilder();
String proj = stmt.columns().stream()
.map(projEan::alias)
.reduce((a, b) -> a + "," + b)
.orElse("");
ObjectNode eanNode = projEan.isEmpty() ? null : projEan.toNode(mapper);
List<SelectedColumn> columns = selectedColumns(stmt);
items = items.stream()
.map(item -> (JsonNode) ProjectionEvaluator.project(item, proj, eanNode))
.map(item -> (JsonNode) selectColumns(item, columns))
.toList();
}
@@ -171,6 +121,203 @@ class DynamoDbPartiQLHandler {
return resp;
}
private record Routing(Cond.Eq pkEq, Cond skCond, List<Cond> filterConds, PVal partition) {}
private static Routing routingOf(List<Cond> where, DynamoDbPartiQLKeyPlan keys, String pkName, String skName) {
Optional<PVal> partition = keys.singlePartition();
if (partition.isEmpty()) {
return new Routing(null, null, where, null);
}
Cond.Eq pkEq = null;
Cond skCond = null;
List<Cond> filterConds = new ArrayList<>();
for (Cond c : where) {
if (c instanceof Cond.Eq eq && isKeyCondition(eq, pkName)) {
pkEq = eq;
} else if (skCond == null && DynamoDbPartiQLKeyPlan.isSortKeyRange(c, skName)) {
skCond = c;
} else if (DynamoDbPartiQLKeyPlan.attributePaths(c).map(Path::root)
.anyMatch(root -> root.equals(pkName) || root.equals(skName))) {
return new Routing(null, null, where, partition.get());
} else {
filterConds.add(c);
}
}
return new Routing(pkEq, skCond, filterConds, null);
}
private record Page(List<JsonNode> items, JsonNode lastEvaluatedKey) {}
private Page readPage(Stmt.Select stmt, TableDefinition table, DynamoDbAccessPath accessPath,
Routing routing, Supplier<JsonNode> startKey, Integer limit, String region) {
if (routing.partition() != null) {
return readPartition(stmt, table, accessPath, routing, startKey, limit, region);
}
String pkName = accessPath.partitionKeyName();
String skName = accessPath.sortKeyName();
Cond.Eq pkEq = routing.pkEq();
Cond skCond = routing.skCond();
List<Cond> filterConds = routing.filterConds();
if (pkEq == null) {
// No equality on the selected source's partition key: AWS performs
// a full scan of the table or index and applies the remaining
// conditions as a filter (characterised on real AWS, eu-west-1,
// 2026-09-02).
ExprAttrBuilder eav = new ExprAttrBuilder();
ExprAttrNameBuilder ean = new ExprAttrNameBuilder();
List<Cond> scanFilters = new ArrayList<>(filterConds);
if (skCond != null) {
scanFilters.add(skCond);
}
String fe = buildFe(scanFilters, eav, ean);
JsonNode exclusiveStartKey = startKey.get();
DynamoDbAccessPathValidator.validateExclusiveStartKey(exclusiveStartKey, table, accessPath, true);
DynamoDbService.ScanResult result = service.scan(stmt.table(), fe,
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());
}
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);
}
ExprAttrBuilder eav = new ExprAttrBuilder();
ExprAttrNameBuilder ean = new ExprAttrNameBuilder();
String kce = buildKce(pkEq, skCond, pkName, skName, eav, ean);
String fe = buildFe(filterConds, eav, ean);
JsonNode exclusiveStartKey = startKey.get();
DynamoDbAccessPathValidator.validateExclusiveStartKey(exclusiveStartKey, table, accessPath, false);
DynamoDbService.QueryResult result = service.query(
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());
}
private Page readPartition(Stmt.Select stmt, TableDefinition table, DynamoDbAccessPath accessPath,
Routing routing, Supplier<JsonNode> startKey, Integer limit, String region) {
ExprAttrBuilder eav = new ExprAttrBuilder();
ExprAttrNameBuilder ean = new ExprAttrNameBuilder();
String kce = ean.alias(accessPath.partitionKeyName()) + " = " + eav.add(toTypedNode(routing.partition()));
JsonNode exclusiveStartKey = startKey.get();
DynamoDbAccessPathValidator.validateExclusiveStartKey(exclusiveStartKey, table, accessPath, false);
DynamoDbService.QueryResult result = service.query(stmt.table(), null, eav.toNode(mapper), kce, null,
limit, null, accessPath.indexName(), exclusiveStartKey, ean.toNode(mapper), region);
ExprAttrBuilder filterValues = new ExprAttrBuilder();
ExprAttrNameBuilder filterNames = new ExprAttrNameBuilder();
ExpressionEvaluator.Expr filter = ExpressionEvaluator.parse(buildFe(routing.filterConds(), filterValues, filterNames));
JsonNode names = filterNames.isEmpty() ? null : filterNames.toNode(mapper);
JsonNode values = filterValues.isEmpty() ? null : filterValues.toNode(mapper);
List<JsonNode> matching = result.items().stream()
.filter(item -> ExpressionEvaluator.evaluate(filter, item, names, values))
.toList();
return new Page(matching, result.lastEvaluatedKey());
}
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<>();
JsonNode lastKey = null;
do {
JsonNode from = lastKey;
Page page = readPage(stmt, table, accessPath, routing, () -> from, null, region);
rows.addAll(page.items());
lastKey = page.lastEvaluatedKey();
} while (lastKey != null);
Comparator<JsonNode> order = orderByComparator(stmt.orderBy(), accessPath, table);
rows.sort(order);
int start = 0;
if (after != null) {
while (start < rows.size() && order.compare(rows.get(start), after) <= 0) {
start++;
}
}
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);
}
private static void requireOrderByShape(Stmt.Select stmt, DynamoDbAccessPath accessPath) {
if (stmt.where().isEmpty()) {
throw new AwsException("ValidationException",
"Must have WHERE clause in the statement when using ORDER BY clause.", 400);
}
Set<String> keys = accessPath.keyAttributeNames();
for (OrderTerm term : stmt.orderBy()) {
if (!keys.contains(term.attribute())) {
throw new AwsException("ValidationException",
"Attribute " + term.attribute() + " in ORDER BY clause must be part of the primary key", 400);
}
}
String pkName = accessPath.partitionKeyName();
int hashKeyConditions = stmt.where().stream().mapToInt(c -> hashKeyConditionCount(c, pkName)).sum();
if (hashKeyConditions == 0) {
throw new AwsException("ValidationException",
"Must have at least one non-optional hash key condition in WHERE clause when using ORDER BY clause.",
400);
}
boolean ordersByHashKey = stmt.orderBy().stream().anyMatch(term -> term.attribute().equals(pkName));
if (hashKeyConditions > 1 && !ordersByHashKey) {
throw new AwsException("ValidationException",
"Must have hash key in ORDER BY clause when more than one hash key condition specified in WHERE clause.",
400);
}
}
private static int hashKeyConditionCount(Cond cond, String pkName) {
return switch (cond) {
case Cond.Eq eq when isKeyCondition(eq, pkName) -> 1;
case Cond.In in when isKeyCondition(in, pkName) -> in.values().size();
case Cond.Or or when or.operands().stream()
.allMatch(o -> o instanceof Cond.Eq && isKeyCondition(o, pkName)) -> or.operands().size();
default -> 0;
};
}
private static Comparator<JsonNode> orderByComparator(List<OrderTerm> terms, DynamoDbAccessPath accessPath,
TableDefinition table) {
String pkName = accessPath.partitionKeyName();
String skName = accessPath.sortKeyName();
boolean pkDescending = directionOf(terms, pkName).orElse(false);
Comparator<JsonNode> order = byAttribute(pkName, pkDescending);
if (skName != null) {
order = order.thenComparing(byAttribute(skName, directionOf(terms, skName).orElse(true)));
}
for (String tableKey : List.of(table.getPartitionKeyName(), Objects.toString(table.getSortKeyName(), ""))) {
if (!tableKey.isEmpty() && !tableKey.equals(pkName) && !tableKey.equals(skName)) {
order = order.thenComparing(byAttribute(tableKey, false));
}
}
return order;
}
private static Optional<Boolean> directionOf(List<OrderTerm> terms, String attribute) {
return terms.stream().filter(term -> term.attribute().equals(attribute)).findFirst().map(OrderTerm::descending);
}
private static Comparator<JsonNode> byAttribute(String attribute, boolean descending) {
Comparator<JsonNode> ascending = (a, b) -> ExpressionEvaluator.compareAttributeValues(a.path(attribute), b.path(attribute));
return descending ? ascending.reversed() : ascending;
}
private JsonNode orderingKey(JsonNode row, DynamoDbAccessPath accessPath, TableDefinition table) {
ObjectNode key = mapper.createObjectNode();
Set<String> names = new LinkedHashSet<>(accessPath.keyAttributeNames());
names.add(table.getPartitionKeyName());
if (table.getSortKeyName() != null) {
names.add(table.getSortKeyName());
}
names.forEach(name -> key.set(name, row.get(name)));
return key;
}
// NextToken is opaque to the client, so it carries a digest binding it to
// the statement text and parameter values that minted it. Real AWS rejects
// a token replayed against any other statement, table or access path with
@@ -239,22 +386,89 @@ class DynamoDbPartiQLHandler {
private String buildCondExpr(Cond c, ExprAttrBuilder eav, ExprAttrNameBuilder ean) {
return switch (c) {
case Cond.Eq eq -> ean.alias(eq.attr()) + " = " + eav.add(toTypedNode(eq.val()));
case Cond.Cmp cmp -> ean.alias(cmp.attr()) + " " + cmp.op() + " " + eav.add(toTypedNode(cmp.val()));
case Cond.Eq eq -> ean.alias(eq.path()) + " = " + eav.add(toTypedNode(eq.val()));
case Cond.Cmp cmp -> ean.alias(cmp.path()) + " " + cmp.op() + " " + eav.add(toTypedNode(cmp.val()));
case Cond.Between b ->
ean.alias(b.attr()) + " BETWEEN " + eav.add(toTypedNode(b.lo())) + " AND " + eav.add(toTypedNode(b.hi()));
ean.alias(b.path()) + " BETWEEN " + eav.add(toTypedNode(b.lo())) + " AND " + eav.add(toTypedNode(b.hi()));
case Cond.BeginsWith bw ->
"begins_with(" + ean.alias(bw.attr()) + ", " + eav.add(toTypedNode(bw.prefix())) + ")";
"begins_with(" + ean.alias(bw.path()) + ", " + eav.add(toTypedNode(bw.prefix())) + ")";
case Cond.In in -> ean.alias(in.path()) + " IN (" + in.values().stream()
.map(v -> eav.add(toTypedNode(v)))
.collect(Collectors.joining(", ")) + ")";
case Cond.Missing m ->
(m.negated() ? "attribute_exists(" : "attribute_not_exists(") + ean.alias(m.path()) + ")";
case Cond.Contains ct ->
"contains(" + ean.alias(ct.path()) + ", " + eav.add(toTypedNode(ct.operand())) + ")";
case Cond.AttributeType at ->
"attribute_type(" + ean.alias(at.path()) + ", " + eav.add(toTypedNode(at.type())) + ")";
case Cond.SizeCmp sc ->
"size(" + ean.alias(sc.path()) + ") " + sc.op() + " " + eav.add(toTypedNode(sc.val()));
case Cond.IsNull isNull -> (isNull.negated() ? "NOT " : "") + "attribute_type(" + ean.alias(isNull.path())
+ ", " + eav.add(mapper.createObjectNode().put("S", "NULL")) + ")";
case Cond.And and -> joinOperands(and.operands(), " AND ", eav, ean);
case Cond.Or or -> joinOperands(or.operands(), " OR ", eav, ean);
case Cond.Not not -> "NOT (" + buildCondExpr(not.operand(), eav, ean) + ")";
};
}
private static String condAttr(Cond c) {
return switch (c) {
case Cond.Eq eq -> eq.attr();
case Cond.Cmp cmp -> cmp.attr();
case Cond.Between b -> b.attr();
case Cond.BeginsWith bw -> bw.attr();
};
private String joinOperands(List<Cond> operands, String separator,
ExprAttrBuilder eav, ExprAttrNameBuilder ean) {
return "(" + operands.stream()
.map(operand -> buildCondExpr(operand, eav, ean))
.collect(Collectors.joining(separator)) + ")";
}
private static void requireFilterAttributesProjected(DynamoDbPartiQLKeyPlan keys, DynamoDbAccessPath accessPath,
TableDefinition table) {
if (!accessPath.isIndex() || "ALL".equals(accessPath.projectionType())) {
return;
}
List<String> unprojected = keys.unprojectedFilterAttributes(accessPath.projectedAttributeNames(table));
if (!unprojected.isEmpty()) {
throw new AwsException("ValidationException",
"One or more parameter values were invalid: Secondary index "
+ accessPath.indexName()
+ " does not project one or more filter attributes: ["
+ String.join(", ", unprojected) + "]", 400);
}
}
private static boolean isKeyCondition(Cond cond, String keyName) {
return cond.bareAttribute().filter(keyName::equals).isPresent();
}
private record SelectedColumn(Path path, String reportedName) {}
private static List<SelectedColumn> selectedColumns(Stmt.Select stmt) {
return stmt.columns().stream()
.map(column -> new SelectedColumn(column, column.leafName()))
.toList();
}
private ObjectNode selectColumns(JsonNode item, List<SelectedColumn> columns) {
ObjectNode projected = mapper.createObjectNode();
for (SelectedColumn column : columns) {
JsonNode value = resolvePath(item, column.path());
if (value != null && !value.isMissingNode()) {
projected.set(column.reportedName(), value);
}
}
return projected;
}
private JsonNode resolvePath(JsonNode item, Path path) {
List<Seg> segments = path.segments();
JsonNode current = item.get(((Seg.Name) segments.getFirst()).value());
for (int i = 1; i < segments.size() && current != null; i++) {
current = switch (segments.get(i)) {
case Seg.Name name -> current.path("M").get(name.value());
case Seg.Index index -> {
JsonNode list = current.path("L");
yield index.value() < list.size() ? list.get((int) index.value()) : null;
}
};
}
return current;
}
// --- INSERT ---
@@ -271,54 +485,108 @@ class DynamoDbPartiQLHandler {
} catch (ConditionalCheckFailedException e) {
throw new AwsException("DuplicateItemException", "Duplicate primary key exists in table", 400);
}
return emptyItemsResponse();
return itemsResponse(null);
}
// --- UPDATE ---
private JsonNode executeUpdate(Stmt.Update stmt, String region) {
requireNoIndexQualifier(stmt.index());
TableDefinition table = service.describeTable(stmt.table(), region);
requireOneValuePerKey(table, stmt.where());
ObjectNode key = buildKey(table, stmt.where());
ExprAttrBuilder eav = new ExprAttrBuilder();
ExprAttrNameBuilder ean = new ExprAttrNameBuilder();
StringBuilder ue = new StringBuilder();
if (!stmt.sets().isEmpty()) {
ue.append("SET ");
List<String> parts = new ArrayList<>();
for (Assign a : stmt.sets()) {
parts.add(ean.alias(a.attr()) + " = " + eav.add(toTypedNode(a.val())));
}
ue.append(String.join(", ", parts));
}
if (!stmt.removes().isEmpty()) {
if (!ue.isEmpty()) ue.append(" ");
ue.append("REMOVE ");
ue.append(stmt.removes().stream().map(ean::alias).reduce((a, b) -> a + ", " + b).orElse(""));
}
String ue = buildUpdateExpression(stmt.sets(), stmt.removes(), eav, ean);
String ce = updateCondition(table, stmt.where(), eav, ean);
String returnValues = stmt.returning().returnValues();
service.updateItem(stmt.table(), key, null, ue.toString(),
DynamoDbService.UpdateResult result = service.updateItem(stmt.table(), key, null, ue,
ean.isEmpty() ? null : ean.toNode(mapper),
eav.isEmpty() ? null : eav.toNode(mapper), "NONE", region);
return emptyItemsResponse();
eav.isEmpty() ? null : eav.toNode(mapper), returnValues, ce, region, "NONE");
return itemsResponse(returnedAttributes(stmt.returning(), result));
}
private static void requireNoIndexQualifier(String index) {
if (index != null) {
throw new AwsException("ValidationException",
"This operation is not supported on an index", 400);
}
}
private static Returning returningOf(Stmt stmt) {
return switch (stmt) {
case Stmt.Update upd -> upd.returning();
case Stmt.Delete del -> del.returning();
case Stmt.Select ignored -> Returning.NONE;
case Stmt.Insert ignored -> Returning.NONE;
case Stmt.Exists ignored -> Returning.NONE;
};
}
private JsonNode returnedAttributes(Returning returning, DynamoDbService.UpdateResult result) {
return switch (returning) {
case NONE -> null;
case ALL_OLD -> result.oldItem();
case ALL_NEW -> result.newItem();
case MODIFIED_OLD -> DynamoDbUpdatedAttributes.collect(result.touched(), false);
case MODIFIED_NEW -> DynamoDbUpdatedAttributes.collect(result.touched(), true);
};
}
// --- DELETE ---
private JsonNode executeDelete(Stmt.Delete stmt, String region) {
requireNoIndexQualifier(stmt.index());
TableDefinition table = service.describeTable(stmt.table(), region);
requireOneValuePerKey(table, stmt.where());
ObjectNode key = buildKey(table, stmt.where());
service.deleteItem(stmt.table(), key, null, null, null, region, "NONE");
return emptyItemsResponse();
ExprAttrBuilder eav = new ExprAttrBuilder();
ExprAttrNameBuilder ean = new ExprAttrNameBuilder();
String ce = deleteCondition(table, stmt.where(), eav, ean);
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);
}
// --- Transaction item builder ---
JsonNode toTransactItem(Stmt stmt, String region) {
record TransactMember(JsonNode item, TransactionCanceledException.CancellationReason reason) {
static final TransactMember TABLE_NOT_FOUND = cancels("ResourceNotFound", "Requested resource not found");
static final TransactMember KEY_MISMATCH = cancels("ValidationError", "The provided key element does not match the schema");
static TransactMember cancels(String code, String message) {
return new TransactMember(null, new TransactionCanceledException.CancellationReason(code, null, message));
}
}
TransactMember toTransactItem(Stmt stmt, String region) {
requireNoIndexQualifier(switch (stmt) {
case Stmt.Update upd -> upd.index();
case Stmt.Delete del -> del.index();
default -> null;
});
Optional<TableDefinition> found = service.findTable(stmt.table(), region);
if (found.isEmpty()) {
return TransactMember.TABLE_NOT_FOUND;
}
TableDefinition table = found.get();
if (returningOf(stmt) != Returning.NONE) {
throw new AwsException("ValidationException",
"RETURNING clause is not supported in ExecuteTransaction.", 400);
}
Optional<TransactMember> keyProblem = keyProblemOf(stmt, table);
if (keyProblem.isPresent()) {
return keyProblem.get();
}
ObjectNode txItem = mapper.createObjectNode();
switch (stmt) {
case Stmt.Insert ins -> {
TableDefinition table = service.describeTable(ins.table(), region);
String pkName = table.getPartitionKeyName();
ObjectNode item = mapper.createObjectNode();
ins.item().forEach((k, v) -> item.set(k, toTypedNode(v)));
@@ -329,67 +597,265 @@ class DynamoDbPartiQLHandler {
txItem.set("Put", put);
}
case Stmt.Update upd -> {
TableDefinition table = service.describeTable(upd.table(), region);
ObjectNode key = buildKey(table, upd.where());
ExprAttrBuilder eav = new ExprAttrBuilder();
ExprAttrNameBuilder ean = new ExprAttrNameBuilder();
StringBuilder ue = new StringBuilder();
if (!upd.sets().isEmpty()) {
ue.append("SET ");
List<String> parts = new ArrayList<>();
for (Assign a : upd.sets()) {
parts.add(ean.alias(a.attr()) + " = " + eav.add(toTypedNode(a.val())));
}
ue.append(String.join(", ", parts));
}
if (!upd.removes().isEmpty()) {
if (!ue.isEmpty()) ue.append(" ");
ue.append("REMOVE ");
ue.append(upd.removes().stream().map(ean::alias).reduce((a, b) -> a + ", " + b).orElse(""));
}
String ue = buildUpdateExpression(upd.sets(), upd.removes(), eav, ean);
ObjectNode update = mapper.createObjectNode();
update.put("TableName", upd.table());
update.set("Key", key);
update.put("UpdateExpression", ue.toString());
update.put("UpdateExpression", ue);
update.put("ConditionExpression", updateCondition(table, upd.where(), eav, ean));
if (!eav.isEmpty()) update.set("ExpressionAttributeValues", eav.toNode(mapper));
if (!ean.isEmpty()) update.set("ExpressionAttributeNames", ean.toNode(mapper));
txItem.set("Update", update);
}
case Stmt.Delete del -> {
TableDefinition table = service.describeTable(del.table(), region);
ObjectNode key = buildKey(table, del.where());
ExprAttrBuilder eav = new ExprAttrBuilder();
ExprAttrNameBuilder ean = new ExprAttrNameBuilder();
String ce = deleteCondition(table, del.where(), eav, ean);
ObjectNode delete = mapper.createObjectNode();
delete.put("TableName", del.table());
delete.set("Key", key);
if (ce != null) {
delete.put("ConditionExpression", ce);
}
if (!eav.isEmpty()) {
delete.set("ExpressionAttributeValues", eav.toNode(mapper));
}
if (!ean.isEmpty()) {
delete.set("ExpressionAttributeNames", ean.toNode(mapper));
}
txItem.set("Delete", delete);
}
case Stmt.Select ignored ->
throw new AwsException("ValidationException",
"SELECT is not supported inside ExecuteTransaction", 400);
case Stmt.Exists exists -> txItem.set("ConditionCheck", conditionCheck(exists.select(), table));
}
return txItem;
return new TransactMember(txItem, null);
}
private ObjectNode conditionCheck(Stmt.Select select, TableDefinition table) {
List<Cond> conditions = nonKeyConditions(table, select.where());
if (!pinsFullKey(table, select.where()) || conditions.isEmpty()) {
throw new AwsException("ValidationException",
"EXISTS() must contain a single item read with additional condition", 400);
}
ExprAttrBuilder eav = new ExprAttrBuilder();
ExprAttrNameBuilder ean = new ExprAttrNameBuilder();
ObjectNode check = mapper.createObjectNode();
check.put("TableName", select.table());
check.set("Key", buildKey(table, select.where()));
check.put("ConditionExpression", joinOperands(conditions, " AND ", eav, ean));
if (!eav.isEmpty()) {
check.set("ExpressionAttributeValues", eav.toNode(mapper));
}
if (!ean.isEmpty()) {
check.set("ExpressionAttributeNames", ean.toNode(mapper));
}
return check;
}
private static Optional<TransactMember> keyProblemOf(Stmt stmt, TableDefinition table) {
return switch (stmt) {
case Stmt.Insert ins -> table.getKeySchema().stream()
.map(KeySchemaElement::getAttributeName)
.filter(name -> !ins.item().containsKey(name))
.findFirst()
.map(name -> TransactMember.cancels("ValidationError",
"One or more parameter values were invalid: Missing the key " + name + " in the item"));
case Stmt.Update upd -> wrongKey(table, upd.where());
case Stmt.Delete del -> wrongKey(table, del.where());
default -> Optional.empty();
};
}
private static Optional<TransactMember> wrongKey(TableDefinition table, List<Cond> where) {
boolean namesOneItem = secondKeyValue(table, where).isEmpty() && pinsFullKey(table, where)
&& keyTypesMatch(table, where);
return namesOneItem ? Optional.empty() : Optional.of(TransactMember.KEY_MISMATCH);
}
private static boolean keyTypesMatch(TableDefinition table, List<Cond> where) {
return firstKeyValues(table, where).entrySet().stream()
.allMatch(key -> DynamoDbPartiQLKeyPlan.matchesKeyType(table, key.getKey(), key.getValue()));
}
TransactMember toTransactGetItem(Stmt.Select stmt, String region) {
Optional<TableDefinition> found = service.findTable(stmt.table(), region);
if (found.isEmpty()) {
return TransactMember.TABLE_NOT_FOUND;
}
TableDefinition table = found.get();
if (stmt.index() != null) {
throw new AwsException("ValidationException",
"Reads on indices are not supported within transactions.", 400);
}
new DynamoDbPartiQLKeyPlan(stmt.where(), DynamoDbAccessPath.resolve(table, null), table).requireNoOverlap();
if (!namesOnlyTheKey(table, stmt.where())) {
throw new AwsException("ValidationException",
"Select statements within ExecuteTransaction must specify the primary key in the where clause.", 400);
}
List<Cond> equalities = asEqualities(stmt.where());
if (!keyTypesMatch(table, equalities)) {
return TransactMember.KEY_MISMATCH;
}
ObjectNode get = mapper.createObjectNode();
get.put("TableName", stmt.table());
get.set("Key", buildKey(table, equalities));
ObjectNode txItem = mapper.createObjectNode();
txItem.set("Get", get);
return new TransactMember(txItem, null);
}
JsonNode projectSelected(Stmt.Select stmt, JsonNode item) {
if (item == null || stmt.columns().isEmpty()) {
return item;
}
return selectColumns(item, selectedColumns(stmt));
}
// --- Shared helpers ---
private ObjectNode buildKey(TableDefinition table, List<Cond> where) {
String pkName = table.getPartitionKeyName();
String skName = table.getSortKeyName();
ObjectNode key = mapper.createObjectNode();
for (Cond c : where) {
if (c instanceof Cond.Eq eq) {
if (pkName.equals(eq.attr()) || (skName != null && skName.equals(eq.attr()))) {
key.set(eq.attr(), toTypedNode(eq.val()));
}
private String buildUpdateExpression(List<SetClause> sets, List<Path> removes,
ExprAttrBuilder eav, ExprAttrNameBuilder ean) {
List<String> assignments = new ArrayList<>();
List<String> adds = new ArrayList<>();
List<String> deletes = new ArrayList<>();
for (SetClause clause : sets) {
switch (clause) {
case Assign assign -> assignments.add(assignExpr(assign, eav, ean));
case SetAdd add -> adds.add(ean.alias(add.path()) + " " + eav.add(toTypedNode(add.bag())));
case SetDelete delete -> deletes.add(ean.alias(delete.path()) + " " + eav.add(toTypedNode(delete.bag())));
}
}
if (!key.has(pkName)) {
throw new AwsException("ValidationException",
"WHERE clause must include an equality condition on the partition key", 400);
List<String> clauses = new ArrayList<>();
if (!assignments.isEmpty()) {
clauses.add("SET " + String.join(", ", assignments));
}
if (!removes.isEmpty()) {
clauses.add("REMOVE " + removes.stream()
.map(ean::alias)
.collect(Collectors.joining(", ")));
}
if (!adds.isEmpty()) {
clauses.add("ADD " + String.join(", ", adds));
}
if (!deletes.isEmpty()) {
clauses.add("DELETE " + String.join(", ", deletes));
}
return String.join(" ", clauses);
}
private String assignExpr(Assign assign, ExprAttrBuilder eav, ExprAttrNameBuilder ean) {
String assignment = ean.alias(assign.path()) + " = " + operandExpr(assign.left(), eav, ean);
if (assign.op() == null) {
return assignment;
}
return assignment + " " + assign.op() + " " + operandExpr(assign.right(), eav, ean);
}
private String operandExpr(Operand operand, ExprAttrBuilder eav, ExprAttrNameBuilder ean) {
return switch (operand) {
case Operand.Value value -> eav.add(toTypedNode(value.val()));
case Operand.Attribute attribute -> ean.alias(attribute.path());
case Operand.ListAppend append -> "list_append(" + operandExpr(append.first(), eav, ean)
+ ", " + operandExpr(append.second(), eav, ean) + ")";
};
}
private ObjectNode buildKey(TableDefinition table, List<Cond> where) {
if (!pinsFullKey(table, where)) {
throw new AwsException("ValidationException",
"Where clause does not contain a mandatory equality on all key attributes", 400);
}
ObjectNode key = mapper.createObjectNode();
firstKeyValues(table, where).forEach((name, value) -> key.set(name, toTypedNode(value)));
return key;
}
private static boolean pinsFullKey(TableDefinition table, List<Cond> where) {
return firstKeyValues(table, where).size() == keyAttributeNames(table).size();
}
static void requireReadsWithinLimit(TableDefinition table, List<Cond> where) {
new DynamoDbPartiQLKeyPlan(where, DynamoDbAccessPath.resolve(table, null), table).requireReadsWithinLimit();
}
static boolean namesOnlyTheKey(TableDefinition table, List<Cond> where) {
List<Cond> equalities = asEqualities(where);
return nonKeyConditions(table, equalities).isEmpty() && pinsFullKey(table, equalities);
}
private static List<Cond> asEqualities(List<Cond> where) {
return where.stream()
.map(c -> c instanceof Cond.In in && in.values().size() == 1 ? new Cond.Eq(in.path(), in.values().getFirst()) : c)
.toList();
}
private static Set<String> keyAttributeNames(TableDefinition table) {
return DynamoDbAccessPath.resolve(table, null).keyAttributeNames();
}
private static boolean isKeyEquality(Cond cond, Set<String> keyNames) {
return cond instanceof Cond.Eq eq && eq.bareAttribute().filter(keyNames::contains).isPresent();
}
private static Map<String, PVal> firstKeyValues(TableDefinition table, List<Cond> where) {
Set<String> keyNames = keyAttributeNames(table);
Map<String, PVal> firstValues = new LinkedHashMap<>();
for (Cond c : where) {
if (c instanceof Cond.Eq eq && isKeyEquality(eq, keyNames)) {
firstValues.putIfAbsent(eq.path().root(), eq.val());
}
}
return firstValues;
}
private static Optional<Cond.Eq> secondKeyValue(TableDefinition table, List<Cond> where) {
Map<String, PVal> firstValues = firstKeyValues(table, where);
return where.stream()
.filter(c -> c instanceof Cond.Eq eq
&& eq.bareAttribute().map(firstValues::get).filter(first -> !first.equals(eq.val())).isPresent())
.map(Cond.Eq.class::cast)
.findFirst();
}
private static List<Cond> nonKeyConditions(TableDefinition table, List<Cond> where) {
Set<String> keyNames = keyAttributeNames(table);
Map<String, PVal> firstValues = firstKeyValues(table, where);
return where.stream()
.filter(c -> !(c instanceof Cond.Eq eq && isKeyEquality(eq, keyNames)
&& firstValues.get(eq.path().root()).equals(eq.val())))
.toList();
}
private static void requireOneValuePerKey(TableDefinition table, List<Cond> where) {
secondKeyValue(table, where).ifPresent(eq -> {
throw new AwsException("ValidationException", "Multiple conditions on same key " + eq.path().root()
+ ". Only single item Update/Insert/Delete are supported", 400);
});
}
private String updateCondition(TableDefinition table, List<Cond> where,
ExprAttrBuilder eav, ExprAttrNameBuilder ean) {
String exists = "attribute_exists(" + ean.alias(table.getPartitionKeyName()) + ")";
List<Cond> filters = nonKeyConditions(table, where);
return filters.isEmpty() ? exists : exists + " AND " + joinOperands(filters, " AND ", eav, ean);
}
private String deleteCondition(TableDefinition table, List<Cond> where,
ExprAttrBuilder eav, ExprAttrNameBuilder ean) {
List<Cond> filters = nonKeyConditions(table, where);
if (filters.isEmpty()) {
return null;
}
return "attribute_not_exists(" + ean.alias(table.getPartitionKeyName()) + ") OR "
+ joinOperands(filters, " AND ", eav, ean);
}
JsonNode toTypedNode(PVal val) {
return switch (val) {
case PVal.Str s -> mapper.createObjectNode().put("S", s.v());
@@ -397,12 +863,34 @@ class DynamoDbPartiQLHandler {
case PVal.Bool b -> mapper.createObjectNode().put("BOOL", b.v());
case PVal.Null ignored -> mapper.createObjectNode().put("NULL", true);
case PVal.Av av -> av.node();
case PVal.ListOf list -> {
ObjectNode node = mapper.createObjectNode();
ArrayNode items = node.putArray("L");
list.items().forEach(item -> items.add(toTypedNode(item)));
yield node;
}
case PVal.Tuple tuple -> {
ObjectNode node = mapper.createObjectNode();
ObjectNode fields = node.putObject("M");
tuple.fields().forEach((name, value) -> fields.set(name, toTypedNode(value)));
yield node;
}
case PVal.Bag bag -> {
ObjectNode node = mapper.createObjectNode();
ArrayNode members = node.putArray(bag.type());
bag.members().forEach(member -> members.add(toTypedNode(member).path(bag.type().substring(0, 1))));
yield node;
}
};
}
private ObjectNode emptyItemsResponse() {
private ObjectNode itemsResponse(JsonNode returned) {
ObjectNode resp = mapper.createObjectNode();
resp.set("Items", mapper.createArrayNode());
ArrayNode items = mapper.createArrayNode();
if (returned != null && !returned.isEmpty()) {
items.add(returned);
}
resp.set("Items", items);
return resp;
}
@@ -440,6 +928,22 @@ class DynamoDbPartiQLHandler {
});
}
String alias(Path path) {
StringBuilder expression = new StringBuilder();
for (Seg segment : path.segments()) {
switch (segment) {
case Seg.Name name -> {
if (!expression.isEmpty()) {
expression.append('.');
}
expression.append(alias(name.value()));
}
case Seg.Index index -> expression.append('[').append(index.value()).append(']');
}
}
return expression.toString();
}
boolean isEmpty() { return aliasToName.isEmpty(); }
ObjectNode toNode(ObjectMapper mapper) {
@@ -0,0 +1,342 @@
package io.github.hectorvent.floci.services.dynamodb;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbPartiQLParser.Cond;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbPartiQLParser.PVal;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbPartiQLParser.Path;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
final class DynamoDbPartiQLKeyPlan {
private static final int MAX_BRANCHES = 1000;
private static final int MAX_DECOMPOSED_READS = 50;
private final String partitionKey;
private final String sortKey;
private final TableDefinition table;
private final boolean everyBranchPinsPartition;
private final List<Cond.Leaf> keyConditions = new ArrayList<>();
private final List<Branch> branches;
private boolean tooManyBranches;
private record Spread(List<Cond.Leaf> keyConditions, List<Cond> filters) {
static final Spread EMPTY = new Spread(List.of(), List.of());
Spread and(Spread other) {
return new Spread(Stream.concat(keyConditions.stream(), other.keyConditions.stream()).toList(),
Stream.concat(filters.stream(), other.filters.stream()).toList());
}
}
private record Branch(Key partition, PVal partitionValue, Range sortRange, List<Cond> filters) {}
DynamoDbPartiQLKeyPlan(List<Cond> where, DynamoDbAccessPath accessPath, TableDefinition table) {
this.partitionKey = accessPath.partitionKeyName();
this.sortKey = accessPath.sortKeyName();
this.table = table;
Cond conditions = new Cond.And(where);
this.everyBranchPinsPartition = everyBranchPinsPartition(conditions);
List<Spread> spread = spread(conditions);
this.branches = tooManyBranches
? List.of(new Branch(null, null, Range.ALL, where))
: spread.stream().map(this::branchOf).toList();
}
void requireKeyTypesMatchSchema() {
for (Cond.Leaf condition : keyConditions) {
String name = condition.path().root();
for (PVal value : values(condition)) {
String type = DynamoDbPartiQLParser.typeCode(value);
if (!DynamoDbPartiQLParser.ORDERED_TYPES.contains(type)) {
throw DynamoDbPartiQLParser.validationEx(
"Key value must be of type S, N, or B. Key name: " + name + ", Key type: " + type);
}
if (!matchesKeyType(table, name, value)) {
throw DynamoDbPartiQLParser.validationEx(
"Key attribute's data type should match its data type in table's schema: Key " + name);
}
}
}
}
static boolean matchesKeyType(TableDefinition table, String keyName, PVal value) {
return DynamoDbAccessPathValidator.attributeType(table, keyName).equals(DynamoDbPartiQLParser.typeCode(value));
}
void requireReadsWithinLimit() {
if (everyBranchPinsPartition && (tooManyBranches || branches.size() > MAX_DECOMPOSED_READS)) {
throw DynamoDbPartiQLParser.validationEx("Too many decomposed read operations for a given query.");
}
}
private boolean everyBranchPinsPartition(Cond cond) {
return switch (cond) {
case Cond.Leaf leaf -> pinsPartition(leaf);
case Cond.And and -> and.operands().stream().anyMatch(this::everyBranchPinsPartition);
case Cond.Or or -> or.operands().stream().allMatch(this::everyBranchPinsPartition);
case Cond.Not ignored -> false;
};
}
void requireNoOverlap() {
if (!keyed()) {
return;
}
Map<Key, List<Range>> rangesByPartition = new TreeMap<>();
for (Branch branch : branches) {
rangesByPartition.computeIfAbsent(branch.partition(), ignored -> new ArrayList<>()).add(branch.sortRange());
}
for (List<Range> ranges : rangesByPartition.values()) {
Range reach = null;
for (Range range : ranges.stream().filter(range -> !range.isEmpty()).sorted(Range.BY_LOWER).toList()) {
if (reach != null && range.startsBefore(reach)) {
throw DynamoDbPartiQLParser.validationEx(
"Overlapping conditions with range keys are not supported in where clause");
}
if (reach == null || range.endsAfter(reach)) {
reach = range;
}
}
}
}
List<String> unprojectedFilterAttributes(Set<String> projected) {
if (!keyed()) {
return List.of();
}
Set<String> last = Set.of();
for (Branch branch : branches.stream().sorted(Comparator.comparing(Branch::partition)).toList()) {
Set<String> names = branch.filters().stream()
.flatMap(DynamoDbPartiQLKeyPlan::attributePaths)
.map(Path::root)
.filter(root -> !projected.contains(root))
.collect(Collectors.toCollection(HashSet::new));
if (names.isEmpty()) {
return List.of();
}
last = names;
}
return List.copyOf(last);
}
Optional<PVal> singlePartition() {
Key first = branches.getFirst().partition();
if (!keyed() || branches.stream().anyMatch(branch -> branch.partition().compareTo(first) != 0)) {
return Optional.empty();
}
return Optional.of(branches.getFirst().partitionValue());
}
static Stream<Path> attributePaths(Cond cond) {
return DynamoDbPartiQLParser.leaves(cond).map(Cond.Leaf::path);
}
static boolean isSortKeyRange(Cond cond, String sortKey) {
if (sortKey == null || cond.bareAttribute().filter(sortKey::equals).isEmpty()) {
return false;
}
return cond instanceof Cond.Cmp cmp ? !"<>".equals(cmp.op())
: cond instanceof Cond.Eq || cond instanceof Cond.Between || cond instanceof Cond.BeginsWith;
}
private boolean keyed() {
return branches.stream().allMatch(branch -> branch.partition() != null);
}
private Branch branchOf(Spread spread) {
Key partition = null;
PVal partitionValue = null;
boolean conflicting = false;
Range sortRange = Range.ALL;
for (Cond.Leaf condition : spread.keyConditions()) {
if (condition.path().root().equals(partitionKey)) {
PVal value = ((Cond.Eq) condition).val();
Key key = Key.of(value);
conflicting |= partition != null && partition.compareTo(key) != 0;
if (partition == null) {
partition = key;
partitionValue = value;
}
} else {
sortRange = sortRange.intersect(rangeOf(condition));
}
}
return new Branch(conflicting ? null : partition, partitionValue, sortRange, spread.filters());
}
private List<Spread> spread(Cond cond) {
return switch (cond) {
case Cond.In in when isKeyCondition(in) -> {
keyConditions.add(in);
yield in.values().stream()
.map(value -> new Spread(List.of(new Cond.Eq(in.path(), value)), List.of()))
.toList();
}
case Cond.Leaf leaf when isKeyCondition(leaf) -> {
keyConditions.add(leaf);
yield List.of(new Spread(List.of(leaf), List.of()));
}
case Cond.And and -> {
List<Spread> spread = List.of(Spread.EMPTY);
for (Cond operand : and.operands()) {
spread = and(spread, spread(operand));
}
yield spread;
}
case Cond.Or or when namesKey(or) -> {
List<Spread> spread = or.operands().stream().flatMap(operand -> spread(operand).stream()).toList();
tooManyBranches |= spread.size() > MAX_BRANCHES;
yield spread;
}
default -> List.of(new Spread(List.of(), List.of(cond)));
};
}
private List<Spread> and(List<Spread> left, List<Spread> right) {
if ((long) left.size() * right.size() > MAX_BRANCHES) {
tooManyBranches = true;
return left;
}
return left.stream().flatMap(l -> right.stream().map(l::and)).toList();
}
private boolean namesKey(Cond cond) {
return switch (cond) {
case Cond.Leaf leaf -> isKeyCondition(leaf);
case Cond.And and -> and.operands().stream().anyMatch(this::namesKey);
case Cond.Or or -> or.operands().stream().anyMatch(this::namesKey);
case Cond.Not ignored -> false;
};
}
private boolean pinsPartition(Cond.Leaf leaf) {
return leaf.bareAttribute().filter(partitionKey::equals).isPresent()
&& (leaf instanceof Cond.Eq || leaf instanceof Cond.In);
}
private boolean isKeyCondition(Cond.Leaf leaf) {
if (leaf.bareAttribute().filter(partitionKey::equals).isPresent()) {
return pinsPartition(leaf);
}
return isSortKeyRange(leaf, sortKey)
|| (leaf instanceof Cond.In && leaf.bareAttribute().filter(name -> name.equals(sortKey)).isPresent());
}
private static List<PVal> values(Cond.Leaf condition) {
return switch (condition) {
case Cond.Eq eq -> List.of(eq.val());
case Cond.Cmp cmp -> List.of(cmp.val());
case Cond.Between between -> List.of(between.lo(), between.hi());
case Cond.BeginsWith beginsWith -> List.of(beginsWith.prefix());
case Cond.In in -> in.values();
default -> List.of();
};
}
private static Range rangeOf(Cond.Leaf condition) {
return switch (condition) {
case Cond.Eq eq -> new Range(Key.of(eq.val()), true, Key.of(eq.val()), true);
case Cond.Between between -> new Range(Key.of(between.lo()), true, Key.of(between.hi()), true);
case Cond.BeginsWith beginsWith -> new Range(Key.of(beginsWith.prefix()), true, prefixEnd(beginsWith.prefix()), false);
case Cond.Cmp cmp -> switch (cmp.op()) {
case "<" -> new Range(null, false, Key.of(cmp.val()), false);
case "<=" -> new Range(null, false, Key.of(cmp.val()), true);
case ">" -> new Range(Key.of(cmp.val()), false, null, false);
default -> new Range(Key.of(cmp.val()), true, null, false);
};
default -> Range.ALL;
};
}
private static Key prefixEnd(PVal prefix) {
byte[] bytes = Key.of(prefix).bytes();
for (int i = bytes.length - 1; i >= 0; i--) {
if (bytes[i] != (byte) 0xFF) {
byte[] end = Arrays.copyOf(bytes, i + 1);
end[i]++;
return new Key(null, end);
}
}
return null;
}
private record Key(BigDecimal number, byte[] bytes) implements Comparable<Key> {
static Key of(PVal value) {
return switch (value) {
case PVal.Num number -> new Key(new BigDecimal(number.v()), "N".getBytes(StandardCharsets.UTF_8));
case PVal.Str text -> new Key(null, text.v().getBytes(StandardCharsets.UTF_8));
case PVal.Av av when av.node().has("B") -> new Key(null, Base64.getDecoder().decode(av.node().get("B").asText()));
default -> new Key(null, DynamoDbPartiQLParser.typeCode(value).getBytes(StandardCharsets.UTF_8));
};
}
@Override
public int compareTo(Key other) {
if (number != null && other.number != null) {
return number.compareTo(other.number);
}
return Arrays.compareUnsigned(bytes, other.bytes);
}
}
private record Range(Key lower, boolean lowerInclusive, Key upper, boolean upperInclusive) {
static final Range ALL = new Range(null, false, null, false);
static final Comparator<Range> BY_LOWER = Comparator
.comparing(Range::lower, Comparator.nullsFirst(Comparator.<Key>naturalOrder()))
.thenComparing(range -> !range.lowerInclusive());
Range intersect(Range other) {
boolean raisesLower = other.lower != null && (lower == null || other.lower.compareTo(lower) > 0
|| (other.lower.compareTo(lower) == 0 && !other.lowerInclusive));
boolean dropsUpper = other.upper != null && (upper == null || other.upper.compareTo(upper) < 0
|| (other.upper.compareTo(upper) == 0 && !other.upperInclusive));
return new Range(raisesLower ? other.lower : lower, raisesLower ? other.lowerInclusive : lowerInclusive,
dropsUpper ? other.upper : upper, dropsUpper ? other.upperInclusive : upperInclusive);
}
boolean isEmpty() {
if (lower == null || upper == null) {
return false;
}
int order = lower.compareTo(upper);
return order > 0 || (order == 0 && !(lowerInclusive && upperInclusive));
}
boolean startsBefore(Range reach) {
if (reach.upper == null || lower == null) {
return true;
}
int order = lower.compareTo(reach.upper);
return order < 0 || (order == 0 && lowerInclusive && reach.upperInclusive);
}
boolean endsAfter(Range reach) {
if (reach.upper == null) {
return false;
}
if (upper == null) {
return true;
}
int order = upper.compareTo(reach.upper);
return order > 0 || (order == 0 && upperInclusive && !reach.upperInclusive);
}
}
}
File diff suppressed because it is too large. Load diff
@@ -633,6 +633,7 @@ public class DynamoDbService implements ResourceProvider {
if (conditionExpression != null) {
evaluateCondition(existing, conditionExpression, exprAttrNames, exprAttrValues, returnValuesOnConditionCheckFailure);
}
requireItemNestingWithinLimit(normalizedItem);
tableItems.put(itemKey, normalizedItem);
if (shouldPersist) {
@@ -922,6 +923,7 @@ public class DynamoDbService implements ResourceProvider {
// Reject any attempt to modify a key attribute
validateKeyNotModified(table, key, item);
requireItemNestingWithinLimit(item);
// AWS validates index key values against the item the update produces.
validateIndexKeyTypes(table, item, true);
@@ -1466,7 +1468,7 @@ public class DynamoDbService implements ResourceProvider {
for (int i = 0; i < transactItems.size(); i++) {
try {
validateTransactItem(transactItems.get(i), region, staged);
} catch (KeySchemaMismatchException e) {
} catch (KeySchemaMismatchException | ItemNestingExceededException e) {
throw cancelledByMember(transactItems.size(), i, e.getMessage());
}
}
@@ -1610,6 +1612,12 @@ public class DynamoDbService implements ResourceProvider {
}
}
private static void requireItemNestingWithinLimit(JsonNode item) {
if (!DynamoDbAttributeValueValidator.nestingWithinLimit(item)) {
throw new ItemNestingExceededException();
}
}
private static TransactionCanceledException cancelledByMember(int memberCount, int failedMember,
String message) {
List<TransactionCanceledException.CancellationReason> reasons = new ArrayList<>();
@@ -1712,6 +1720,7 @@ public class DynamoDbService implements ResourceProvider {
DynamoDbItemSize.validateSize(normalizedItem);
buildItemKey(table, normalizedItem);
validateIndexKeyTypes(table, normalizedItem, false);
requireItemNestingWithinLimit(normalizedItem);
} else if (transactItem.has("Delete")) {
JsonNode del = transactItem.get("Delete");
String tableName = canonicalTableName(region, del.path("TableName").asText());
@@ -1743,6 +1752,7 @@ public class DynamoDbService implements ResourceProvider {
applyUpdateExpression(item, updateExpression, exprAttrNames, exprAttrValues);
}
validateKeyNotModified(table, key, item);
requireItemNestingWithinLimit(item);
validateIndexKeyTypes(table, item, true);
}
}
@@ -2271,7 +2281,6 @@ public class DynamoDbService implements ResourceProvider {
String attrPath = clause.substring(0, eqIdx).trim();
touched.add(attrPath);
String attrName = resolveAttributeName(attrPath, exprAttrNames);
String rest = clause.substring(eqIdx + 1).trim();
@@ -2335,7 +2344,7 @@ public class DynamoDbService implements ResourceProvider {
// if_not_exists(attrRef, fallbackExpr) evaluates to:
// attrRef's current value — when attrRef exists in the item
// fallbackExpr — otherwise
// The result is always assigned to attrName.
// The result is always assigned to attrPath.
String[] args = extractFunctionArgs(valuePart);
if (args.length == 2) {
String checkAttr = resolveAttributeName(args[0].trim(), exprAttrNames);
@@ -2380,7 +2389,7 @@ public class DynamoDbService implements ResourceProvider {
ObjectNode result =
JsonNodeFactory.instance.objectNode();
result.set("L", merged);
item.set(attrName, result);
setValueAtPath(item, attrPath, result, exprAttrNames);
}
}
} else if (valuePart.startsWith(":") && exprAttrValues != null) {
@@ -2532,6 +2541,7 @@ public class DynamoDbService implements ResourceProvider {
* - For sets (SS, NS, BS): adds elements to the existing set, or creates the set if it doesn't exist
*/
private JsonNode applyAddOperation(JsonNode existingValue, JsonNode addValue) {
requireSameTypeAsOperand(existingValue, addValue, List.of("N", "SS", "NS", "BS"));
ObjectNode result = JsonNodeFactory.instance.objectNode();
// Handle number addition
@@ -2646,13 +2656,61 @@ public class DynamoDbService implements ResourceProvider {
return clause;
}
private static final Map<String, String> OPERAND_TYPE_NAMES = Map.of(
"S", "STRING", "N", "NUMBER", "B", "Binary", "BOOL", "BOOL", "NULL", "NULL", "L", "LIST", "M", "MAP");
void requireAddOrDeleteOperandTypes(String updateExpression, JsonNode exprAttrValues, boolean inValidationEnvelope) {
if (updateExpression == null || exprAttrValues == null) {
return;
}
String remaining = updateExpression.trim().replaceAll("\\s+", " ");
while (!remaining.isEmpty()) {
String keyword = remaining.substring(0, Math.max(remaining.indexOf(' '), 0)).toUpperCase();
String body = remaining.substring(keyword.length()).trim();
int nextClause = findNextClauseKeyword(body);
String actions = nextClause < 0 ? body : body.substring(0, nextClause);
remaining = nextClause < 0 ? "" : body.substring(nextClause);
Set<String> allowed = switch (keyword) {
case "ADD" -> Set.of("N", "SS", "NS", "BS");
case "DELETE" -> Set.of("SS", "NS", "BS");
default -> null;
};
while (allowed != null && !actions.isBlank()) {
int comma = findNextComma(actions);
String[] words = (comma < 0 ? actions : actions.substring(0, comma)).trim().split(" ");
actions = comma < 0 ? "" : actions.substring(comma + 1);
JsonNode operand = exprAttrValues.get(words[words.length - 1]);
if (operand == null) {
continue;
}
String type = DynamoDbAttributeValueValidator.typeOf(operand);
if (!allowed.contains(type)) {
throw new AwsException("ValidationException", (inValidationEnvelope ? "1 validation error detected: " : "")
+ "Invalid UpdateExpression: Incorrect operand type for operator or function;"
+ " operator: " + keyword + ", operand type: " + OPERAND_TYPE_NAMES.get(type)
+ ", typeSet: ALLOWED_FOR_ADD_OPERAND", 400);
}
}
}
}
private static void requireSameTypeAsOperand(JsonNode existingValue, JsonNode operand, List<String> types) {
for (String type : types) {
if (operand.has(type) && existingValue != null && !existingValue.has(type)) {
throw new AwsException("ValidationException",
"An operand in the update expression has an incorrect data type", 400);
}
}
}
/**
* Implements DynamoDB DELETE operation semantics:
* removes the specified elements from a set attribute (SS, NS, BS).
* Returns null if the resulting set is empty (caller should remove the attribute).
* Returns the existing value unchanged if types don't match or the value isn't a set.
* Returns the existing value unchanged if the value to delete isn't a set.
*/
private JsonNode applyDeleteOperation(JsonNode existingValue, JsonNode deleteValue) {
requireSameTypeAsOperand(existingValue, deleteValue, List.of("SS", "NS", "BS"));
ObjectNode result = JsonNodeFactory.instance.objectNode();
if (deleteValue.has("SS") && existingValue.has("SS")) {
@@ -711,7 +711,7 @@ final class ExpressionEvaluator {
JsonNode leftNode = resolveAttributeValue(cmp.left(), item, exprAttrNames, exprAttrValues);
JsonNode rightNode = resolveAttributeValue(cmp.right(), item, exprAttrNames, exprAttrValues);
if (leftNode == null || rightNode == null) return false;
if (leftNode == null || rightNode == null || !sameType(leftNode, rightNode)) return false;
int cmpResult = compareAttributeValues(leftNode, rightNode);
return switch (cmp.op()) {
case LT -> cmpResult < 0;
@@ -727,10 +727,14 @@ final class ExpressionEvaluator {
JsonNode val = resolveAttributeValue(bet.value(), item, exprAttrNames, exprAttrValues);
JsonNode low = resolveAttributeValue(bet.low(), item, exprAttrNames, exprAttrValues);
JsonNode high = resolveAttributeValue(bet.high(), item, exprAttrNames, exprAttrValues);
if (val == null || low == null || high == null) return false;
if (val == null || low == null || high == null || !sameType(val, low) || !sameType(val, high)) return false;
return compareAttributeValues(val, low) >= 0 && compareAttributeValues(val, high) <= 0;
}
private static boolean sameType(JsonNode left, JsonNode right) {
return left.fieldNames().next().equals(right.fieldNames().next());
}
private static boolean evaluateIn(InExpr in, JsonNode item,
JsonNode exprAttrNames, JsonNode exprAttrValues) {
// For IN, we use type-aware equality via the raw attribute value nodes
@@ -0,0 +1,10 @@
package io.github.hectorvent.floci.services.dynamodb;
import io.github.hectorvent.floci.core.common.AwsException;
public class ItemNestingExceededException extends AwsException {
public ItemNestingExceededException() {
super("ValidationException", DynamoDbAttributeValueValidator.NESTING_EXCEEDED, 400);
}
}