mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(dynamodb): scan when a PartiQL branch names the sort key twice (#8728)
* fix(dynamodb): scan when a PartiQL branch names the sort key twice * fix(dynamodb): stop at the first PartiQL branch that names the sort key twice * chore(dynamodb): keep the PartiQL two sort-key rule in one place * chore(dynamodb): test PartiQL index reads that name the index sort key twice
This commit is contained in:
1 parent
a9cb14b2ea
commit
77a4a1ff65
3 files changed
+179
-20
No files matched your search
@@ -101,11 +101,11 @@ class DynamoDbPartiQLHandler {
|
||||
Optional<List<Cond.Leaf>> sortKeyReads = routing.partition() == null
|
||||
? Optional.empty()
|
||||
: keys.sortKeyReads(descending);
|
||||
if (!stmt.orderBy().isEmpty()) {
|
||||
requireOrderByShape(stmt, accessPath, keys.readsWholeTable());
|
||||
}
|
||||
Page page;
|
||||
if (sortKeyReads.isPresent()) {
|
||||
if (!stmt.orderBy().isEmpty()) {
|
||||
requireOrderByShape(stmt, accessPath);
|
||||
}
|
||||
page = readSortKeyReads(stmt, table, accessPath, routing.partition(), sortKeyReads.get(), descending,
|
||||
startKey.get(), ctx.limit(), region);
|
||||
} else if (stmt.orderBy().isEmpty()) {
|
||||
@@ -361,7 +361,6 @@ class DynamoDbPartiQLHandler {
|
||||
|
||||
private Page readOrdered(Stmt.Select stmt, TableDefinition table, DynamoDbAccessPath accessPath,
|
||||
Routing routing, JsonNode after, Integer limit, String region) {
|
||||
requireOrderByShape(stmt, accessPath);
|
||||
List<JsonNode> rows = new ArrayList<>();
|
||||
long scannedBytes = 0;
|
||||
List<JsonNode> scannedItems = new ArrayList<>();
|
||||
@@ -388,7 +387,8 @@ class DynamoDbPartiQLHandler {
|
||||
return new Page(new ArrayList<>(rows.subList(start, end)), resumeAfter, List.of(scannedBytes), scannedItems);
|
||||
}
|
||||
|
||||
private static void requireOrderByShape(Stmt.Select stmt, DynamoDbAccessPath accessPath) {
|
||||
private static void requireOrderByShape(Stmt.Select stmt, DynamoDbAccessPath accessPath,
|
||||
boolean readsWholeTable) {
|
||||
if (stmt.where().isEmpty()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Must have WHERE clause in the statement when using ORDER BY clause.", 400);
|
||||
@@ -401,7 +401,9 @@ class DynamoDbPartiQLHandler {
|
||||
}
|
||||
}
|
||||
String pkName = accessPath.partitionKeyName();
|
||||
int hashKeyConditions = stmt.where().stream().mapToInt(c -> hashKeyConditionCount(c, pkName)).sum();
|
||||
int hashKeyConditions = readsWholeTable
|
||||
? 0
|
||||
: 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.",
|
||||
|
||||
@@ -12,6 +12,7 @@ import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -32,6 +33,7 @@ final class DynamoDbPartiQLKeyPlan {
|
||||
private final boolean everyBranchPinsPartition;
|
||||
private final List<Cond.Leaf> keyConditions = new ArrayList<>();
|
||||
private final List<Branch> branches;
|
||||
private final boolean readsWholeTable;
|
||||
private boolean tooManyBranches;
|
||||
|
||||
private record Spread(List<Cond.Leaf> keyConditions, List<Cond> filters) {
|
||||
@@ -44,11 +46,16 @@ final class DynamoDbPartiQLKeyPlan {
|
||||
}
|
||||
}
|
||||
|
||||
private record Branch(Key partition, PVal partitionValue, Range sortRange, List<Cond.Leaf> sortConditions,
|
||||
List<Cond> filters) {
|
||||
private record Branch(Key partition, PVal partitionValue, Range sortRange, List<Cond.Leaf> keyConditions,
|
||||
List<Cond.Leaf> sortConditions, List<Cond> filters) {
|
||||
|
||||
static final Comparator<Branch> IN_KEY_ORDER = Comparator.comparing(Branch::partition)
|
||||
.thenComparing(Branch::sortRange, Range.BY_LOWER);
|
||||
|
||||
// A key condition holds one sort-key condition, so a branch that names two reads the whole table.
|
||||
boolean readsWholeTable() {
|
||||
return sortConditions.size() > 1;
|
||||
}
|
||||
}
|
||||
|
||||
DynamoDbPartiQLKeyPlan(List<Cond> where, DynamoDbAccessPath accessPath, TableDefinition table) {
|
||||
@@ -59,14 +66,29 @@ final class DynamoDbPartiQLKeyPlan {
|
||||
this.everyBranchPinsPartition = everyBranchPinsPartition(conditions);
|
||||
List<Spread> spread = spread(conditions);
|
||||
this.branches = tooManyBranches
|
||||
? List.of(new Branch(null, null, Range.ALL, List.of(), where))
|
||||
? List.of(new Branch(null, null, Range.ALL, List.of(), List.of(), where))
|
||||
: spread.stream().map(this::branchOf).toList();
|
||||
this.readsWholeTable = branches.stream().anyMatch(Branch::readsWholeTable);
|
||||
}
|
||||
|
||||
/** A statement with a branch that DynamoDB cannot read by key is read as a scan of the whole table or index. */
|
||||
boolean readsWholeTable() {
|
||||
return readsWholeTable;
|
||||
}
|
||||
|
||||
void requireKeyTypesMatchSchema() {
|
||||
// Only the branches read by key check the types of their key values.
|
||||
Set<Cond.Leaf> readByKey = branches.stream()
|
||||
.filter(branch -> !branch.readsWholeTable())
|
||||
.flatMap(branch -> branch.keyConditions().stream())
|
||||
.collect(Collectors.toSet());
|
||||
for (Cond.Leaf condition : keyConditions) {
|
||||
String name = condition.path().root();
|
||||
for (PVal value : values(condition)) {
|
||||
Cond.Leaf held = condition instanceof Cond.In in ? new Cond.Eq(in.path(), value) : condition;
|
||||
if (readsWholeTable && !readByKey.contains(held)) {
|
||||
continue;
|
||||
}
|
||||
String type = DynamoDbPartiQLParser.typeCode(value);
|
||||
if (!DynamoDbPartiQLParser.ORDERED_TYPES.contains(type)) {
|
||||
throw DynamoDbPartiQLParser.validationEx(
|
||||
@@ -85,7 +107,8 @@ final class DynamoDbPartiQLKeyPlan {
|
||||
}
|
||||
|
||||
void requireReadsWithinLimit() {
|
||||
if (everyBranchPinsPartition && (tooManyBranches || branches.size() > MAX_DECOMPOSED_READS)) {
|
||||
if (everyBranchPinsPartition && !readsWholeTable
|
||||
&& (tooManyBranches || branches.size() > MAX_DECOMPOSED_READS)) {
|
||||
throw DynamoDbPartiQLParser.validationEx("Too many decomposed read operations for a given query.");
|
||||
}
|
||||
}
|
||||
@@ -215,7 +238,7 @@ final class DynamoDbPartiQLKeyPlan {
|
||||
}
|
||||
|
||||
private boolean keyed() {
|
||||
return branches.stream().allMatch(branch -> branch.partition() != null);
|
||||
return !readsWholeTable && branches.stream().allMatch(branch -> branch.partition() != null);
|
||||
}
|
||||
|
||||
private Branch branchOf(Spread spread) {
|
||||
@@ -240,8 +263,8 @@ final class DynamoDbPartiQLKeyPlan {
|
||||
}
|
||||
}
|
||||
}
|
||||
return new Branch(conflicting ? null : partition, partitionValue, sortRange, sortConditions,
|
||||
spread.filters());
|
||||
return new Branch(conflicting ? null : partition, partitionValue, sortRange, spread.keyConditions(),
|
||||
sortConditions, spread.filters());
|
||||
}
|
||||
|
||||
private List<Spread> spread(Cond cond) {
|
||||
@@ -264,20 +287,33 @@ final class DynamoDbPartiQLKeyPlan {
|
||||
yield spread;
|
||||
}
|
||||
case Cond.Or or when anyLeaf(or, this::isKeyCondition) -> {
|
||||
List<Spread> spread = or.operands().stream().flatMap(operand -> spread(operand).stream()).toList();
|
||||
tooManyBranches |= spread.size() > MAX_BRANCHES;
|
||||
yield spread;
|
||||
List<List<Spread>> operands = or.operands().stream().map(this::spread).toList();
|
||||
yield upToTheFirstScan(operands.stream().flatMap(List::stream));
|
||||
}
|
||||
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 upToTheFirstScan(left.stream().flatMap(l -> right.stream().map(l::and)));
|
||||
}
|
||||
|
||||
// DynamoDB walks the branches in written order and scans from the first one that names the sort key
|
||||
// twice, so it never reads the branches after that one by key.
|
||||
private List<Spread> upToTheFirstScan(Stream<Spread> branches) {
|
||||
List<Spread> kept = new ArrayList<>();
|
||||
for (Iterator<Spread> each = branches.iterator(); each.hasNext(); ) {
|
||||
Spread branch = each.next();
|
||||
kept.add(branch);
|
||||
if (branchOf(branch).readsWholeTable()) {
|
||||
break;
|
||||
}
|
||||
if (kept.size() > MAX_BRANCHES) {
|
||||
tooManyBranches = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return left.stream().flatMap(l -> right.stream().map(l::and)).toList();
|
||||
return kept;
|
||||
}
|
||||
|
||||
private static boolean anyLeaf(Cond cond, Predicate<Cond.Leaf> test) {
|
||||
|
||||
+121
@@ -18,6 +18,7 @@ import static io.floci.aws.testing.DynamoDbRequests.nestedMap;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.hamcrest.Matchers.empty;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
@@ -891,6 +892,126 @@ class DynamoDbPartiQLEdgeCaseIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(35)
|
||||
void readsTheWholeTableForABranchThatNamesTheSortKeyTwice() {
|
||||
String select = "SELECT sk FROM " + QUOTED_TABLE + " WHERE ";
|
||||
|
||||
statement(select + "pk='ranges' AND sk >= '1' AND sk <= '2'")
|
||||
.statusCode(200)
|
||||
.body("Items.sk.S", containsInAnyOrder("1", "2"));
|
||||
statement(select + "pk='ranges' AND ((sk >= '1' AND sk <= '2') OR sk = '1')")
|
||||
.statusCode(200)
|
||||
.body("Items.sk.S", containsInAnyOrder("1", "2"));
|
||||
statement(select + "pk='ranges' AND (sk = '1' OR flag = 'x') AND (sk = '2' OR flag = 'one')")
|
||||
.statusCode(200)
|
||||
.body("Items.sk.S", contains("1"));
|
||||
for (int count : List.of(9, 16)) {
|
||||
String pairs = IntStream.range(0, count)
|
||||
.mapToObj(n -> "(sk = 's" + n + "' OR flag = '" + n + "')")
|
||||
.collect(Collectors.joining(" AND "));
|
||||
statement(select + "pk='ranges' AND " + pairs).statusCode(200).body("Items", empty());
|
||||
}
|
||||
for (String where : List.of("pk='ranges' AND sk = '1' AND sk = '2'",
|
||||
"pk=true AND sk >= '1' AND sk <= '2'", "pk=1 AND sk >= '1' AND sk <= '2'",
|
||||
"pk='ranges' AND sk >= 1 AND sk <= '2'",
|
||||
"pk=true AND ((sk >= 'b' AND sk <= 'c') OR sk = 'a')",
|
||||
"pk=true AND (sk = 's0' OR flag = '0') AND (sk = 's1' OR flag = '1')",
|
||||
"pk='ranges' AND ((sk >= 'b' AND sk <= 'c') OR sk = 1)")) {
|
||||
statement(select + where).statusCode(200).body("Items", empty());
|
||||
}
|
||||
|
||||
statement(select + "pk='ranges' AND (sk = '1' OR flag = 'x') AND (sk = '1' OR flag = 'one')")
|
||||
.statusCode(400)
|
||||
.body("message", equalTo("Overlapping conditions with range keys are not supported in where clause"));
|
||||
for (String where : List.of("pk=true AND (sk = 'a' OR (sk >= 'b' AND sk <= 'c'))",
|
||||
"pk=true AND (flag = '0' OR sk = 's0') AND (sk = 's1' OR flag = '1')")) {
|
||||
statement(select + where)
|
||||
.statusCode(400)
|
||||
.body("message", equalTo("Key value must be of type S, N, or B. Key name: pk, Key type: BOOL"));
|
||||
}
|
||||
statement(select + "pk='ranges' AND sk >= '1' AND sk <= '2' ORDER BY sk DESC")
|
||||
.statusCode(400)
|
||||
.body("message", equalTo(
|
||||
"Must have at least one non-optional hash key condition in WHERE clause when using ORDER BY clause."));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(36)
|
||||
void readsTheWholeIndexForABranchThatNamesItsSortKeyTwice() {
|
||||
request("DynamoDB_20120810.CreateTable", """
|
||||
{
|
||||
"TableName": "partiql-edge-cases-index-sort",
|
||||
"AttributeDefinitions": [
|
||||
{"AttributeName":"pk","AttributeType":"S"},
|
||||
{"AttributeName":"sk","AttributeType":"S"},
|
||||
{"AttributeName":"g","AttributeType":"S"},
|
||||
{"AttributeName":"gs","AttributeType":"S"},
|
||||
{"AttributeName":"l","AttributeType":"S"}
|
||||
],
|
||||
"KeySchema": [
|
||||
{"AttributeName":"pk","KeyType":"HASH"},
|
||||
{"AttributeName":"sk","KeyType":"RANGE"}
|
||||
],
|
||||
"GlobalSecondaryIndexes": [{
|
||||
"IndexName": "gix",
|
||||
"KeySchema": [{"AttributeName":"g","KeyType":"HASH"},{"AttributeName":"gs","KeyType":"RANGE"}],
|
||||
"Projection": {"ProjectionType":"ALL"}
|
||||
}],
|
||||
"LocalSecondaryIndexes": [{
|
||||
"IndexName": "lix",
|
||||
"KeySchema": [{"AttributeName":"pk","KeyType":"HASH"},{"AttributeName":"l","KeyType":"RANGE"}],
|
||||
"Projection": {"ProjectionType":"ALL"}
|
||||
}],
|
||||
"BillingMode": "PAY_PER_REQUEST"
|
||||
}
|
||||
""")
|
||||
.statusCode(200);
|
||||
for (List<String> item : List.of(List.of("r1", "a", "0"), List.of("r2", "b", "1"), List.of("r3", "c", "2"))) {
|
||||
request("DynamoDB_20120810.PutItem", """
|
||||
{"TableName":"partiql-edge-cases-index-sort","Item":{"pk":{"S":"p"},"sk":{"S":"%1$s"},
|
||||
"g":{"S":"ga"},"gs":{"S":"%2$s"},"l":{"S":"%2$s"},"x":{"S":"%3$s"}}}
|
||||
""".formatted(item.get(0), item.get(1), item.get(2)))
|
||||
.statusCode(200);
|
||||
}
|
||||
String gsi = "SELECT sk FROM \"partiql-edge-cases-index-sort\".\"gix\" WHERE ";
|
||||
String lsi = "SELECT sk FROM \"partiql-edge-cases-index-sort\".\"lix\" WHERE ";
|
||||
|
||||
statement(gsi + "g = 'ga' AND gs >= 'a' AND gs <= 'b'")
|
||||
.statusCode(200)
|
||||
.body("Items.sk.S", containsInAnyOrder("r1", "r2"));
|
||||
statement(lsi + "pk = 'p' AND l >= 'a' AND l <= 'b'")
|
||||
.statusCode(200)
|
||||
.body("Items.sk.S", containsInAnyOrder("r1", "r2"));
|
||||
for (String select : List.of(gsi + "g = 1 AND gs >= 'a' AND gs <= 'b'",
|
||||
gsi + "g = 'ga' AND (gs = 'a' OR x = '0') AND (gs = 'b' OR x = '1')",
|
||||
lsi + "pk = 1 AND l >= 'a' AND l <= 'b'",
|
||||
lsi + "pk = 'p' AND (l = 'a' OR x = '0') AND (l = 'b' OR x = '1')")) {
|
||||
statement(select).statusCode(200).body("Items", empty());
|
||||
}
|
||||
|
||||
for (String select : List.of(gsi + "g = 1 AND gs >= 'a'", gsi + "g = 1 AND sk >= 'r1' AND sk <= 'r2'")) {
|
||||
statement(select)
|
||||
.statusCode(400)
|
||||
.body("message", equalTo("Key attribute's data type should match its data type in table's schema: Key g"));
|
||||
}
|
||||
for (String select : List.of(lsi + "pk = 1 AND l >= 'a'", lsi + "pk = 1 AND sk >= 'r1' AND sk <= 'r2'")) {
|
||||
statement(select)
|
||||
.statusCode(400)
|
||||
.body("message", equalTo("Key attribute's data type should match its data type in table's schema: Key pk"));
|
||||
}
|
||||
statement(gsi + "g = 'ga' AND (gs = 'a' OR x = '0') AND (gs = 'a' OR x = '1')")
|
||||
.statusCode(400)
|
||||
.body("message", equalTo("Overlapping conditions with range keys are not supported in where clause"));
|
||||
for (String select : List.of(gsi + "g = 'ga' AND gs >= 'a' AND gs <= 'b' ORDER BY gs DESC",
|
||||
lsi + "pk = 'p' AND l >= 'a' AND l <= 'b' ORDER BY l DESC")) {
|
||||
statement(select)
|
||||
.statusCode(400)
|
||||
.body("message", equalTo(
|
||||
"Must have at least one non-optional hash key condition in WHERE clause when using ORDER BY clause."));
|
||||
}
|
||||
}
|
||||
|
||||
private static void putItem(String pk, String attributes) {
|
||||
putItem(pk, "1", attributes);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user