From a102cd16d5c6cbfb9d1c9ecfb8770b14300838c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?TATSUNO=20=E2=80=9CTaz=E2=80=9D=20Yasuhiro?= Date: Sat, 7 Nov 2026 15:32:20 +0900 Subject: [PATCH] fix(dynamodb): check the operands of a PartiQL condition function (#7726) --- .../dynamodb/DynamoDbPartiQLParser.java | 333 +++++++++++------- .../DynamoDbPartiQLIntegrationTest.java | 22 ++ .../dynamodb/DynamoDbPartiQLParserTest.java | 215 +++++++++++ 3 files changed, 446 insertions(+), 124 deletions(-) diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLParser.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLParser.java index 83b4d960b2..945823dff2 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLParser.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLParser.java @@ -8,6 +8,7 @@ import java.math.BigInteger; import java.math.MathContext; import java.math.RoundingMode; import java.util.*; +import java.util.stream.Collectors; import java.util.stream.Stream; public class DynamoDbPartiQLParser { @@ -59,6 +60,15 @@ public class DynamoDbPartiQLParser { } return name.toString(); } + + String display() { + return segments.stream() + .map(segment -> switch (segment) { + case Seg.Name name -> name.value(); + case Seg.Index index -> "[" + index.value() + "]"; + }) + .collect(Collectors.joining(", ", "[", "]")); + } } public enum Returning { @@ -471,6 +481,8 @@ public class DynamoDbPartiQLParser { private String fromClauseError; // DynamoDB reports these only once the whole statement parses, and the first one in the statement wins. private String deferredError; + // DynamoDB checks operands once it has read every term, and the first one in the statement wins. + private String expressionError; private DynamoDbPartiQLParser(String statement, List parameters) { this.statement = statement; @@ -503,16 +515,9 @@ public class DynamoDbPartiQLParser { if (parser.deferredError != null) { throw validationEx(parser.deferredError); } - stmt.where().stream() - .flatMap(DynamoDbPartiQLParser::leaves) - .filter(Cond.In.class::isInstance) - .map(Cond.In.class::cast) - .filter(in -> in.values().size() > MAX_IN_OPERANDS) - .findFirst() - .ifPresent(in -> { - throw validationEx("The IN operator is provided with too many operands; number of operands: " - + in.values().size()); - }); + if (parser.expressionError != null) { + throw validationEx(parser.expressionError); + } if (stmt instanceof Stmt.Delete delete && delete.returning() != Returning.NONE && delete.returning() != Returning.ALL_OLD) { throw validationEx("Invalid returning clause: " + delete.returning().clause() @@ -715,7 +720,8 @@ public class DynamoDbPartiQLParser { if (peekCall()) { Token name = advance(); defer("Unexpected path component at " + position(name)); - return parseCall(name, false); + parseCall(name, false); + return PATH_STAND_IN; } return parsePath(); } @@ -802,11 +808,10 @@ public class DynamoDbPartiQLParser { Target target = parseTarget(); Edits edits = parseEdits(); // DynamoDB checks the WHERE clause before the SET values. - String setError = deferredError; - deferredError = null; + String setError = takeError(); consume(TType.WHERE); List where = parseConditions(); - defer(setError); + deferExpression(setError); return new Stmt.Update(target.table(), target.index(), edits.sets(), edits.removes(), where, parseReturning()); } @@ -817,7 +822,11 @@ public class DynamoDbPartiQLParser { Target target = parseTarget(); List where = List.of(); if (peek().type() == TType.WHERE) { advance(); where = parseConditions(); } + String whereError = takeError(); Edits edits = parseEdits(); + String setError = takeError(); + deferExpression(whereError); + deferExpression(setError); return new Stmt.Update(target.table(), target.index(), edits.sets(), edits.removes(), where, parseReturning()); } @@ -1031,9 +1040,6 @@ public class DynamoDbPartiQLParser { private static final Set COMPARISONS = EnumSet.of(TType.EQ, TType.NE, TType.LT, TType.LE, TType.GT, TType.GE); - private static final List PREDICATE_FUNCTIONS = - List.of("begins_with", "contains", "attribute_type", "attribute_exists", "attribute_not_exists"); - private Cond parseComparison() { if (peek().type() == TType.BOOL && (tokens.get(pos + 1).type() == TType.EQ || tokens.get(pos + 1).type() == TType.NE)) { @@ -1045,7 +1051,8 @@ public class DynamoDbPartiQLParser { } Cond cond = parseCond(); if (peek().type() == TType.BETWEEN) { - throw incorrectOperandType("BETWEEN", "BOOL"); + deferExpression(incorrectOperandType("BETWEEN", "BOOL")); + return parsePredicate(PATH_STAND_IN, peek()); } if (peek().type() == TType.IN) { advance(); @@ -1067,7 +1074,7 @@ public class DynamoDbPartiQLParser { String op = parseOp(); requireRightHandSide(); if (!"=".equals(op) && !"<>".equals(op)) { - throw incorrectOperandType(op, "BOOL"); + deferExpression(incorrectOperandType(op, "BOOL")); } Cond equal = conditionEquals(cond); return "=".equals(op) ? equal : new Cond.Not(equal); @@ -1110,18 +1117,14 @@ public class DynamoDbPartiQLParser { } private void requireOrdered(String op, PVal val) { - if (!literalErrorPending() && !ORDERED_TYPES.contains(typeCode(val))) { - throw incorrectOperandType(op, val); + if (!ORDERED_TYPES.contains(typeCode(val))) { + deferExpression(incorrectOperandType(op, typeCode(val))); } } - private static AwsException incorrectOperandType(String op, PVal val) { - return incorrectOperandType(op, typeCode(val)); - } - - private static AwsException incorrectOperandType(String op, String type) { - return validationEx("Incorrect operand type for operator or function; " - + "operator or function: " + op + ", operand type: " + type); + private static String incorrectOperandType(String op, String type) { + return "Incorrect operand type for operator or function; " + + "operator or function: " + op + ", operand type: " + type; } private Cond parseCond() { @@ -1131,65 +1134,14 @@ public class DynamoDbPartiQLParser { consume(TType.RPAREN); return grouped; } - if (peek().type() == TType.IDENT && "begins_with".equalsIgnoreCase(peek().value())) { - advance(); - consume(TType.LPAREN); - Path path = parsePath(); - consume(TType.COMMA); - PVal prefix = parseValue(); - consume(TType.RPAREN); - return new Cond.BeginsWith(path, prefix); - } - if (peekFunction("contains")) { - advance(); - consume(TType.LPAREN); - Path path = parsePath(); - consume(TType.COMMA); - PVal operand = parseValue(); - consume(TType.RPAREN); - return new Cond.Contains(path, operand); - } - if (peekFunction("attribute_type")) { - advance(); - consume(TType.LPAREN); - Path path = parsePath(); - consume(TType.COMMA); - PVal type = parseValue(); - consume(TType.RPAREN); - requireAttributeTypeName(type); - return new Cond.AttributeType(path, type); - } - if (peekFunction("attribute_exists") || peekFunction("attribute_not_exists")) { - boolean exists = "attribute_exists".equalsIgnoreCase(advance().value()); - consume(TType.LPAREN); - Path path = parsePath(); - consume(TType.RPAREN); - return new Cond.Missing(path, exists); - } - if (peekFunction("size")) { - advance(); - consume(TType.LPAREN); - Path path = parsePath(); - consume(TType.RPAREN); - String op = parseOp(); - requireRightHandSide(); - PVal val = parseValue(); - if (!"=".equals(op) && !"<>".equals(op)) { - requireOrdered(op, val); - } - return new Cond.SizeCmp(path, op, val); + if (peekCall()) { + return parseCallCondition(); } Token operand = peek(); - boolean call = peekCall(); - Path path = call ? parseCall(advance(), false) : parsePath(); - if (call && !CALL_PREDICATES.contains(peek().type())) { - if (COMPARISONS.contains(peek().type())) { - advance(); - requireRightHandSide(); - parseCallArgument(false); - } - return new Cond.Missing(path, false); - } + return parsePredicate(parsePath(), operand); + } + + private Cond parsePredicate(Path path, Token operand) { if (peek().type() == TType.BETWEEN) { advance(); requireRightHandSide(); @@ -1215,6 +1167,10 @@ public class DynamoDbPartiQLParser { values.add(parseValue()); } consume(TType.RBRACKET); + if (MAX_IN_OPERANDS < values.size()) { + deferExpression("The IN operator is provided with too many operands; number of operands: " + + values.size()); + } return new Cond.In(path, List.copyOf(values)); } if (peek().type() == TType.IS) { @@ -1248,8 +1204,6 @@ public class DynamoDbPartiQLParser { && tokens.get(pos + 1).type() == TType.LPAREN; } - private static final Set CALL_PREDICATES = EnumSet.of(TType.BETWEEN, TType.IN, TType.IS); - private static final Set AGGREGATE_FUNCTIONS = Set.of("avg", "count", "max", "min", "sum"); private static final Set KEYWORD_FUNCTIONS = Set.of("avg", "bit_length", "char_length", "character_length", @@ -1265,11 +1219,82 @@ public class DynamoDbPartiQLParser { && (!isKeyword(name) || KEYWORD_FUNCTIONS.contains(name.value().toLowerCase(Locale.ROOT))); } - // The path only stands in for the call. A call always fails the statement, or the call around it does. - private Path parseCall(Token name, boolean update) { + private static final Map CONDITION_FUNCTION_OPERANDS = Map.of("attribute_exists", 1, + "attribute_not_exists", 1, "size", 1, "attribute_type", 2, "begins_with", 2, "contains", 2); + + private static final Set TYPES_WITHOUT_SIZE = Set.of("N", "BOOL", "NULL"); + + private static final Set BEGINS_WITH_TYPES = Set.of("S", "B"); + + // Stands in for a term of a statement DynamoDB refuses, so the statement can be read to its end. + private static final Path PATH_STAND_IN = new Path(List.of(new Seg.Name("call"))); + + // A path has no type. A call has a type, and no value Floci can read. + private record Argument(Token start, Path path, PVal value, String type) {} + + private Cond parseCallCondition() { + Token name = advance(); + String function = name.value().toLowerCase(Locale.ROOT); + List operands = parseCall(name, false); + if (peek().type() == TType.IS) { + return parsePredicate(PATH_STAND_IN, name); + } + boolean refused = errorPending(); + if ("size".equals(function)) { + return parseSizeComparison(refused ? PATH_STAND_IN : conditionPath(operands.getFirst())); + } + if (refused) { + if (COMPARISONS.contains(peek().type())) { + advance(); + requireRightHandSide(); + parseCallArgument(false); + } + return new Cond.Missing(PATH_STAND_IN, false); + } + Path path = conditionPath(operands.getFirst()); + return switch (function) { + case "attribute_exists" -> new Cond.Missing(path, true); + case "attribute_not_exists" -> new Cond.Missing(path, false); + case "begins_with" -> new Cond.BeginsWith(path, conditionValue(operands.getLast())); + case "contains" -> new Cond.Contains(path, conditionValue(operands.getLast())); + default -> new Cond.AttributeType(path, conditionValue(operands.getLast())); + }; + } + + // DynamoDB also takes a literal here, which Floci cannot evaluate. + private Path conditionPath(Argument operand) { + if (operand.path() == null) { + deferExpression("Expected identifier, got: '" + operand.start().value() + "'"); + } + return operand.path(); + } + + // DynamoDB also takes a path or a call here, which Floci cannot evaluate. + private PVal conditionValue(Argument operand) { + if (operand.value() == null) { + deferExpression("Expected value literal or ?, got: " + operand.start().value()); + } + return operand.value(); + } + + private Cond parseSizeComparison(Path path) { + if (!COMPARISONS.contains(peek().type())) { + deferExpression("Expected comparison operator, got: " + peek().value()); + return new Cond.Missing(path, false); + } + String op = parseOp(); + requireRightHandSide(); + PVal val = parseValue(); + if (!"=".equals(op) && !"<>".equals(op)) { + requireOrdered(op, val); + } + return new Cond.SizeCmp(path, op, val); + } + + private List parseCall(Token name, boolean update) { String function = name.value().toLowerCase(Locale.ROOT); String errorBeforeCall = deferredError; - parseCallArguments(name, update); + List arguments = parseCallArguments(name, update); String shapeError = callShapeError(name, addPathSteps(new ArrayList<>())); if (shapeError != null) { deferredError = errorBeforeCall; @@ -1279,8 +1304,51 @@ public class DynamoDbPartiQLParser { + " expression; function: " + function); } else if (!isFunctionOf(update, function)) { defer("Unrecognized function: " + function + " at " + position(name)); + } else if (!update) { + checkOperands(function, arguments); + } + return arguments; + } + + private void checkOperands(String function, List operands) { + if (operands.size() != CONDITION_FUNCTION_OPERANDS.get(function)) { + deferExpression("Incorrect number of operands for operator or function; operator or function: " + + function + ", number of operands: " + operands.size()); + return; + } + Argument first = operands.getFirst(); + Argument last = operands.getLast(); + switch (function) { + case "attribute_exists", "attribute_not_exists" -> { + if (first.path() == null) { + deferExpression("Operator or function requires a document path; operator or function: " + + function); + } + } + case "size" -> { + if (first.type() != null && TYPES_WITHOUT_SIZE.contains(first.type())) { + deferExpression(incorrectOperandType(function, first.type())); + } + } + default -> { + if (first.path() != null && first.path().equals(last.path())) { + deferExpression("The first operand must be distinct from the remaining operands for this " + + "operator or function; operator: " + function + ", first operand: " + + first.path().display()); + } + if ("begins_with".equals(function)) { + operands.forEach(this::requireBeginsWithType); + } else if ("attribute_type".equals(function)) { + requireAttributeTypeName(last); + } + } + } + } + + private void requireBeginsWithType(Argument operand) { + if (operand.type() != null && !BEGINS_WITH_TYPES.contains(operand.type())) { + deferExpression(incorrectOperandType("begins_with", operand.type())); } - return new Path(List.of(new Seg.Name(name.value()))); } // DynamoDB reports these before it looks at the arguments. @@ -1299,12 +1367,13 @@ public class DynamoDbPartiQLParser { private static boolean isFunctionOf(boolean update, String function) { return update ? "list_append".equals(function) - : "size".equals(function) || PREDICATE_FUNCTIONS.contains(function); + : CONDITION_FUNCTION_OPERANDS.containsKey(function); } - private void parseCallArguments(Token name, boolean update) { + private List parseCallArguments(Token name, boolean update) { String function = name.value().toLowerCase(Locale.ROOT); boolean aggregate = AGGREGATE_FUNCTIONS.contains(function); + List arguments = new ArrayList<>(); consume(TType.LPAREN); if (isStar(peek())) { if (!"count".equals(function)) { @@ -1315,10 +1384,10 @@ public class DynamoDbPartiQLParser { if (aggregate && (isWord(peek(), "DISTINCT") || peek().type() == TType.ALL)) { advance(); } - parseCallArgument(update); + arguments.add(parseCallArgument(update)); while (peek().type() == TType.COMMA) { advance(); - parseCallArgument(update); + arguments.add(parseCallArgument(update)); } } else if (aggregate) { throw validationEx(NOT_WELL_FORMED + "Aggregate functions are always unary"); @@ -1327,16 +1396,20 @@ public class DynamoDbPartiQLParser { throw validationEx(NOT_WELL_FORMED + "Expected RIGHT_PAREN"); } advance(); + return arguments; } - private void parseCallArgument(boolean update) { + private Argument parseCallArgument(boolean update) { + Token start = peek(); if (peekCall()) { parseCall(advance(), update); - } else if (peek().type() == TType.IDENT) { - parsePath(); - } else { - parseValue(); + return new Argument(start, null, null, "size".equalsIgnoreCase(start.value()) ? "N" : "BOOL"); } + if (start.type() == TType.IDENT) { + return new Argument(start, parsePath(), null, null); + } + PVal value = parseValue(); + return new Argument(start, null, value, typeCode(value)); } private static final Map TYPE_NAMES = Map.ofEntries( @@ -1492,15 +1565,14 @@ public class DynamoDbPartiQLParser { private static final List ATTRIBUTE_TYPE_NAMES = List.of("N", "BS", "L", "B", "NULL", "M", "S", "SS", "NS", "BOOL"); - private void requireAttributeTypeName(PVal type) { - if (literalErrorPending()) { + private void requireAttributeTypeName(Argument operand) { + if (operand.type() == null) { return; } - if (!(type instanceof PVal.Str name)) { - throw incorrectOperandType("attribute_type", type); - } - if (!ATTRIBUTE_TYPE_NAMES.contains(name.v())) { - throw validationEx("Invalid attribute type name found; type: " + name.v() + if (!(operand.value() instanceof PVal.Str name)) { + deferExpression(incorrectOperandType("attribute_type", operand.type())); + } else if (!ATTRIBUTE_TYPE_NAMES.contains(name.v())) { + deferExpression("Invalid attribute type name found; type: " + name.v() + ", valid types: {" + String.join(",", ATTRIBUTE_TYPE_NAMES) + "}"); } } @@ -1534,8 +1606,8 @@ public class DynamoDbPartiQLParser { } private void requireNumberLiteral(String op, Operand operand) { - if (!literalErrorPending() && operand instanceof Operand.Value value && !(value.val() instanceof PVal.Num)) { - throw incorrectOperandType(op, value.val()); + if (operand instanceof Operand.Value value && !(value.val() instanceof PVal.Num)) { + deferExpression(incorrectOperandType(op, typeCode(value.val()))); } } @@ -1544,16 +1616,14 @@ public class DynamoDbPartiQLParser { String name = function.value().toUpperCase(Locale.ROOT); consume(TType.LPAREN); Token firstArgument = peek(); - if (!parsePath().equals(target) && !literalErrorPending()) { - throw validationEx("The first argument to " + name + " must equal the assignment value at " - + position(function)); + if (!parsePath().equals(target)) { + defer("The first argument to " + name + " must equal the assignment value at " + position(function)); } consume(TType.COMMA); PVal bag = parseValue(); consume(TType.RPAREN); - if (!SET_TYPES.contains(typeCode(bag)) && !literalErrorPending()) { - throw validationEx("The second argument to " + name + " must be a value with type SET at " - + position(firstArgument)); + if (!SET_TYPES.contains(typeCode(bag))) { + defer("The second argument to " + name + " must be a value with type SET at " + position(firstArgument)); } return "set_add".equalsIgnoreCase(function.value()) ? new SetAdd(target, bag) : new SetDelete(target, bag); } @@ -1629,7 +1699,7 @@ public class DynamoDbPartiQLParser { long index = Long.parseLong(t.value()); if (index < 0 || index > Integer.MAX_VALUE) { int sign = index < 0 ? 1 : 0; - throw validationEx("List index is not within the allowable range; index: [" + t.value() + "] at " + defer("List index is not within the allowable range; index: [" + t.value() + "] at " + position(t.start() + sign, t.value().length() - sign)); } return index; @@ -1704,18 +1774,21 @@ public class DynamoDbPartiQLParser { private PVal parseCallValue(Token name, OpenCollection parent, String path) { String expectedValue = "Expected value literal or ?, got: " + name.value(); - if (!isCall(pos - 1)) { + if (name.type() != TType.IDENT) { throw validationEx(expectedValue); } + if (!isCall(pos - 1)) { + addPathSteps(new ArrayList<>()); + deferExpression(expectedValue); + return new PVal.Null(); + } if (parent != null) { boolean firstInBag = parent.close == TType.RBAG && parent.items.isEmpty(); defer((firstInBag ? BAG_MEMBER_TYPES : "Unsupported data type: Call under key " + path) + " at " + position(name)); } parseCall(name, false); - if (!literalErrorPending()) { - throw validationEx(expectedValue); - } + deferExpression(expectedValue); return new PVal.Null(); } @@ -1834,15 +1907,14 @@ public class DynamoDbPartiQLParser { if (bag.invalid) { return REFUSED_BAG; } - if (!literalErrorPending()) { + if (deferredError == null) { checkDistinctMembers(bag.memberType, bag.items); } return new PVal.Bag(bag.memberType + "S", List.copyOf(bag.items)); } - // DynamoDB checks operand types only after the FROM clause and every literal, so an error in either wins. - private boolean literalErrorPending() { - return fromClauseError != null || deferredError != null; + private boolean errorPending() { + return fromClauseError != null || deferredError != null || expressionError != null; } private void defer(String message) { @@ -1851,6 +1923,19 @@ public class DynamoDbPartiQLParser { } } + private void deferExpression(String message) { + if (expressionError == null) { + expressionError = message; + } + } + + private String takeError() { + String error = deferredError != null ? deferredError : expressionError; + deferredError = null; + expressionError = null; + return error; + } + private void checkDistinctMembers(String memberType, List members) { boolean numbers = memberType.equals("N"); List texts = members.stream() diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLIntegrationTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLIntegrationTest.java index 3862c03be0..e99055d27a 100644 --- a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLIntegrationTest.java @@ -758,6 +758,28 @@ class DynamoDbPartiQLIntegrationTest { .body("message", equalTo("Unsupported data type: foo under key root at 1:" + (insert.length() + 1) + ":3")); } + @Test + @Order(36) + void aConditionFunctionChecksItsOperands() { + String where = "SELECT * FROM \"" + TABLE + "\" WHERE "; + statement(where + "attribute_exists()") + .statusCode(400) + .body("message", equalTo("Incorrect number of operands for operator or function; " + + "operator or function: attribute_exists, number of operands: 0")); + statement(where + "attribute_exists('a')") + .statusCode(400) + .body("message", equalTo("Operator or function requires a document path; " + + "operator or function: attribute_exists")); + statement(where + "size(1) = 1") + .statusCode(400) + .body("message", equalTo("Incorrect operand type for operator or function; " + + "operator or function: size, operand type: N")); + statement(where + "contains(a, a)") + .statusCode(400) + .body("message", equalTo("The first operand must be distinct from the remaining operands for this " + + "operator or function; operator: contains, first operand: [a]")); + } + private static void putItem(String pk, String attributes) { request("DynamoDB_20120810.PutItem", """ {"TableName":"%s","Item":{"pk":{"S":"%s"},%s}} diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLParserTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLParserTest.java index e0883436ce..8d00070beb 100644 --- a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLParserTest.java +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLParserTest.java @@ -501,6 +501,221 @@ class DynamoDbPartiQLParserTest { assertEquals("Expected value literal or ?, got: size", e.getMessage()); } + @ParameterizedTest + @CsvSource(delimiter = '|', quoteCharacter = '`', textBlock = """ + attribute_exists() | attribute_exists | 0 + ATTRIBUTE_EXISTS(a, b) | attribute_exists | 2 + "attribute_not_exists"() | attribute_not_exists | 0 + attribute_exists('x', 'y') | attribute_exists | 2 + attribute_exists(?, ?, 1) | attribute_exists | 3 + a = 1 AND size() | size | 0 + size(a, b) = 1 | size | 2 + size() < true | size | 0 + size() IN [1] | size | 0 + size() BETWEEN 1 AND 2 | size | 0 + begins_with(a) | begins_with | 1 + contains(a, b, c) | contains | 3 + attribute_type() | attribute_type | 0 + NOT attribute_exists() | attribute_exists | 0 + (attribute_exists()) | attribute_exists | 0 + a = 'x' OR attribute_exists() | attribute_exists | 0 + a = attribute_exists() | attribute_exists | 0 + a = size() | size | 0 + a IN [attribute_exists()] | attribute_exists | 0 + attribute_exists() < 1 | attribute_exists | 0 + attribute_exists() BETWEEN 1 AND 2 | attribute_exists | 0 + attribute_exists() = attribute_exists() | attribute_exists | 0 + attribute_exists(size()) | size | 0 + attribute_exists(size(), size()) | size | 0 + begins_with(size(), 'x') | size | 0 + """) + void refusesTheWrongNumberOfOperands(String condition, String function, int operands) { + assertEquals("Incorrect number of operands for operator or function; operator or function: " + function + + ", number of operands: " + operands, refusal(condition, 2)); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', quoteCharacter = '`', textBlock = """ + attribute_exists('x') | attribute_exists + attribute_exists(?) | attribute_exists + attribute_not_exists(1) | attribute_not_exists + attribute_exists(true) | attribute_exists + attribute_exists(null) | attribute_exists + attribute_exists([1]) | attribute_exists + attribute_exists({'x': 1}) | attribute_exists + attribute_exists(<<'x'>>) | attribute_exists + attribute_not_exists(size(a)) | attribute_not_exists + attribute_exists(attribute_exists(a)) | attribute_exists + attribute_exists(attribute_exists(1), attribute_exists()) | attribute_exists + a = attribute_exists(1) | attribute_exists + attribute_exists(a) = attribute_exists('x') | attribute_exists + """) + void requiresADocumentPath(String condition, String function) { + assertEquals("Operator or function requires a document path; operator or function: " + function, + refusal(condition, 1)); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', quoteCharacter = '`', textBlock = """ + size(1) = 1 | size | N + a = 1 AND size(1) | size | N + size(-1) = 1 | size | N + size(true) = 1 | size | BOOL + size(null) = 1 | size | NULL + size(size(a)) = 1 | size | N + size(attribute_exists(a))=1 | size | BOOL + a < size(1) | size | N + a IN [size(1)] | size | N + a BETWEEN size(1) AND 2 | size | N + contains(size(1), 'x') | size | N + attribute_exists(size(1)) | size | N + begins_with(a, 1) | begins_with | N + begins_with(1, 'x') | begins_with | N + begins_with('x', 1) | begins_with | N + begins_with(1, true) | begins_with | N + begins_with(true, 1) | begins_with | BOOL + begins_with(1, a) | begins_with | N + begins_with(null, 'x') | begins_with | NULL + begins_with(a, [1]) | begins_with | L + begins_with(a, {'x': 1}) | begins_with | M + begins_with(a, <<'x'>>) | begins_with | SS + begins_with(a, size(a)) | begins_with | N + attribute_type(a, 1) | attribute_type | N + attribute_type(1, 1) | attribute_type | N + attribute_type(true, true) | attribute_type | BOOL + attribute_type(a, null) | attribute_type | NULL + attribute_type(a, [1]) | attribute_type | L + attribute_type(a, size(a)) | attribute_type | N + """) + void refusesAnOperandOfTheWrongType(String condition, String function, String type) { + assertEquals("Incorrect operand type for operator or function; operator or function: " + function + + ", operand type: " + type, refusal(condition, 0)); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', quoteCharacter = '`', textBlock = """ + contains(a, a) | contains | [a] + contains("a", a) | contains | [a] + begins_with(m.a, m.a) | begins_with | [m, a] + begins_with(m."a".b, m.a.b) | begins_with | [m, a, b] + attribute_type(a, a) | attribute_type | [a] + attribute_type(l[0].a, l[0].a) | attribute_type | [l, [0], a] + contains(m."x y", m."x y") | contains | [m, x y] + """) + void refusesTheSamePathAsBothOperands(String condition, String function, String path) { + assertEquals("The first operand must be distinct from the remaining operands for this operator or function; " + + "operator: " + function + ", first operand: " + path, refusal(condition, 0)); + } + + private String refusal(String condition, int parameters) { + List values = IntStream.range(0, parameters).mapToObj(i -> json("{\"S\":\"x\"}")).toList(); + AwsException e = assertThrows(AwsException.class, + () -> DynamoDbPartiQLParser.parse("SELECT * FROM \"t\" WHERE " + condition, values)); + return e.getMessage(); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', quoteCharacter = '`', textBlock = """ + SELECT * FROM "t" WHERE foo(1) AND attribute_exists() | Unrecognized function: foo at 1:25:3 + SELECT * FROM "t" WHERE attribute_exists() AND foo(1) | Unrecognized function: foo at 1:48:3 + SELECT * FROM "t" WHERE attribute_exists(foo(1)) | Unrecognized function: foo at 1:42:3 + SELECT * FROM "t" WHERE attribute_exists(foo(1), size()) | Unrecognized function: foo at 1:42:3 + SELECT * FROM "t" WHERE size(foo(1)) = 1 | Unrecognized function: foo at 1:30:3 + SELECT * FROM "t" WHERE foo(size(1)) | Unrecognized function: foo at 1:25:3 + SELECT * FROM "t" WHERE foo(attribute_exists()) | Unrecognized function: foo at 1:25:3 + SELECT * FROM "t" WHERE attribute_exists(<<>>) | Empty bags are not supported + SELECT * FROM "t" WHERE attribute_exists() AND a = <<>> | Empty bags are not supported + SELECT * FROM "t" WHERE a < true AND foo(1) | Unrecognized function: foo at 1:38:3 + SELECT * FROM "t" WHERE a < true AND a = <<>> | Empty bags are not supported + SELECT * FROM "t" WHERE begins_with(a, 1) AND foo(1) | Unrecognized function: foo at 1:47:3 + SELECT * FROM "t" WHERE attribute_type(a, 1) AND foo(1) | Unrecognized function: foo at 1:50:3 + SELECT * FROM "t" WHERE attribute_type(a, 'BAD') AND foo(1) | Unrecognized function: foo at 1:54:3 + SELECT * FROM "t" WHERE attribute_exists(a) < 1 AND foo(1) | Unrecognized function: foo at 1:53:3 + SELECT * FROM "t" WHERE attribute_exists(a) BETWEEN 1 AND 2 AND foo(1) | Unrecognized function: foo at 1:65:3 + SELECT * FROM "t" WHERE a BETWEEN true AND 2 AND foo(1) | Unrecognized function: foo at 1:50:3 + SELECT * FROM "t" WHERE a < true AND m[99999999999] = 1 | List index is not within the allowable range; index: [99999999999] at 1:40:11 + SELECT * FROM "t" WHERE attribute_exists() AND m[-1] = 1 | List index is not within the allowable range; index: [-1] at 1:51:1 + SELECT * FROM "t" WHERE m[99999999999] = 1 AND foo(1) | List index is not within the allowable range; index: [99999999999] at 1:27:11 + SELECT * FROM "t" WHERE foo(1) AND m[99999999999] = 1 | Unrecognized function: foo at 1:25:3 + SELECT * FROM "t" WHERE a = <<>> AND m[99999999999] = 1 | Empty bags are not supported + SELECT * FROM "t" WHERE foo(l[99999999999]) | List index is not within the allowable range; index: [99999999999] at 1:31:11 + SELECT l[99999999999] FROM "t" WHERE foo(1) | List index is not within the allowable range; index: [99999999999] at 1:10:11 + SELECT foo(1), l[99999999999] FROM "t" | Unexpected path component at 1:8:3 + SELECT * FROM "t" WHERE foo(1) AND a = b | Unrecognized function: foo at 1:25:3 + SELECT * FROM "t" WHERE a = m.b AND foo(1) | Unrecognized function: foo at 1:37:3 + SELECT * FROM "t" WHERE a = l[99999999999] | List index is not within the allowable range; index: [99999999999] at 1:31:11 + SELECT * FROM "t" WHERE attribute_exists() IS NULL | The left hand side argument to IS must be a Variable Reference, Literal, or Path + SELECT * FROM "t" WHERE size(1) IS NULL | The left hand side argument to IS must be a Variable Reference, Literal, or Path + SELECT * FROM "t" WHERE attribute_exists(a) IS NULL | The left hand side argument to IS must be a Variable Reference, Literal, or Path + SELECT * FROM "t" WHERE attribute_exists().a = 1 | Unexpected path component at 1:25:16 + SELECT * FROM "t" WHERE size(a)[0] = 1 | Unexpected path component at 1:25:4 + SELECT * FROM a.b.c WHERE attribute_exists() | A path may contain at most 2 components in the FROM clause + SELECT * FROM a.b.c WHERE a < true | A path may contain at most 2 components in the FROM clause + SELECT * FROM a.b.c WHERE m[99999999999] = 1 | A path may contain at most 2 components in the FROM clause + """) + void reportsTheOperandChecksLast(String statement, String message) { + AwsException e = assertThrows(AwsException.class, () -> DynamoDbPartiQLParser.parse(statement, List.of())); + + assertEquals(message, e.getMessage()); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', quoteCharacter = '`', textBlock = """ + attribute_exists('x') AND a < true | Operator or function requires a document path; operator or function: attribute_exists + a < true AND b = c | Incorrect operand type for operator or function; operator or function: <, operand type: BOOL + a < true AND attribute_exists('x') | Incorrect operand type for operator or function; operator or function: <, operand type: BOOL + attribute_exists() AND begins_with(a, a) | Incorrect number of operands for operator or function; operator or function: attribute_exists, number of operands: 0 + begins_with(a, a) AND attribute_exists() | The first operand must be distinct from the remaining operands for this operator or function; operator: begins_with, first operand: [a] + attribute_exists(a) < 1 AND size() | Incorrect operand type for operator or function; operator or function: <, operand type: BOOL + size() AND attribute_exists(a) < 1 | Incorrect number of operands for operator or function; operator or function: size, number of operands: 0 + attribute_type(a, 1) AND size() | Incorrect operand type for operator or function; operator or function: attribute_type, operand type: N + """) + void reportsTheFirstOperandCheckInTheStatement(String condition, String message) { + assertEquals(message, refusal(condition, 0)); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', quoteCharacter = '`', textBlock = """ + UPDATE "t" SET l[99999999999] = 1 WHERE foo(1) | Unrecognized function: foo at 1:41:3 + UPDATE "t" REMOVE l[99999999999] WHERE attribute_exists() | Incorrect number of operands for operator or function; operator or function: attribute_exists, number of operands: 0 + UPDATE "t" SET a = foo(1) WHERE a < true | Incorrect operand type for operator or function; operator or function: <, operand type: BOOL + UPDATE "t" SET a = size(b) WHERE attribute_exists('x') | Operator or function requires a document path; operator or function: attribute_exists + UPDATE "t" SET a = 'x' + 1 WHERE foo(1) | Unrecognized function: foo at 1:34:3 + UPDATE "t" SET a = 'x' + 1, b = foo(1) WHERE pk = 1 | Unrecognized function: foo at 1:33:3 + UPDATE "t" SET a = 'x' + 1, b = <<>> WHERE pk = 1 | Empty bags are not supported + UPDATE "t" SET a = 'x' + 1 REMOVE l[99999999999] WHERE pk = 1 | List index is not within the allowable range; index: [99999999999] at 1:37:11 + UPDATE "t" SET a = set_add(b, <<'x'>>), c = foo(1) WHERE pk = 1 | The first argument to SET_ADD must equal the assignment value at 1:20:7 + FROM "t" WHERE attribute_exists('x') SET a = size(b) | Operator or function requires a document path; operator or function: attribute_exists + FROM "t" WHERE a < true SET a = foo(1) | Incorrect operand type for operator or function; operator or function: <, operand type: BOOL + FROM "t" WHERE foo(1) SET a = bar(1) | Unrecognized function: foo at 1:16:3 + DELETE FROM "t" WHERE pk = 1 AND a < true RETURNING ALL NEW * | Incorrect operand type for operator or function; operator or function: <, operand type: BOOL + DELETE FROM "t" WHERE attribute_exists() RETURNING ALL NEW * | Incorrect number of operands for operator or function; operator or function: attribute_exists, number of operands: 0 + """) + void checksTheWhereClauseBeforeTheEdits(String statement, String message) { + AwsException e = assertThrows(AwsException.class, () -> DynamoDbPartiQLParser.parse(statement, List.of())); + + assertEquals(message, e.getMessage()); + } + + @Test + void countsInOperandsWithTheOperandChecks() { + String tooMany = "The IN operator is provided with too many operands; number of operands: 101"; + String in = "a IN [" + inValues(101) + "]"; + int foo = "SELECT * FROM \"t\" WHERE ".length() + in.length() + " AND ".length() + 1; + + assertEquals(tooMany, refusal(in + " AND a < true", 0)); + assertEquals(tooMany, refusal(in + " AND attribute_exists()", 0)); + assertEquals("Incorrect operand type for operator or function; operator or function: <, operand type: BOOL", + refusal("a < true AND " + in, 0)); + assertEquals("Unrecognized function: foo at 1:" + foo + ":3", refusal(in + " AND foo(1)", 0)); + } + + @Test + void readsAFunctionNameWithoutParenthesesAsAPath() { + assertDoesNotThrow(() -> DynamoDbPartiQLParser.parse( + "SELECT * FROM \"t\" WHERE begins_with = 1 AND contains.a = 1", List.of())); + } + @Test void namesWhatFollowsALongRunOfSigns() { AwsException e = assertThrows(AwsException.class,