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

@@ -0,0 +1,115 @@
package io.github.hectorvent.floci.services.dynamodb;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
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.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
/**
* ADD and DELETE operand types, with every expectation captured from real DynamoDB (eu-west-2, 2026-09-17).
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class DynamoDbAddDeleteOperandIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String TABLE = "add-delete-operands";
private static final String KEY = "{\"pk\":{\"S\":\"a\"}}";
private static final String REFUSED = "Invalid UpdateExpression: Incorrect operand type for operator or function;"
+ " operator: %s, operand type: %s, typeSet: ALLOWED_FOR_ADD_OPERAND";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
@Order(1)
void createTable() {
request("DynamoDB_20120810.CreateTable", """
{
"TableName": "%s",
"AttributeDefinitions": [{"AttributeName":"pk","AttributeType":"S"}],
"KeySchema": [{"AttributeName":"pk","KeyType":"HASH"}],
"BillingMode": "PAY_PER_REQUEST"
}
""".formatted(TABLE))
.statusCode(200);
request("DynamoDB_20120810.PutItem", """
{"TableName":"%s","Item":{"pk":{"S":"a"},"n":{"N":"5"},"s":{"SS":["m"]}}}
""".formatted(TABLE))
.statusCode(200);
}
@Test
@Order(2)
void updateItemRefusesAnOperandBeforeReadingTheItem() {
updateItem("\"UpdateExpression\":\"ADD n :v\",\"ExpressionAttributeValues\":{\":v\":{\"S\":\"x\"}}")
.statusCode(400)
.body("message", equalTo("1 validation error detected: " + REFUSED.formatted("ADD", "STRING")));
updateItem("\"UpdateExpression\":\"SET t = :t ADD n :v\","
+ "\"ExpressionAttributeValues\":{\":t\":{\"S\":\"t\"},\":v\":{\"BOOL\":true}}")
.statusCode(400)
.body("message", equalTo("1 validation error detected: " + REFUSED.formatted("ADD", "BOOL")));
updateItem("\"UpdateExpression\":\"DELETE nope :v\",\"ConditionExpression\":\"attribute_exists(nope)\","
+ "\"ExpressionAttributeValues\":{\":v\":{\"L\":[{\"S\":\"m\"}]}}")
.statusCode(400)
.body("message", equalTo("1 validation error detected: " + REFUSED.formatted("DELETE", "LIST")));
updateItem("\"UpdateExpression\":\"DELETE s :v\",\"ExpressionAttributeValues\":{\":v\":{\"N\":\"1\"}}")
.statusCode(400)
.body("message", equalTo("1 validation error detected: " + REFUSED.formatted("DELETE", "NUMBER")));
request("DynamoDB_20120810.UpdateItem", """
{"TableName":"add-delete-operands-missing","Key":%s,"UpdateExpression":"ADD n :v",
"ExpressionAttributeValues":{":v":{"S":"x"}}}
""".formatted(KEY))
.statusCode(400)
.body("message", equalTo("1 validation error detected: " + REFUSED.formatted("ADD", "STRING")));
assertItemUnchanged();
}
@Test
@Order(3)
void transactWriteItemsRefusesAnOperandWithoutTheErrorCount() {
request("DynamoDB_20120810.TransactWriteItems", """
{"TransactItems":[{"Update":{"TableName":"%s","Key":%s,"UpdateExpression":"ADD n :v",
"ExpressionAttributeValues":{":v":{"S":"x"}}}}]}
""".formatted(TABLE, KEY))
.statusCode(400)
.body("message", equalTo(REFUSED.formatted("ADD", "STRING")));
assertItemUnchanged();
}
private static void assertItemUnchanged() {
request("DynamoDB_20120810.GetItem", """
{"TableName":"%s","Key":%s,"ConsistentRead":true}
""".formatted(TABLE, KEY))
.statusCode(200)
.body("Item.n.N", equalTo("5"))
.body("Item.s.SS", contains("m"))
.body("Item.t", nullValue());
}
private static ValidatableResponse updateItem(String expression) {
return request("DynamoDB_20120810.UpdateItem",
"{\"TableName\":\"" + TABLE + "\",\"Key\":" + KEY + "," + expression + "}");
}
private static ValidatableResponse request(String target, String body) {
return given()
.header("X-Amz-Target", target)
.contentType(CONTENT_TYPE)
.body(body)
.when()
.post("/")
.then();
}
}
@@ -1322,6 +1322,24 @@ class DynamoDbJsonHandlerTest {
assertEquals(NESTING_MESSAGE, ex.getMessage());
}
@Test
void updateItemRejectsAValueThatLeavesALeafAtLevel33UnderANestedPath() throws Exception {
createUsersTable("eu-west-1");
ObjectNode create = updateUserRequest();
create.put("UpdateExpression", "SET parent = :empty");
ObjectNode emptyMap = mapper.createObjectNode();
emptyMap.putObject("M");
create.set("ExpressionAttributeValues", mapper.createObjectNode().set(":empty", emptyMap));
handler.handle("UpdateItem", create, "eu-west-1");
ObjectNode request = updateUserRequest();
request.put("UpdateExpression", "SET parent.deep = :deep");
request.set("ExpressionAttributeValues", mapper.createObjectNode().set(":deep", nestedMaps(31)));
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("UpdateItem", request, "eu-west-1"));
assertEquals("Nesting Levels have exceeded supported limits", ex.getMessage());
}
private ObjectNode transactWrite(String action, ObjectNode op) {
op.put("TableName", "Users");
var member = mapper.createObjectNode();
@@ -1662,17 +1680,30 @@ class DynamoDbJsonHandlerTest {
createUsersTable("eu-west-1");
var request = mapper.createObjectNode();
request.put("Statement", "UPDATE \"Users\" SET deep=? WHERE userId=?");
request.set("Parameters", mapper.createArrayNode().add(nestedMaps(32)).add(attributeValue("S", "u1")));
request.set("Parameters", mapper.createArrayNode().add(nestedMaps(33)).add(attributeValue("S", "u1")));
var ex = assertThrows(AwsException.class,
() -> handler.handle("ExecuteStatement", request, "eu-west-1"));
assertEquals("ValidationException", ex.getErrorCode());
assertEquals("Nesting Levels have exceeded supported limits", ex.getMessage());
assertEquals("Nesting Levels have exceeded supported limits: "
+ "Attributes in the item have nested levels beyond supported limit", ex.getMessage());
}
@Test
void executeTransactionCancelsOnATooDeepParameterWithThatStatementsReason() throws Exception {
void executeStatementReadsAParameterWithALeafAtLevel33() throws Exception {
createUsersTable("eu-west-1");
ObjectNode request = mapper.createObjectNode();
request.put("Statement", "SELECT * FROM \"Users\" WHERE userId=? AND deep=?");
request.set("Parameters", mapper.createArrayNode().add(attributeValue("S", "u1")).add(nestedMaps(32)));
Response response = handler.handle("ExecuteStatement", request, "eu-west-1");
assertEquals(200, response.getStatus());
}
@Test
void executeTransactionCancelsOnAnItemLeftTooDeepWithThatStatementsReason() throws Exception {
createUsersTable("eu-west-1");
service.putItem("Users", item("userId", "u1"), "eu-west-1");
var fine = mapper.createObjectNode();
fine.put("Statement", "UPDATE \"Users\" SET x=? WHERE userId=?");
fine.set("Parameters", mapper.createArrayNode().add(attributeValue("S", "x")).add(attributeValue("S", "u1")));
@@ -0,0 +1,372 @@
package io.github.hectorvent.floci.services.dynamodb;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
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 java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.stream.Collectors;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* The PartiQL forms the AWS developer guide shows, with every expectation captured from real
* DynamoDB (eu-west-2, 2026-09-17).
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class DynamoDbPartiQLDocumentedSyntaxIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String TABLE = "partiql-documented-syntax";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
@Order(1)
void createTable() {
request("DynamoDB_20120810.CreateTable", """
{
"TableName": "%s",
"AttributeDefinitions": [
{"AttributeName":"pk","AttributeType":"S"},
{"AttributeName":"sk","AttributeType":"S"}
],
"KeySchema": [
{"AttributeName":"pk","KeyType":"HASH"},
{"AttributeName":"sk","KeyType":"RANGE"}
],
"BillingMode": "PAY_PER_REQUEST"
}
""".formatted(TABLE))
.statusCode(200);
}
@Test
@Order(2)
void insertsMapsListsAndSets() {
statement("INSERT INTO \"" + TABLE + "\" value {'pk':'dt', 'sk':'1', 'NumberType':1,"
+ " 'MapType' : {'entryname1': 'value', 'entryname2': 4},"
+ " 'ListType': [1,'stringval'],"
+ " 'NumberSetType':<<1,34,32,4.5>>,"
+ " 'StringSetType':<<'stringval','stringval2'>>}")
.statusCode(200);
getItem("dt")
.body("Item.NumberType.N", equalTo("1"))
.body("Item.MapType.M.entryname1.S", equalTo("value"))
.body("Item.MapType.M.entryname2.N", equalTo("4"))
.body("Item.ListType.L[0].N", equalTo("1"))
.body("Item.ListType.L[1].S", equalTo("stringval"))
.body("Item.NumberSetType.NS", containsInAnyOrder("1", "34", "32", "4.5"))
.body("Item.StringSetType.SS", containsInAnyOrder("stringval", "stringval2"));
}
@Test
@Order(3)
void updatesWithListAppendAndSetAdd() {
statement("UPDATE \"" + TABLE + "\""
+ " SET NumberType=NumberType + 100"
+ " SET MapType.NewMapEntry=[2020, 'stringvalue', 2.4]"
+ " SET ListType = LIST_APPEND(ListType, [4, <<'string1', 'string2'>>])"
+ " SET NumberSetType= SET_ADD(NumberSetType, <<345, 48.4>>)"
+ " SET StringSetType = SET_ADD(StringSetType, <<'stringsetvalue1', 'stringsetvalue2'>>)"
+ " WHERE pk='dt' AND sk='1'")
.statusCode(200);
getItem("dt")
.body("Item.NumberType.N", equalTo("101"))
.body("Item.MapType.M.NewMapEntry.L[0].N", equalTo("2020"))
.body("Item.MapType.M.NewMapEntry.L[1].S", equalTo("stringvalue"))
.body("Item.MapType.M.NewMapEntry.L[2].N", equalTo("2.4"))
.body("Item.ListType.L.size()", equalTo(4))
.body("Item.ListType.L[3].SS", containsInAnyOrder("string1", "string2"))
.body("Item.NumberSetType.NS", containsInAnyOrder("1", "4.5", "32", "34", "48.4", "345"))
.body("Item.StringSetType.SS",
containsInAnyOrder("stringsetvalue1", "stringsetvalue2", "stringval", "stringval2"));
}
@Test
@Order(4)
void updatesWithRemoveAndSetDelete() {
statement("UPDATE \"" + TABLE + "\""
+ " SET NumberType=NumberType - 1"
+ " REMOVE ListType[1]"
+ " REMOVE MapType.NewMapEntry"
+ " SET NumberSetType = SET_DELETE( NumberSetType, <<345>>)"
+ " SET StringSetType = SET_DELETE( StringSetType, <<'stringsetvalue1'>>)"
+ " WHERE pk='dt' AND sk='1'")
.statusCode(200);
getItem("dt")
.body("Item.NumberType.N", equalTo("100"))
.body("Item.ListType.L.size()", equalTo(3))
.body("Item.ListType.L[1].N", equalTo("4"))
.body("Item.MapType.M.NewMapEntry", nullValue())
.body("Item.NumberSetType.NS", containsInAnyOrder("1", "4.5", "32", "34", "48.4"))
.body("Item.StringSetType.SS", containsInAnyOrder("stringsetvalue2", "stringval", "stringval2"));
}
@Test
@Order(5)
void readsExponentsAndDoubledQuotes() {
statement("INSERT INTO \"" + TABLE + "\" VALUE {'pk':'num', 'sk':'1',"
+ " 'a':1E3, 'b':-1.5e-3, 'c':2.50, 'd':-0, 'q':'it''s here'}")
.statusCode(200);
getItem("num")
.body("Item.a.N", equalTo("1000"))
.body("Item.b.N", equalTo("-0.0015"))
.body("Item.c.N", equalTo("2.5"))
.body("Item.d.N", equalTo("0"))
.body("Item.q.S", equalTo("it's here"));
statement("SELECT sk FROM \"" + TABLE + "\" WHERE pk = 'num' AND q = 'it''s here' AND a = 1e3")
.statusCode(200)
.body("Items.size()", equalTo(1));
}
@Test
@Order(6)
void refusesABagDynamoDbCannotStore() {
statement("INSERT INTO \"" + TABLE + "\" VALUE {'pk':'bag', 'sk':'1', 's':<<>>}")
.statusCode(400)
.body("message", equalTo("Empty bags are not supported"));
statement("INSERT INTO \"" + TABLE + "\" VALUE {'pk':'bag', 'sk':'1', 's':<<1, 'a'>>}")
.statusCode(400)
.body("message", equalTo(
"Unsupported data type in Bag. DynamoDB only supports either numbers or strings in bags"));
statement("INSERT INTO \"" + TABLE + "\" VALUE {'pk':'bag', 'sk':'1', 's':<<'a', 'a'>>}")
.statusCode(400)
.body("message", equalTo(
"One or more parameter values were invalid: Input collection [a, a] contains duplicates."));
}
@Test
@Order(7)
void appendsToListsAndChangesSetMembers() {
putItem("sets", "\"AwardDetail\":{\"M\":{\"Grammys\":{\"L\":[{\"N\":\"2020\"},{\"N\":\"2018\"}]}}},"
+ "\"BandMembers\":{\"SS\":[\"member1\",\"member2\"]},\"Only\":{\"SS\":[\"only\"]}");
update("sets", "SET AwardDetail.Grammys = list_append(AwardDetail.Grammys, [2016])");
update("sets", "SET AwardDetail.Grammys = list_append([2010], AwardDetail.Grammys)");
update("sets", "SET BandMembers = set_add(BandMembers, <<'newbandmember'>>)");
update("sets", "SET BandMembers = set_delete(BandMembers, <<'member1'>>)");
update("sets", "SET Fresh = set_add(Fresh, <<'m'>>)");
update("sets", "SET Only = set_delete(Only, <<'only'>>)");
getItem("sets")
.body("Item.AwardDetail.M.Grammys.L.N", equalTo(List.of("2010", "2020", "2018", "2016")))
.body("Item.'#n0.#n1'", nullValue())
.body("Item.BandMembers.SS", containsInAnyOrder("member2", "newbandmember"))
.body("Item.Fresh.SS", containsInAnyOrder("m"))
.body("Item.Only", nullValue());
}
@Test
@Order(8)
void refusesMisusedUpdateFunctions() {
String prefix = "UPDATE \"" + TABLE + "\" SET Other = ";
statement(prefix + "set_add(BandMembers, <<'x'>>) WHERE pk='sets' AND sk='1'")
.statusCode(400)
.body("message", equalTo("The first argument to SET_ADD must equal the assignment value at 1:"
+ (prefix.length() + 1) + ":7"));
statement("UPDATE \"" + TABLE + "\" SET BandMembers = set_add(BandMembers, <<1>>) WHERE pk='sets' AND sk='1'")
.statusCode(400)
.body("message", equalTo("An operand in the update expression has an incorrect data type"));
statement("UPDATE \"" + TABLE + "\" SET NoList = list_append(NoList, [1]) WHERE pk='sets' AND sk='1'")
.statusCode(400)
.body("message", equalTo("The provided expression refers to an attribute that does not exist in the item"));
}
@Test
@Order(9)
void filtersWithFunctionsAndNullChecks() {
putItem("fn-1", "\"Address\":{\"S\":\"7834 24th Kirkland\"},\"tags\":{\"SS\":[\"a\",\"b\"]},"
+ "\"Total\":{\"N\":\"400\"},\"nul\":{\"NULL\":true},"
+ "\"Image\":{\"B\":\"" + Base64.getEncoder().encodeToString(new byte[400]) + "\"}");
putItem("fn-2", "\"Total\":{\"N\":\"550\"}");
assertKeys("pk IN ['fn-1', 'fn-2'] AND contains(\"Address\", 'Kirkland')", "fn-1");
assertKeys("pk IN ['fn-1', 'fn-2'] AND contains(tags, 'a')", "fn-1");
assertKeys("pk IN ['fn-1', 'fn-2'] AND attribute_type(\"Total\", 'N')", "fn-1", "fn-2");
assertKeys("pk IN ['fn-1', 'fn-2'] AND size(\"Image\") > 300", "fn-1");
assertKeys("pk IN ['fn-1', 'fn-2'] AND Total != 400", "fn-2");
assertKeys("pk IN ['fn-1', 'fn-2'] AND nul IS NULL", "fn-1");
assertKeys("pk IN ['fn-1', 'fn-2'] AND nul IS NOT NULL", "fn-2");
assertKeys("pk IN ['fn-1', 'fn-2'] AND absent IS NULL");
statement("SELECT pk FROM \"" + TABLE + "\" WHERE pk = 'fn-1' AND attribute_type(Total, 'X')")
.statusCode(400)
.body("message", equalTo(
"Invalid attribute type name found; type: X, valid types: {N,BS,L,B,NULL,M,S,SS,NS,BOOL}"));
}
@Test
@Order(10)
void ordersByTheKey() {
for (String pk : List.of("o", "p")) {
for (String sk : List.of("1", "2", "3")) {
request("DynamoDB_20120810.PutItem", """
{"TableName":"%s","Item":{"pk":{"S":"%s"},"sk":{"S":"%s"}}}
""".formatted(TABLE, pk, sk))
.statusCode(200);
}
}
assertOrder("pk = 'o' ORDER BY sk DESC", "o/3", "o/2", "o/1");
assertOrder("pk = 'o' ORDER BY sk", "o/1", "o/2", "o/3");
assertOrder("pk = 'o' ORDER BY pk ASC", "o/3", "o/2", "o/1");
assertOrder("pk IN ['o', 'p'] ORDER BY pk DESC, sk ASC", "p/1", "p/2", "p/3", "o/1", "o/2", "o/3");
String firstToken = request("DynamoDB_20120810.ExecuteStatement",
orderedBody("pk IN ['o', 'p'] ORDER BY pk DESC", 2, null))
.statusCode(200)
.body("Items.sk.S", equalTo(List.of("3", "2")))
.body("NextToken", notNullValue())
.extract().path("NextToken");
request("DynamoDB_20120810.ExecuteStatement", orderedBody("pk IN ['o', 'p'] ORDER BY pk DESC", 2, firstToken))
.statusCode(200)
.body("Items.pk.S", equalTo(List.of("p", "o")))
.body("Items.sk.S", equalTo(List.of("1", "3")));
}
@Test
@Order(11)
void refusesAnOrderByItCannotServe() {
String select = "SELECT sk FROM \"" + TABLE + "\" ";
statement(select + "ORDER BY sk")
.statusCode(400)
.body("message", equalTo("Must have WHERE clause in the statement when using ORDER BY clause."));
statement(select + "WHERE pk = 'o' ORDER BY Total DESC")
.statusCode(400)
.body("message", equalTo("Attribute Total in ORDER BY clause must be part of the primary key"));
statement(select + "WHERE pk > 'a' ORDER BY sk")
.statusCode(400)
.body("message", equalTo("Must have at least one non-optional hash key condition in WHERE clause"
+ " when using ORDER BY clause."));
statement(select + "WHERE pk IN ['o', 'p'] ORDER BY sk DESC")
.statusCode(400)
.body("message", equalTo("Must have hash key in ORDER BY clause when more than one hash key condition"
+ " specified in WHERE clause."));
}
@Test
@Order(12)
void checksAConditionWithExists() {
putItem("x1", "\"free\":{\"S\":\"x\"}");
putItem("x2", "\"free\":{\"S\":\"x\"}");
putItem("x3", "\"Awards\":{\"N\":\"1\"}");
transaction("EXISTS(SELECT * FROM \"" + TABLE + "\" WHERE pk = 'x1' AND sk = '1' AND Awards IS MISSING)",
"UPDATE \"" + TABLE + "\" SET AwardsWon=1 WHERE pk = 'x2' AND sk = '1'")
.statusCode(200);
getItem("x2").body("Item.AwardsWon.N", equalTo("1"));
transaction("EXISTS(SELECT * FROM \"" + TABLE + "\" WHERE pk = 'x3' AND sk = '1' AND Awards IS MISSING)",
"UPDATE \"" + TABLE + "\" SET Touched=1 WHERE pk = 'x1' AND sk = '1'")
.statusCode(400)
.body("__type", equalTo("TransactionCanceledException"))
.body("message", equalTo("Transaction cancelled, please refer cancellation reasons for specific reasons"
+ " [ConditionalCheckFailed, None]"))
.body("CancellationReasons[0].Code", equalTo("ConditionalCheckFailed"))
.body("CancellationReasons[0].Message", equalTo("The conditional request failed"))
.body("CancellationReasons[1].Code", equalTo("None"))
.body("CancellationReasons[1]", not(hasKey("Message")));
transaction("EXISTS(SELECT * FROM \"" + TABLE + "\" WHERE pk = 'x1' AND sk = '1')",
"UPDATE \"" + TABLE + "\" SET Touched=1 WHERE pk = 'x2' AND sk = '1'")
.statusCode(400)
.body("message", equalTo("Validation failed in TransactStatements[0]:"
+ " EXISTS() must contain a single item read with additional condition"));
statement("EXISTS(SELECT * FROM \"" + TABLE + "\" WHERE pk = 'x1' AND sk = '1' AND Awards IS MISSING)")
.statusCode(400)
.body("message", equalTo("EXISTS can only be used in ExecuteTransaction write requests."));
transaction("SELECT * FROM \"" + TABLE + "\" WHERE pk = 'x3' AND sk = '1'",
"UPDATE \"" + TABLE + "\" SET Touched=1 WHERE pk = 'x3' AND sk = '1'")
.statusCode(400)
.body("message", equalTo(
"ExecuteTransaction API does not support both read and write operations in the same request."));
}
private void assertKeys(String where, String... pks) {
statement("SELECT pk FROM \"" + TABLE + "\" WHERE " + where)
.statusCode(200)
.body("Items.pk.S", containsInAnyOrder((Object[]) pks));
}
private void assertOrder(String whereAndOrder, String... rows) {
List<String> expected = List.of(rows);
request("DynamoDB_20120810.ExecuteStatement", orderedBody(whereAndOrder, null, null))
.statusCode(200)
.body("Items.pk.S", equalTo(expected.stream().map(r -> r.split("/")[0]).toList()))
.body("Items.sk.S", equalTo(expected.stream().map(r -> r.split("/")[1]).toList()));
}
private static String orderedBody(String whereAndOrder, Integer limit, String nextToken) {
String statement = "SELECT pk, sk FROM \"" + TABLE + "\" WHERE " + whereAndOrder;
return "{\"Statement\":" + json(statement)
+ (limit == null ? "" : ",\"Limit\":" + limit)
+ (nextToken == null ? "" : ",\"NextToken\":" + json(nextToken)) + "}";
}
private static void update(String pk, String action) {
statement("UPDATE \"" + TABLE + "\" " + action + " WHERE pk='" + pk + "' AND sk='1'").statusCode(200);
}
private static ValidatableResponse getItem(String pk) {
return request("DynamoDB_20120810.GetItem", """
{"TableName":"%s","Key":{"pk":{"S":"%s"},"sk":{"S":"1"}},"ConsistentRead":true}
""".formatted(TABLE, pk))
.statusCode(200);
}
private static void putItem(String pk, String attributes) {
request("DynamoDB_20120810.PutItem", """
{"TableName":"%s","Item":{"pk":{"S":"%s"},"sk":{"S":"1"},%s}}
""".formatted(TABLE, pk, attributes))
.statusCode(200);
}
private static ValidatableResponse statement(String partiql) {
return request("DynamoDB_20120810.ExecuteStatement", "{\"Statement\":" + json(partiql) + "}");
}
private static ValidatableResponse transaction(String... statements) {
String members = Arrays.stream(statements)
.map(s -> "{\"Statement\":" + json(s) + "}")
.collect(Collectors.joining(","));
return request("DynamoDB_20120810.ExecuteTransaction", "{\"TransactStatements\":[" + members + "]}");
}
private static String json(String text) {
return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"") + "\"";
}
private static ValidatableResponse request(String target, String body) {
return given()
.header("X-Amz-Target", target)
.contentType(CONTENT_TYPE)
.body(body)
.when()
.post("/")
.then();
}
}
@@ -0,0 +1,732 @@
package io.github.hectorvent.floci.services.dynamodb;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
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 java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* PartiQL edge cases, with every expectation captured from real DynamoDB (eu-west-2, 2026-09-17).
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class DynamoDbPartiQLEdgeCaseIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String TABLE = "partiql-edge-cases";
private static final String QUOTED_TABLE = "\"" + TABLE + "\"";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
@Order(1)
void createTable() {
request("DynamoDB_20120810.CreateTable", """
{
"TableName": "%s",
"AttributeDefinitions": [
{"AttributeName":"pk","AttributeType":"S"},
{"AttributeName":"sk","AttributeType":"S"}
],
"KeySchema": [
{"AttributeName":"pk","KeyType":"HASH"},
{"AttributeName":"sk","KeyType":"RANGE"}
],
"BillingMode": "PAY_PER_REQUEST"
}
""".formatted(TABLE))
.statusCode(200);
}
@Test
@Order(2)
void readsKeyEqualitiesInsideAGroupedAnd() {
putItem("grouped", "\"flag\":{\"S\":\"x\"}");
putItem("grouped-other", "\"flag\":{\"S\":\"x\"}");
statement("UPDATE " + QUOTED_TABLE + " SET a=2 WHERE (pk='grouped' AND sk='1') AND flag='x'")
.statusCode(200);
getItem("grouped").body("Item.a.N", equalTo("2"));
transaction("EXISTS(SELECT * FROM " + QUOTED_TABLE + " WHERE (pk='grouped' AND sk='1') AND nope IS MISSING)",
"UPDATE " + QUOTED_TABLE + " SET b=1 WHERE pk='grouped-other' AND sk='1'")
.statusCode(200);
getItem("grouped-other").body("Item.b.N", equalTo("1"));
statement("DELETE FROM " + QUOTED_TABLE + " WHERE (pk='grouped' AND sk='1') AND flag='x'")
.statusCode(200);
getItem("grouped").body("Item", nullValue());
}
@Test
@Order(3)
void subtractsWithoutSpacesAndRefusesTrailingTokens() {
putItem("minus", "\"n\":{\"N\":\"5\"}");
statement("UPDATE " + QUOTED_TABLE + " SET n=n-1 WHERE pk='minus' AND sk='1'").statusCode(200);
getItem("minus").body("Item.n.N", equalTo("4"));
statement("SELECT sk FROM " + QUOTED_TABLE + " WHERE pk='minus' AND n>-5;")
.statusCode(200)
.body("Items.size()", equalTo(1));
statement("UPDATE " + QUOTED_TABLE + " SET t=1 WHERE pk='minus' AND sk='1' garbage")
.statusCode(400)
.body("message", equalTo(
"Statement wasn't well formed, can't be processed: Unexpected token after expression"));
getItem("minus").body("Item.t", nullValue());
}
@Test
@Order(4)
void refusesANegativeListIndex() {
putItem("index", "\"l\":{\"L\":[{\"S\":\"a\"},{\"S\":\"b\"}]}");
String select = "SELECT l[-1] FROM " + QUOTED_TABLE + " WHERE pk='index' AND sk='1'";
statement(select)
.statusCode(400)
.body("message", equalTo("List index is not within the allowable range; index: [-1] at 1:11:1"));
statement("SELECT l[-0] FROM " + QUOTED_TABLE + " WHERE pk='index' AND sk='1'")
.statusCode(200)
.body("Items[0].'l[0]'.S", equalTo("a"));
}
@Test
@Order(15)
void refusesAListIndexAboveTheIntegerRange() {
statement("SELECT l[2147483648] FROM " + QUOTED_TABLE + " WHERE pk='index' AND sk='1'")
.statusCode(400)
.body("message", equalTo("List index is not within the allowable range; index: [2147483648] at 1:10:10"));
statement("UPDATE " + QUOTED_TABLE + " REMOVE l[2147483648] WHERE pk='index' AND sk='1'")
.statusCode(400);
statement("SELECT l[2147483647] FROM " + QUOTED_TABLE + " WHERE pk='index' AND sk='1'")
.statusCode(200);
getItem("index").body("Item.l.L.size()", equalTo(2));
}
@Test
@Order(5)
void refusesANonStringTypeInAttributeType() {
statement("SELECT sk FROM " + QUOTED_TABLE + " WHERE pk='index' AND attribute_type(l, 1)")
.statusCode(400)
.body("message", equalTo("Incorrect operand type for operator or function;"
+ " operator or function: attribute_type, operand type: N"));
statement("SELECT sk FROM " + QUOTED_TABLE + " WHERE pk='index' AND attribute_type(l, true)")
.statusCode(400)
.body("message", equalTo("Incorrect operand type for operator or function;"
+ " operator or function: attribute_type, operand type: BOOL"));
}
@Test
@Order(6)
void refusesAValueThatIsNotASetInSetAdd() {
putItem("sets", "\"BandMembers\":{\"SS\":[\"member1\",\"member2\"]}");
String prefix = "UPDATE " + QUOTED_TABLE + "\nSET BandMembers = set_add(";
statement(prefix + "BandMembers, 'x')\nWHERE pk='sets' AND sk='1'")
.statusCode(400)
.body("message", equalTo("The second argument to SET_ADD must be a value with type SET at 2:27:11"));
String quotedPrefix = "UPDATE " + QUOTED_TABLE + " SET \"BandMembers\" = set_delete(";
statement(quotedPrefix + "\"BandMembers\", ['x']) WHERE pk='sets' AND sk='1'")
.statusCode(400)
.body("message", equalTo("The second argument to SET_DELETE must be a value with type SET at 1:"
+ (quotedPrefix.length() + 1) + ":13"));
getItem("sets").body("Item.BandMembers.SS", containsInAnyOrder("member1", "member2"));
}
@Test
@Order(7)
void refusesDuplicateMembersInABag() {
putItem("bags", "\"s\":{\"SS\":[\"a\"]},\"n\":{\"NS\":[\"1\"]}");
String update = "UPDATE " + QUOTED_TABLE + " SET ";
String where = " WHERE pk='bags' AND sk='1'";
statement(update + "s = set_add(s, <<'b','b'>>)" + where)
.statusCode(400)
.body("message", equalTo(
"One or more parameter values were invalid: Input collection [b, b] contains duplicates."));
statement(update + "n = set_add(n, <<2, 2.0>>)" + where)
.statusCode(400)
.body("message", equalTo(
"One or more parameter values were invalid: Input collection [2, 2.0] contains duplicates! under root"));
statement("SELECT sk FROM " + QUOTED_TABLE + where + " AND s = <<'a','a'>>")
.statusCode(400)
.body("message", equalTo(
"One or more parameter values were invalid: Input collection [a, a] contains duplicates."));
transaction("INSERT INTO " + QUOTED_TABLE + " VALUE {'pk':'bags-tx','sk':'1','x':[<<'a','a'>>]}")
.statusCode(400)
.body("message", equalTo("Validation failed in TransactStatements[0]:"
+ " One or more parameter values were invalid: Input collection [a, a] contains duplicates."));
getItem("bags-tx").body("Item", nullValue());
statement(update + "n = <<1, 10>>" + where).statusCode(200);
getItem("bags")
.body("Item.s.SS", containsInAnyOrder("a"))
.body("Item.n.NS", containsInAnyOrder("1", "10"));
}
@Test
@Order(8)
void refusesAnInvalidParameterBeforeReadingTheStatement() {
String duplicates = "One or more parameter values were invalid: Input collection [a, a] contains duplicates.";
String insert = "INSERT INTO " + QUOTED_TABLE + " VALUE {'pk':'params','sk':'1','x':?}";
String update = "UPDATE " + QUOTED_TABLE + " SET y = ? WHERE pk='params' AND sk='1'";
statement("UPDATE " + QUOTED_TABLE + " SET WHERE", "[{\"SS\":[\"a\",\"a\"]}]")
.statusCode(400)
.body("message", equalTo(duplicates));
statement(insert, "[{\"NULL\":false}]")
.statusCode(400)
.body("message", equalTo(
"One or more parameter values were invalid: Null attribute value types must have the value of true"));
request("DynamoDB_20120810.ExecuteTransaction", "{\"TransactStatements\":["
+ member(update, "[{\"N\":\"1\"}]") + "," + member(insert, "[{\"SS\":[\"a\",\"a\"]}]") + "]}")
.statusCode(400)
.body("message", equalTo(duplicates));
request("DynamoDB_20120810.BatchExecuteStatement",
"{\"Statements\":[" + member(update, "[{\"SS\":[]}]") + "]}")
.statusCode(200)
.body("Responses[0].Error.Code", equalTo("ValidationError"))
.body("Responses[0].Error.Message", equalTo(
"One or more parameter values were invalid: An string set may not be empty"));
getItem("params").body("Item", nullValue());
}
@Test
@Order(9)
void refusesTwoReadsOfOneItemInATransaction() {
putItem("reads", "\"a\":{\"S\":\"x\"}");
String select = "SELECT * FROM " + QUOTED_TABLE + " WHERE pk='reads' AND sk='1'";
transaction(select, "SELECT a FROM " + QUOTED_TABLE + " WHERE sk='1' AND pk='reads'")
.statusCode(400)
.body("message", equalTo("Transaction request cannot include multiple operations on one item"));
transaction(select, select, "SELECT * FROM " + QUOTED_TABLE + " WHERE pk=1 AND sk='1'")
.statusCode(400)
.body("message", equalTo("Transaction cancelled, please refer cancellation reasons for specific reasons"
+ " [None, None, ValidationError]"));
transaction(select, "SELECT * FROM " + QUOTED_TABLE + " WHERE pk='reads' AND sk='2'")
.statusCode(200)
.body("Responses[0].Item.a.S", equalTo("x"));
}
@Test
@Order(10)
void readsOnlyByTheKeyInATransaction() {
putItem("keyed", "\"flag\":{\"S\":\"right\"}");
String select = "SELECT * FROM " + QUOTED_TABLE + " WHERE ";
String refused = "Validation failed in TransactStatements[0]:"
+ " Select statements within ExecuteTransaction must specify the primary key in the where clause.";
transaction(select + "pk='keyed' AND sk='1' AND flag='right'")
.statusCode(400)
.body("message", equalTo(refused));
transaction(select + "pk='keyed' AND sk='1' AND pk='reads'")
.statusCode(400)
.body("message", equalTo(refused));
transaction(select + "pk='keyed'")
.statusCode(400)
.body("message", equalTo(refused));
transaction(select + "(sk='1') AND pk='keyed' AND pk='keyed'")
.statusCode(200)
.body("Responses[0].Item.flag.S", equalTo("right"));
}
@Test
@Order(11)
void refusesUnprojectedAttributesInsideGroupedConditionsOnAKeyedIndexRead() {
request("DynamoDB_20120810.CreateTable", """
{
"TableName": "partiql-edge-cases-index",
"AttributeDefinitions": [
{"AttributeName":"pk","AttributeType":"S"},
{"AttributeName":"gsiPk","AttributeType":"S"}
],
"KeySchema": [{"AttributeName":"pk","KeyType":"HASH"}],
"GlobalSecondaryIndexes": [{
"IndexName": "gsi-inc",
"KeySchema": [{"AttributeName":"gsiPk","KeyType":"HASH"}],
"Projection": {"ProjectionType":"INCLUDE","NonKeyAttributes":["projattr"]}
}],
"BillingMode": "PAY_PER_REQUEST"
}
""")
.statusCode(200);
request("DynamoDB_20120810.PutItem", """
{"TableName":"partiql-edge-cases-index",
"Item":{"pk":{"S":"p"},"gsiPk":{"S":"y"},"projattr":{"S":"proj1"},"nonproj":{"S":"np1"}}}
""")
.statusCode(200);
String select = "SELECT pk FROM \"partiql-edge-cases-index\".\"gsi-inc\" WHERE gsiPk='y' AND ";
String refused = "One or more parameter values were invalid: Secondary index gsi-inc"
+ " does not project one or more filter attributes: ";
statement(select + "NOT (nonproj='np1' OR projattr='x')")
.statusCode(400)
.body("message", equalTo(refused + "[nonproj]"));
statement(select + "b='1' AND (a='2' OR projattr='3')")
.statusCode(400)
.body("message", equalTo(refused + "[a, b]"));
statement(select + "(zz='1' OR aa='2' OR mm='3')")
.statusCode(400)
.body("message", equalTo(refused + "[zz, aa, mm]"));
statement(select + "(projattr='proj1' OR projattr='proj2')")
.statusCode(200)
.body("Items[0].pk.S", equalTo("p"));
}
@Test
@Order(12)
void skipsLineAndBlockComments() {
putItem("comments", "\"n\":{\"N\":\"1\"},\"note\":{\"S\":\"a--b /*c*/\"}");
String key = "pk='comments' AND sk='1'";
statement("SELECT/**/* FROM " + QUOTED_TABLE + " -- the table\nWHERE pk/* key */='comments' AND sk='1' --")
.statusCode(200)
.body("Items[0].note.S", equalTo("a--b /*c*/"));
statement("SELECT note FROM " + QUOTED_TABLE + " WHERE " + key + " AND note = 'a--b /*c*/'; -- done")
.statusCode(200)
.body("Items.size()", equalTo(1));
statement("UPDATE " + QUOTED_TABLE + " SET n=n--1 WHERE " + key)
.statusCode(400);
statement("SELECT * FROM " + QUOTED_TABLE + " WHERE " + key + " /* open")
.statusCode(400);
getItem("comments").body("Item.n.N", equalTo("1"));
}
@Test
@Order(13)
void appliesASignToANumberLiteral() {
putItem("signs", "\"n\":{\"N\":\"1\"}");
String select = "SELECT sk FROM " + QUOTED_TABLE + " WHERE pk='signs' AND sk='1' AND ";
statement(select + "n = - - 1").statusCode(200).body("Items.size()", equalTo(1));
statement(select + "n > -/* c */-1").statusCode(200).body("Items.size()", equalTo(0));
statement(select + "n BETWEEN - 2 AND +5 AND n IN [- 1, 1]").statusCode(200).body("Items.size()", equalTo(1));
statement(select + "n > -?").statusCode(400);
statement(select + "n > -n").statusCode(400);
statement("UPDATE " + QUOTED_TABLE + " SET n = n - - 2, l = [- 1] WHERE pk='signs' AND sk='1'").statusCode(200);
getItem("signs")
.body("Item.n.N", equalTo("3"))
.body("Item.l.L[0].N", equalTo("-1"));
}
@Test
@Order(14)
void refusesAParameterInsideACollectionLiteral() {
String prefix = "UPDATE " + QUOTED_TABLE + " SET x = ";
statement(prefix + "[?] WHERE pk='literals' AND sk='1'", "[{\"S\":\"v\"}]")
.statusCode(400)
.body("message", equalTo("Unsupported data type: Parameter under key root[0] at 1:"
+ (prefix.length() + 2) + ":1"));
String insert = "INSERT INTO " + QUOTED_TABLE + " VALUE {'pk':'literals','sk':'1','m':{'k':?}}";
statement(insert, "[{\"S\":\"v\"}]")
.statusCode(400)
.body("message", equalTo("Unsupported data type: Parameter under key root.k at 1:"
+ (insert.indexOf('?') + 1) + ":1"));
getItem("literals").body("Item", nullValue());
statement("INSERT INTO " + QUOTED_TABLE + " VALUE {'pk':?,'sk':'1','n':1}", "[{\"S\":\"literals\"}]")
.statusCode(200);
statement("SELECT sk FROM " + QUOTED_TABLE + " WHERE pk='literals' AND n IN [?, 2]", "[{\"N\":\"1\"}]")
.statusCode(200)
.body("Items.size()", equalTo(1));
}
@Test
@Order(16)
void refusesALiteralNested32LevelsDeep() {
String update = "UPDATE " + QUOTED_TABLE + " SET d = ";
String where = " WHERE pk='nested' AND sk='1'";
statement(update + "{'a':".repeat(32) + "1" + "}".repeat(32) + where)
.statusCode(400)
.body("message", equalTo("Nesting Levels have exceeded supported limits under root" + ".a".repeat(32)));
statement(update + "{'a':" + "[".repeat(31) + "1" + "]".repeat(31) + "}" + where)
.statusCode(400)
.body("message", equalTo("Nesting Levels have exceeded supported limits under root.a" + "[0]".repeat(31)));
transaction(update + "[".repeat(32) + "1" + "]".repeat(32) + where)
.statusCode(400)
.body("message", equalTo("Validation failed in TransactStatements[0]:"
+ " Nesting Levels have exceeded supported limits under root" + "[0]".repeat(32)));
statement("INSERT INTO " + QUOTED_TABLE + " VALUE {'pk':'nested','sk':'1','d':"
+ "{'a':".repeat(31) + "1" + "}".repeat(31) + "}")
.statusCode(200);
getItem("nested").body("Item.d.M.a.M.a.M", notNullValue());
}
@Test
@Order(17)
void refusesANonNumberLiteralInArithmeticBeforeTheCondition() {
putItem("arithmetic", "\"n\":{\"N\":\"1\"}");
String update = "UPDATE " + QUOTED_TABLE + " SET n = ";
String failingCondition = " WHERE pk='arithmetic' AND sk='1' AND nope='x'";
statement(update + "'a' + 1" + failingCondition)
.statusCode(400)
.body("message", equalTo("Incorrect operand type for operator or function; operator or function: +, operand type: S"));
statement(update + "n - null" + failingCondition)
.statusCode(400)
.body("message", equalTo("Incorrect operand type for operator or function; operator or function: -, operand type: NULL"));
transaction(update + "n + [1] WHERE pk='arithmetic' AND sk='1'")
.statusCode(400)
.body("message", equalTo("Validation failed in TransactStatements[0]:"
+ " Incorrect operand type for operator or function; operator or function: +, operand type: L"));
getItem("arithmetic").body("Item.n.N", equalTo("1"));
}
@Test
@Order(18)
void readsAttributeExistsAndAttributeNotExists() {
putItem("exists", "\"m\":{\"M\":{\"x\":{\"S\":\"y\"}}},\"l\":{\"L\":[{\"S\":\"a\"}]}");
String select = "SELECT sk FROM " + QUOTED_TABLE + " WHERE pk='exists' AND sk='1' AND ";
statement(select + "attribute_exists(m.x) AND ATTRIBUTE_NOT_EXISTS (nope) AND attribute_exists(l[0])")
.statusCode(200)
.body("Items.size()", equalTo(1));
statement(select + "(attribute_exists(nope) OR NOT attribute_exists(\"m\"))")
.statusCode(200)
.body("Items.size()", equalTo(0));
statement(select + "attribute_exists('m')").statusCode(400);
statement("UPDATE " + QUOTED_TABLE + " SET t=1 WHERE pk='exists' AND sk='1' AND attribute_exists(nope)")
.statusCode(400)
.body("__type", equalTo("ConditionalCheckFailedException"));
getItem("exists").body("Item.t", nullValue());
}
@Test
@Order(19)
void comparesAConditionWithABoolean() {
putItem("booleans", "\"n\":{\"N\":\"1\"},\"flag\":{\"S\":\"right\"},\"yes\":{\"BOOL\":true}");
String select = "SELECT sk FROM " + QUOTED_TABLE + " WHERE pk='booleans' AND sk='1' AND ";
for (String holds : List.of("attribute_exists(nope) = false", "true = attribute_exists(n)",
"attribute_exists(n) <> 1", "contains(nope, 'z') = false", "(n BETWEEN 0 AND 5) = true",
"(n = 5 OR flag = 'x') = false", "attribute_exists(nope) IN [true, false]",
"attribute_exists(n) = attribute_exists(flag)", "attribute_exists(n) = yes")) {
statement(select + holds).statusCode(200).body("Items.size()", equalTo(1));
}
for (String fails : List.of("attribute_exists(n) = 1", "NOT attribute_exists(n) = true",
"(attribute_exists(n) = true) = false", "attribute_exists(n) = flag")) {
statement(select + fails).statusCode(200).body("Items.size()", equalTo(0));
}
statement(select + "attribute_exists(n) > false")
.statusCode(400)
.body("message", equalTo("Incorrect operand type for operator or function; operator or function: >, operand type: BOOL"));
}
@Test
@Order(20)
void readsSortKeyConditionsThatAQueryKeyCannotHold() {
putItem("ranges", "\"flag\":{\"S\":\"one\"}");
putItem("ranges", "2", "\"flag\":{\"S\":\"two\"}");
String select = "SELECT sk FROM " + QUOTED_TABLE + " WHERE pk='ranges' AND ";
for (String both : List.of("(sk='1' OR sk='2')", "sk IN ['1','2']", "(sk < '1' OR sk > '1' OR sk='1')",
"attribute_exists(pk)")) {
statement(select + both).statusCode(200).body("Items.sk.S", containsInAnyOrder("1", "2"));
}
for (String second : List.of("NOT sk='1'", "sk <> '1'", "sk > '0' AND sk <> '1'")) {
statement(select + second).statusCode(200).body("Items.sk.S", containsInAnyOrder("2"));
}
statement(select + "sk='1' AND sk > '0'").statusCode(200).body("Items.sk.S", containsInAnyOrder("1"));
}
@Test
@Order(21)
void refusesOverlappingKeyConditionsAndMismatchedKeyTypes() {
String select = "SELECT sk FROM " + QUOTED_TABLE + " WHERE ";
String overlapping = "Overlapping conditions with range keys are not supported in where clause";
for (String where : List.of("pk IN ['ranges','ranges']", "pk='ranges' OR pk='ranges'",
"pk='ranges' AND (sk > '0' OR sk < '5')", "pk='ranges' AND (sk='1' OR flag='two')",
"(pk='ranges' AND flag='one') OR (pk='ranges' AND flag='two')")) {
statement(select + where).statusCode(400).body("message", equalTo(overlapping));
}
transaction(select + "pk IN ['ranges','ranges'] AND sk='1'")
.statusCode(400)
.body("message", equalTo("Validation failed in TransactStatements[0]: " + overlapping));
statement(select + "pk='ranges' OR sk='1'").statusCode(200);
statement(select + "pk = 1 OR pk = 'ranges'")
.statusCode(400)
.body("message", equalTo("Key attribute's data type should match its data type in table's schema: Key pk"));
statement(select + "pk = 'ranges' AND sk IN ['1', 2]")
.statusCode(400)
.body("message", equalTo("Key attribute's data type should match its data type in table's schema: Key sk"));
statement(select + "pk > 1").statusCode(200).body("Items.size()", equalTo(0));
}
@Test
@Order(22)
void checksProjectionOnEachKeyedBranchOfAnIndexRead() {
String select = "SELECT pk FROM \"partiql-edge-cases-index\".\"gsi-inc\" WHERE ";
String refused = "One or more parameter values were invalid: Secondary index gsi-inc"
+ " does not project one or more filter attributes: ";
statement(select + "(gsiPk='y' OR gsiPk='z') AND zz='1'")
.statusCode(400)
.body("message", equalTo(refused + "[zz]"));
statement(select + "(gsiPk='b' AND u1='1') OR (gsiPk='q' AND u2='1')")
.statusCode(400)
.body("message", equalTo(refused + "[u2]"));
statement(select + "(gsiPk='q' AND u1='1') OR (gsiPk='b' AND u2='1')")
.statusCode(400)
.body("message", equalTo(refused + "[u1]"));
for (String accepted : List.of("(gsiPk='y' AND projattr='1') OR (gsiPk='z' AND aa='1')",
"gsiPk > 'a' AND zz='1'", "gsiPk='y' AND (gsiPk='z' OR zz='1')", "(gsiPk='y' AND zz='1') OR aa='1'")) {
statement(select + accepted).statusCode(200);
}
statement(select + "(gsiPk='y' AND zz='1') OR (gsiPk='y' AND aa='1')")
.statusCode(400)
.body("message", equalTo("Overlapping conditions with range keys are not supported in where clause"));
}
@Test
@Order(23)
void readsByAOneValueInAndRefusesAnythingBesideTheKeyInTransactionAndBatchReads() {
String select = "SELECT sk FROM " + QUOTED_TABLE + " WHERE ";
String batchRefused = "Select statements within BatchExecuteStatement must specify the primary key in the where clause.";
transaction(select + "pk IN ['ranges'] AND sk IN ['1']")
.statusCode(200)
.body("Responses[0].Item.sk.S", equalTo("1"));
transaction(select + "(pk IN ['ranges']) AND pk='ranges' AND sk='2'")
.statusCode(200)
.body("Responses[0].Item.sk.S", equalTo("2"));
transaction(select + "pk IN ['other'] AND pk='ranges' AND sk='1'")
.statusCode(400)
.body("message", equalTo("Validation failed in TransactStatements[0]:"
+ " Select statements within ExecuteTransaction must specify the primary key in the where clause."));
transaction("EXISTS(" + select + "pk IN ['ranges'] AND sk='1' AND flag='one')",
"UPDATE " + QUOTED_TABLE + " SET b=1 WHERE pk='ranges' AND sk='2'")
.statusCode(400)
.body("message", equalTo("Validation failed in TransactStatements[0]:"
+ " EXISTS() must contain a single item read with additional condition"));
request("DynamoDB_20120810.BatchExecuteStatement", "{\"Statements\":["
+ "{\"Statement\":" + json(select + "pk IN ['ranges'] AND sk='1'") + "},"
+ "{\"Statement\":" + json(select + "pk='ranges' AND sk='1' AND flag='one'") + "},"
+ "{\"Statement\":" + json(select + "pk='ranges' AND sk='1' AND pk='other'") + "}]}")
.statusCode(200)
.body("Responses[0].Item.sk.S", equalTo("1"))
.body("Responses[1].Error.Message", equalTo(batchRefused))
.body("Responses[2].Error.Message", equalTo(batchRefused));
}
@Test
@Order(24)
void refusesTwoValuesForOneKeyOnAWriteAndReadsTheFirstInExists() {
putItem("conflict", "\"flag\":{\"S\":\"right\"}");
putItem("other", "\"flag\":{\"S\":\"right\"}");
String multiple = "Multiple conditions on same key pk. Only single item Update/Insert/Delete are supported";
statement("UPDATE " + QUOTED_TABLE + " SET a=1 WHERE pk='conflict' AND sk='1' AND pk='other'")
.statusCode(400)
.body("message", equalTo(multiple));
statement("DELETE FROM " + QUOTED_TABLE + " WHERE pk='conflict' AND sk='1' AND pk='other'")
.statusCode(400)
.body("message", equalTo(multiple));
statement("UPDATE " + QUOTED_TABLE + " SET a=2 WHERE pk='conflict' AND sk='1' AND pk='conflict'")
.statusCode(200);
getItem("conflict").body("Item.a.N", equalTo("2"));
transaction("EXISTS(SELECT * FROM " + QUOTED_TABLE + " WHERE pk='conflict' AND sk='1' AND pk='other' AND flag='right')",
"UPDATE " + QUOTED_TABLE + " SET b=1 WHERE pk='other' AND sk='1'")
.statusCode(400)
.body("CancellationReasons[0].Code", equalTo("ConditionalCheckFailed"))
.body("CancellationReasons[1].Code", equalTo("None"));
}
@Test
@Order(25)
void cancelsATransactionThatNamesAMissingTable() {
putItem("missing", "\"flag\":{\"S\":\"right\"}");
String missingUpdate = "UPDATE \"partiql-edge-cases-missing\" SET a=1 WHERE pk='x' AND sk='1'";
String select = "SELECT * FROM " + QUOTED_TABLE + " WHERE pk='missing' AND sk='1'";
transaction(missingUpdate + " RETURNING ALL NEW *", "DELETE FROM \"partiql-edge-cases-missing\" WHERE pk='x' AND sk='1'")
.statusCode(400)
.body("__type", equalTo("TransactionCanceledException"))
.body("CancellationReasons.Code", contains("ResourceNotFound", "ResourceNotFound"))
.body("CancellationReasons[0].Message", equalTo("Requested resource not found"));
transaction(select, "SELECT * FROM \"partiql-edge-cases-missing\".\"idx\" WHERE pk='x' AND sk='1'")
.statusCode(400)
.body("CancellationReasons.Code", contains("None", "ResourceNotFound"))
.body("CancellationReasons[0].Message", nullValue());
transaction(missingUpdate, "UPDATE " + QUOTED_TABLE + " SET a=1 WHERE pk='missing' AND sk='1' RETURNING ALL NEW *")
.statusCode(400)
.body("message", equalTo("Validation failed in TransactStatements[1]: RETURNING clause is not supported in ExecuteTransaction."));
transaction("SELECT * FROM \"partiql-edge-cases-missing\" WHERE pk='x' AND sk='1'", "SELECT * FROM " + QUOTED_TABLE + ".\"idx\" WHERE pk='x' AND sk='1'")
.statusCode(400)
.body("message", equalTo("Validation failed in TransactStatements[1]: Reads on indices are not supported within transactions."));
getItem("missing").body("Item.a", nullValue());
}
@Test
@Order(26)
void cancelsATransactionWhoseWriteDoesNotNameOneItem() {
putItem("keys", "\"flag\":{\"S\":\"right\"}");
String update = "UPDATE " + QUOTED_TABLE + " SET a=1 WHERE ";
String mismatch = "The provided key element does not match the schema";
transaction(update + "pk='keys'", update + "pk IN ['keys'] AND sk='1'", update + "pk='keys' AND sk='1' AND pk='other'",
update + "pk='keys' AND sk=1", update + "pk='keys' AND sk='1'")
.statusCode(400)
.body("CancellationReasons.Code", contains("ValidationError", "ValidationError", "ValidationError",
"ValidationError", "None"))
.body("CancellationReasons[0].Message", equalTo(mismatch))
.body("CancellationReasons[3].Message", equalTo(mismatch));
transaction("INSERT INTO " + QUOTED_TABLE + " VALUE {'pk':'keys-insert'}", "DELETE FROM " + QUOTED_TABLE + " WHERE sk='1'")
.statusCode(400)
.body("CancellationReasons[0].Message", equalTo("One or more parameter values were invalid: Missing the key sk in the item"))
.body("CancellationReasons[1].Message", equalTo(mismatch));
transaction("SELECT * FROM " + QUOTED_TABLE + " WHERE pk='keys' AND sk=1")
.statusCode(400)
.body("CancellationReasons[0].Message", equalTo(mismatch));
getItem("keys").body("Item.a", nullValue());
}
@Test
@Order(27)
void refusesAWriteThatLeavesTheItemTooDeep() {
putItem("deep-path", "\"m\":{\"M\":{}}");
String update = "UPDATE " + QUOTED_TABLE + " SET m.deep = ? WHERE pk='deep-path' AND sk='1'";
String parameters = "[" + "{\"M\":{\"a\":".repeat(31) + "{\"S\":\"x\"}" + "}}".repeat(31) + "]";
String tooDeep = "Nesting Levels have exceeded supported limits";
statement(update, parameters)
.statusCode(400)
.body("message", equalTo(tooDeep));
request("DynamoDB_20120810.ExecuteTransaction", "{\"TransactStatements\":[" + member(update, parameters) + "]}")
.statusCode(400)
.body("CancellationReasons[0].Code", equalTo("ValidationError"))
.body("CancellationReasons[0].Message", equalTo(tooDeep));
request("DynamoDB_20120810.BatchExecuteStatement", "{\"Statements\":[" + member(update, parameters) + "]}")
.statusCode(200)
.body("Responses[0].Error.Message", equalTo(tooDeep))
.body("Responses[0].TableName", equalTo(TABLE));
getItem("deep-path").body("Item.m.M.deep", nullValue());
}
@Test
@Order(28)
void namesAPathColumnFromItsLastNamedComponent() {
putItem("columns", "\"m\":{\"M\":{\"k\":{\"L\":[{\"S\":\"c\"}]}}}");
statement("SELECT m.k[0] FROM " + QUOTED_TABLE + " WHERE pk='columns' AND sk='1'")
.statusCode(200)
.body("Items[0].'k[0]'.S", equalTo("c"));
}
@Test
@Order(29)
void refusesTooManyInOperandsAndTooManyDecomposedReads() {
String select = "SELECT sk FROM " + QUOTED_TABLE + " WHERE ";
String tooManyReads = "Too many decomposed read operations for a given query.";
String tooManyOperands = "The IN operator is provided with too many operands; number of operands: 101";
for (String where : List.of("pk IN [" + inValues(51) + "]",
"pk='ranges' AND sk IN [" + inValues(51) + "]",
"pk IN [" + inValues(26) + "] AND sk IN ['1','2']")) {
statement(select + where).statusCode(400).body("message", equalTo(tooManyReads));
}
for (String where : List.of("pk IN [" + inValues(50) + "] AND flag IN [" + inValues(100) + "]",
"pk IN [" + inValues(51) + "] OR flag='one'")) {
statement(select + where).statusCode(200);
}
request("DynamoDB_20120810.BatchExecuteStatement",
"{\"Statements\":[{\"Statement\":" + json(select + "pk IN [" + inValues(51) + "] AND sk='1'") + "}]}")
.statusCode(200)
.body("Responses[0].Error.Message", equalTo(tooManyReads));
statement(select + "pk='ranges' AND flag IN [" + inValues(101) + "]")
.statusCode(400)
.body("message", equalTo(tooManyOperands));
statement("UPDATE " + QUOTED_TABLE + " SET t=1 WHERE pk='ranges' AND sk='1' AND flag IN [" + inValues(101) + "]")
.statusCode(400)
.body("message", equalTo(tooManyOperands));
transaction("SELECT * FROM " + QUOTED_TABLE + " WHERE pk IN [" + inValues(101) + "] AND sk='1'")
.statusCode(400)
.body("message", equalTo("Validation failed in TransactStatements[0]: " + tooManyOperands));
getItem("ranges").body("Item.t", nullValue());
}
private static ValidatableResponse getItem(String pk) {
return request("DynamoDB_20120810.GetItem", """
{"TableName":"%s","Key":{"pk":{"S":"%s"},"sk":{"S":"1"}},"ConsistentRead":true}
""".formatted(TABLE, pk))
.statusCode(200);
}
private static void putItem(String pk, String attributes) {
putItem(pk, "1", attributes);
}
private static void putItem(String pk, String sk, String attributes) {
request("DynamoDB_20120810.PutItem", """
{"TableName":"%s","Item":{"pk":{"S":"%s"},"sk":{"S":"%s"},%s}}
""".formatted(TABLE, pk, sk, attributes))
.statusCode(200);
}
private static ValidatableResponse statement(String partiql) {
return request("DynamoDB_20120810.ExecuteStatement", "{\"Statement\":" + json(partiql) + "}");
}
private static ValidatableResponse statement(String partiql, String parameters) {
return request("DynamoDB_20120810.ExecuteStatement", member(partiql, parameters));
}
private static ValidatableResponse transaction(String... statements) {
String members = Arrays.stream(statements)
.map(s -> "{\"Statement\":" + json(s) + "}")
.collect(Collectors.joining(","));
return request("DynamoDB_20120810.ExecuteTransaction", "{\"TransactStatements\":[" + members + "]}");
}
private static String member(String partiql, String parameters) {
return "{\"Statement\":" + json(partiql) + ",\"Parameters\":" + parameters + "}";
}
private static String inValues(int count) {
return IntStream.range(0, count).mapToObj(i -> "'v" + i + "'").collect(Collectors.joining(","));
}
private static String json(String text) {
return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n") + "\"";
}
private static ValidatableResponse request(String target, String body) {
return given()
.header("X-Amz-Target", target)
.contentType(CONTENT_TYPE)
.body(body)
.when()
.post("/")
.then();
}
}
@@ -0,0 +1,342 @@
package io.github.hectorvent.floci.services.dynamodb;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
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.equalTo;
import static org.hamcrest.Matchers.nullValue;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class DynamoDbPartiQLIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String TABLE = "partiql-statements";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
@Order(1)
void createTable() {
request("DynamoDB_20120810.CreateTable", """
{
"TableName": "%s",
"AttributeDefinitions": [{"AttributeName":"pk","AttributeType":"S"}],
"KeySchema": [{"AttributeName":"pk","KeyType":"HASH"}],
"BillingMode": "PAY_PER_REQUEST"
}
""".formatted(TABLE))
.statusCode(200);
}
@Test
@Order(2)
void selectReportsADocumentPathUnderItsLeafName() {
putItem("path-select", """
"profile":{"M":{"sub":{"S":"deep"},"sib":{"S":"keep"}}},
"tags":{"L":[{"S":"a"},{"S":"b"}]}
""");
statement("SELECT profile.sub, tags[1] FROM \"" + TABLE + "\" WHERE pk = 'path-select'")
.statusCode(200)
.body("Items.size()", equalTo(1))
.body("Items[0].sub.S", equalTo("deep"))
.body("Items[0].'tags[1]'.S", equalTo("b"))
.body("Items[0].profile", nullValue());
}
@Test
@Order(3)
void updateWritesThroughADocumentPath() {
putItem("path-update", "\"profile\":{\"M\":{\"sub\":{\"S\":\"old\"}}}");
statement("UPDATE \"" + TABLE + "\" SET profile.sub = 'new' WHERE pk = 'path-update'")
.statusCode(200);
statement("SELECT profile.sub FROM \"" + TABLE + "\" WHERE pk = 'path-update'")
.statusCode(200)
.body("Items[0].sub.S", equalTo("new"));
}
@Test
@Order(4)
void whereTakesInNotAndTheMissingPredicate() {
putItem("grammar-a", "\"kind\":{\"S\":\"alpha\"}");
putItem("grammar-b", "\"kind\":{\"S\":\"beta\"}");
statement("SELECT pk FROM \"" + TABLE + "\" WHERE pk IN ['grammar-a','grammar-b']"
+ " AND NOT begins_with(\"kind\", 'al')")
.statusCode(200)
.body("Items.size()", equalTo(1))
.body("Items[0].pk.S", equalTo("grammar-b"));
statement("SELECT pk FROM \"" + TABLE + "\" WHERE pk = 'grammar-a' AND \"kind\" IS NOT MISSING")
.statusCode(200)
.body("Items.size()", equalTo(1));
statement("SELECT pk FROM \"" + TABLE + "\" WHERE pk = 'grammar-a' AND \"kind\" IS MISSING")
.statusCode(200)
.body("Items.size()", equalTo(0));
}
@Test
@Order(5)
void updateOnAKeyHoldingNoItemFailsTheConditionalCheck() {
statement("UPDATE \"" + TABLE + "\" SET data = 'new' WHERE pk = 'write-ghost'")
.statusCode(400)
.body("__type", equalTo("ConditionalCheckFailedException"));
request("DynamoDB_20120810.GetItem", """
{"TableName":"%s","Key":{"pk":{"S":"write-ghost"}}}
""".formatted(TABLE))
.statusCode(200)
.body("Item", nullValue());
}
@Test
@Order(6)
void aFalsePredicateBesideTheKeyLeavesTheItem() {
putItem("write-pred", "\"name\":{\"S\":\"alpha\"},\"n\":{\"N\":\"5\"}");
statement("UPDATE \"" + TABLE + "\" SET n = 9 WHERE pk = 'write-pred' AND \"name\" = 'beta'")
.statusCode(400)
.body("__type", equalTo("ConditionalCheckFailedException"));
statement("DELETE FROM \"" + TABLE + "\" WHERE pk = 'write-pred' AND \"name\" = 'beta'")
.statusCode(400)
.body("__type", equalTo("ConditionalCheckFailedException"));
request("DynamoDB_20120810.GetItem", """
{"TableName":"%s","Key":{"pk":{"S":"write-pred"}}}
""".formatted(TABLE))
.statusCode(200)
.body("Item.n.N", equalTo("5"));
}
@Test
@Order(7)
void deleteOnAKeyHoldingNoItemIsANoOpEvenWithAPredicate() {
statement("DELETE FROM \"" + TABLE + "\" WHERE pk = 'write-absent' AND \"name\" = 'x'")
.statusCode(200);
}
@Test
@Order(8)
void aWriteWithoutTheKeyEqualityIsRejected() {
statement("DELETE FROM \"" + TABLE + "\" WHERE \"name\" = 'alpha'")
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo(
"Where clause does not contain a mandatory equality on all key attributes"));
}
@Test
@Order(9)
void updateReturningReportsTheRowOnTheRequestedSide() {
putItem("ret-update", "\"data\":{\"S\":\"old\"},\"keep\":{\"S\":\"same\"}");
statement("UPDATE \"" + TABLE + "\" SET data = 'new' WHERE pk = 'ret-update' RETURNING ALL OLD *")
.statusCode(200)
.body("Items.size()", equalTo(1))
.body("Items[0].data.S", equalTo("old"))
.body("Items[0].keep.S", equalTo("same"));
statement("UPDATE \"" + TABLE + "\" SET data = 'newer' WHERE pk = 'ret-update'"
+ " RETURNING MODIFIED NEW *")
.statusCode(200)
.body("Items.size()", equalTo(1))
.body("Items[0].data.S", equalTo("newer"))
.body("Items[0].keep", nullValue())
.body("Items[0].pk", nullValue());
}
@Test
@Order(10)
void anEmptyModifiedProjectionAnswersNoRow() {
putItem("ret-removed", "\"data\":{\"S\":\"old\"}");
statement("UPDATE \"" + TABLE + "\" REMOVE data WHERE pk = 'ret-removed'"
+ " RETURNING MODIFIED NEW *")
.statusCode(200)
.body("Items.size()", equalTo(0));
}
@Test
@Order(11)
void deleteTakesOnlyReturningAllOld() {
putItem("ret-delete", "\"data\":{\"S\":\"gone\"}");
statement("DELETE FROM \"" + TABLE + "\" WHERE pk = 'ret-delete' RETURNING MODIFIED OLD *")
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("Invalid returning clause: RETURNING MODIFIED OLD *."
+ " Only RETURNING ALL OLD * is allowed in DELETE statements."));
statement("DELETE FROM \"" + TABLE + "\" WHERE pk = 'ret-delete' RETURNING ALL OLD *")
.statusCode(200)
.body("Items.size()", equalTo(1))
.body("Items[0].data.S", equalTo("gone"));
statement("DELETE FROM \"" + TABLE + "\" WHERE pk = 'ret-delete' RETURNING ALL OLD *")
.statusCode(200)
.body("Items.size()", equalTo(0));
}
@Test
@Order(12)
void aTransactionMemberTakesNoReturningClause() {
request("DynamoDB_20120810.ExecuteTransaction", """
{"TransactStatements":[{"Statement":"UPDATE \\"%s\\" SET data = 'v' WHERE pk = 'ret-txn' RETURNING ALL NEW *"}]}
""".formatted(TABLE))
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("Validation failed in TransactStatements[0]:"
+ " RETURNING clause is not supported in ExecuteTransaction."));
}
@Test
@Order(13)
void updateSetsFromAnAttributeAndALiteral() {
putItem("arith", "\"n\":{\"N\":\"5\"}");
statement("UPDATE \"" + TABLE + "\" SET n = n + 1 WHERE pk = 'arith' RETURNING MODIFIED NEW *")
.statusCode(200)
.body("Items[0].n.N", equalTo("6"));
statement("UPDATE \"" + TABLE + "\" SET n = n - 2 WHERE pk = 'arith' RETURNING MODIFIED NEW *")
.statusCode(200)
.body("Items[0].n.N", equalTo("4"));
}
@Test
@Order(14)
void aReplayedTransactionTokenDoesNotApplyTwice() {
putItem("txn-idem", "\"n\":{\"N\":\"0\"}");
String body = """
{"ClientRequestToken":"partiql-idem-token","TransactStatements":[
{"Statement":"UPDATE \\"%s\\" SET n = n + 1 WHERE pk = 'txn-idem'"}]}
""".formatted(TABLE);
request("DynamoDB_20120810.ExecuteTransaction", body).statusCode(200);
request("DynamoDB_20120810.ExecuteTransaction", body).statusCode(200);
request("DynamoDB_20120810.GetItem", """
{"TableName":"%s","Key":{"pk":{"S":"txn-idem"}}}
""".formatted(TABLE))
.statusCode(200)
.body("Item.n.N", equalTo("1"));
}
@Test
@Order(15)
void aWriteStatementRejectsAnIndexQualifier() {
statement("INSERT INTO \"" + TABLE + "\".\"an-index\" VALUE {'pk': 'qualified'}")
.statusCode(400)
.body("message", equalTo("FROM clause may only contain a single table name"));
statement("UPDATE \"" + TABLE + "\".\"an-index\" SET data = 'x' WHERE pk = 'qualified'")
.statusCode(400)
.body("message", equalTo("This operation is not supported on an index"));
statement("DELETE FROM \"" + TABLE + "\".\"an-index\" WHERE pk = 'qualified'")
.statusCode(400)
.body("message", equalTo("This operation is not supported on an index"));
request("DynamoDB_20120810.ExecuteTransaction", """
{"TransactStatements":[{"Statement":"UPDATE \\"%s\\".\\"an-index\\" SET data = 'x' WHERE pk = 'qualified'"}]}
""".formatted(TABLE))
.statusCode(400)
.body("message", equalTo("Validation failed in TransactStatements[0]:"
+ " This operation is not supported on an index"));
}
@Test
@Order(16)
void theFromClauseTakesAtMostTwoNonEmptyComponents() {
statement("SELECT * FROM \"\" WHERE pk = 'x'")
.statusCode(400)
.body("message", equalTo("Path component cannot be an empty string"));
statement("SELECT * FROM \"" + TABLE + "\".\"\" WHERE pk = 'x'")
.statusCode(400)
.body("message", equalTo("Path component cannot be an empty string"));
statement("SELECT * FROM \"" + TABLE + "\".\"an-index\".\"extra\" WHERE pk = 'x'")
.statusCode(400)
.body("message", equalTo("A path may contain at most 2 components in the FROM clause"));
}
@Test
@Order(17)
void aTransactionOfSelectsReadsTheItems() {
putItem("txn-read", "\"data\":{\"S\":\"here\"}");
request("DynamoDB_20120810.ExecuteTransaction", """
{"TransactStatements":[{"Statement":"SELECT * FROM \\"%s\\" WHERE pk = 'txn-read'"}]}
""".formatted(TABLE))
.statusCode(200)
.body("Responses.size()", equalTo(1))
.body("Responses[0].Item.data.S", equalTo("here"));
request("DynamoDB_20120810.ExecuteTransaction", """
{"TransactStatements":[{"Statement":"SELECT * FROM \\"%s\\".\\"an-index\\" WHERE pk = 'txn-read'"}]}
""".formatted(TABLE))
.statusCode(400)
.body("message", equalTo("Validation failed in TransactStatements[0]:"
+ " Reads on indices are not supported within transactions."));
}
@Test
@Order(18)
void aBatchMemberCarriesTheShortErrorCode() {
putItem("batch-dup", "\"val\":{\"S\":\"here\"}");
request("DynamoDB_20120810.BatchExecuteStatement", """
{"Statements":[
{"Statement":"SLECT * FROM \\"%1$s\\" WHERE pk = 'batch-dup'"},
{"Statement":"INSERT INTO \\"%1$s\\" VALUE {'pk': 'batch-dup'}"},
{"Statement":"UPDATE \\"%1$s\\" SET touched = 'yes' WHERE pk = 'batch-dup' AND val = 'wrong'"}]}
""".formatted(TABLE))
.statusCode(200)
.body("Responses[0].Error.Code", equalTo("ValidationError"))
.body("Responses[0].Error.Message", equalTo(
"Statement wasn't well formed, can't be processed: Expected data manipulation"))
.body("Responses[0].TableName", nullValue())
.body("Responses[1].Error.Code", equalTo("DuplicateItem"))
.body("Responses[1].TableName", equalTo(TABLE))
.body("Responses[2].Error.Code", equalTo("ConditionalCheckFailed"))
.body("Responses[2].TableName", equalTo(TABLE));
}
private static void putItem(String pk, String attributes) {
request("DynamoDB_20120810.PutItem", """
{"TableName":"%s","Item":{"pk":{"S":"%s"},%s}}
""".formatted(TABLE, pk, attributes))
.statusCode(200);
}
private static ValidatableResponse statement(String partiql) {
return request("DynamoDB_20120810.ExecuteStatement",
"{\"Statement\":\"" + partiql.replace("\"", "\\\"") + "\"}");
}
private static ValidatableResponse request(String target, String body) {
return given()
.header("X-Amz-Target", target)
.contentType(CONTENT_TYPE)
.body(body)
.when()
.post("/")
.then();
}
}
@@ -5,18 +5,26 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
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.DynamoDbPartiQLParser.Seg;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbPartiQLParser.Stmt;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class DynamoDbPartiQLParserTest {
@@ -160,4 +168,105 @@ class DynamoDbPartiQLParserTest {
assertEquals("<", assertInstanceOf(Cond.Cmp.class, cond).op());
}
@Test
void parsesADocumentPathInASelectColumn() {
Stmt stmt = DynamoDbPartiQLParser.parse("SELECT a.b[2].c FROM \"t\" WHERE pk = 'p'", List.of());
Path column = assertInstanceOf(Stmt.Select.class, stmt).columns().getFirst();
assertEquals(List.of(new Seg.Name("a"), new Seg.Name("b"), new Seg.Index(2), new Seg.Name("c")),
column.segments());
assertEquals("a", column.root());
assertEquals("c", column.leafName());
}
@Test
void parsesADocumentPathInAnUpdateTarget() {
Stmt stmt = DynamoDbPartiQLParser.parse(
"UPDATE \"t\" SET profile.sub = 'x' REMOVE tags[0] WHERE pk = 'p'", List.of());
Stmt.Update update = assertInstanceOf(Stmt.Update.class, stmt);
assertEquals(List.of(new Seg.Name("profile"), new Seg.Name("sub")),
update.sets().getFirst().path().segments());
assertEquals(List.of(new Seg.Name("tags"), new Seg.Index(0)),
update.removes().getFirst().segments());
}
@Test
void keepsABareAttributeNameAsARootOnlyPath() {
Path path = assertInstanceOf(Cond.Eq.class, firstCond(SELECT + "= 'x'")).path();
assertTrue(path.isRootOnly());
assertEquals("val", path.root());
}
@Test
void parsesAnInListAsOneCondition() {
Cond.In in = assertInstanceOf(Cond.In.class, firstCond(SELECT + "IN ['a', 'b']"));
assertEquals(2, in.values().size());
assertEquals("val", in.path().root());
}
@ParameterizedTest
@CsvSource({"IS MISSING, false", "IS NOT MISSING, true"})
void parsesTheMissingPredicateWithItsNegation(String predicate, boolean negated) {
Cond.Missing missing = assertInstanceOf(Cond.Missing.class, firstCond(SELECT + predicate));
assertEquals(negated, missing.negated());
}
@Test
void parsesNotAheadOfThePredicateItNegates() {
Stmt stmt = DynamoDbPartiQLParser.parse(
"SELECT pk FROM \"t\" WHERE NOT begins_with(val, 'a')", List.of());
Cond.Not not = assertInstanceOf(Cond.Not.class,
assertInstanceOf(Stmt.Select.class, stmt).where().getFirst());
assertInstanceOf(Cond.BeginsWith.class, not.operand());
}
@Test
void parsesAGroupedOrAsASingleTopLevelCondition() {
Stmt stmt = DynamoDbPartiQLParser.parse(
"SELECT pk FROM \"t\" WHERE (pk = 'a' AND v = 1) OR (pk = 'b')", List.of());
List<Cond> where = assertInstanceOf(Stmt.Select.class, stmt).where();
assertEquals(1, where.size());
Cond.Or or = assertInstanceOf(Cond.Or.class, where.getFirst());
assertEquals(2, or.operands().size());
assertInstanceOf(Cond.And.class, or.operands().getFirst());
}
@Test
void rejectsAListIndexThatIsNotAWholeNumber() {
AwsException e = assertThrows(AwsException.class,
() -> DynamoDbPartiQLParser.parse("SELECT a[1.5] FROM \"t\" WHERE pk = 'p'", List.of()));
assertEquals("ValidationException", e.getErrorCode());
}
@Test
void rejectsAnInOperatorWithMoreThan100Operands() {
AwsException e = assertThrows(AwsException.class,
() -> DynamoDbPartiQLParser.parse("SELECT a FROM \"t\" WHERE pk IN [" + inValues(101) + "]", List.of()));
assertEquals("ValidationException", e.getErrorCode());
assertEquals("The IN operator is provided with too many operands; number of operands: 101", e.getMessage());
assertDoesNotThrow(() -> DynamoDbPartiQLParser.parse(
"SELECT a FROM \"t\" WHERE pk IN [" + inValues(100) + "]", List.of()));
}
@Test
void readsTheWholeStatementBeforeItCountsInOperands() {
AwsException e = assertThrows(AwsException.class,
() -> DynamoDbPartiQLParser.parse("SELECT a FROM \"t\" WHERE pk IN [" + inValues(101) + "] AND", List.of()));
assertEquals("ValidationException", e.getErrorCode());
assertNotEquals("The IN operator is provided with too many operands; number of operands: 101", e.getMessage());
}
private static String inValues(int count) {
return IntStream.range(0, count).mapToObj(i -> "'v" + i + "'").collect(Collectors.joining(","));
}
}
@@ -267,6 +267,14 @@ class ExpressionEvaluatorTest {
return mapper.readTree(json);
}
@Test
void orderingAgainstAnotherTypeMatchesNothing() throws Exception {
JsonNode i = item("{\"a\": {\"S\": \"5\"}}");
JsonNode v = values("{\":low\": {\"N\": \"1\"}, \":high\": {\"N\": \"9\"}}");
assertFalse(ExpressionEvaluator.matches("a > :low", i, null, v));
assertFalse(ExpressionEvaluator.matches("a BETWEEN :low AND :high", i, null, v));
}
// AND, OR, NOT logic
@Test