feat(dynamodb): implement ExecuteStatement, ExecuteTransaction, BatchExecuteStatement (#864)

Adds PartiQL support for DynamoDB via a hand-rolled tokenizer and
recursive-descent parser that translates SELECT, INSERT, UPDATE, and
DELETE statements into existing DynamoDbService calls.

  - DynamoDbPartiQLParser: tokenizer + AST (sealed interfaces) with
    positional ? placeholder resolution from Parameters array
  - DynamoDbPartiQLHandler: translates AST to GetItem/Query, PutItem,
    UpdateItem, DeleteItem; always uses ExpressionAttributeNames to avoid
    reserved-keyword conflicts; routes pk-only WHERE to Query (not GetItem)
    when the table has a composite key
  - DynamoDbJsonHandler: wires ExecuteStatement, ExecuteTransaction, and
    BatchExecuteStatement; BatchExecuteStatement captures per-statement
    errors without aborting the batch
  - DynamoDbPartiQLTest: 13 compatibility tests covering INSERT, SELECT
    (pk-only, range, projection, begins_with, ? placeholders), UPDATE
    SET/REMOVE, DELETE, ExecuteTransaction, and BatchExecuteStatement
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-05-16 19:34:33 -05:00
1 parent 9a10f81fb7
commit 2608b8d6d6
4 files changed
+940

No files matched your search

@@ -27,6 +27,7 @@ public class DynamoDbJsonHandler {
private final DynamoDbStreamService dynamoDbStreamService;
private final KinesisService kinesisService;
private final ObjectMapper objectMapper;
private final DynamoDbPartiQLHandler partiQLHandler;
@Inject
public DynamoDbJsonHandler(DynamoDbService dynamoDbService, DynamoDbStreamService dynamoDbStreamService,
@@ -35,6 +36,7 @@ public class DynamoDbJsonHandler {
this.dynamoDbStreamService = dynamoDbStreamService;
this.kinesisService = kinesisService;
this.objectMapper = objectMapper;
this.partiQLHandler = new DynamoDbPartiQLHandler(dynamoDbService, objectMapper);
}
public Response handle(String action, JsonNode request, String region) throws Exception {
@@ -67,6 +69,9 @@ public class DynamoDbJsonHandler {
case "ExportTableToPointInTime" -> handleExportTable(request, region);
case "DescribeExport" -> handleDescribeExport(request, region);
case "ListExports" -> handleListExports(request, region);
case "ExecuteStatement" -> handleExecuteStatement(request, region);
case "ExecuteTransaction" -> handleExecuteTransaction(request, region);
case "BatchExecuteStatement" -> handleBatchExecuteStatement(request, region);
default -> Response.status(400)
.entity(new AwsErrorResponse("UnknownOperationException", "Operation " + action + " is not supported."))
.build();
@@ -1877,4 +1882,86 @@ public class DynamoDbJsonHandler {
}
return Response.ok(response).build();
}
private Response handleExecuteStatement(JsonNode request, String region) {
String statement = request.path("Statement").asText();
List<JsonNode> parameters = toPartiQLParams(request.path("Parameters"));
DynamoDbPartiQLParser.Stmt stmt = DynamoDbPartiQLParser.parse(statement, parameters);
JsonNode result = partiQLHandler.execute(stmt, region);
return Response.ok(result).build();
}
private Response handleExecuteTransaction(JsonNode request, String region) {
JsonNode stmts = request.path("TransactStatements");
if (stmts.isMissingNode() || !stmts.isArray() || stmts.isEmpty()) {
throw new AwsException("ValidationException", "TransactStatements must not be empty", 400);
}
List<JsonNode> transactItems = new ArrayList<>();
for (JsonNode s : stmts) {
DynamoDbPartiQLParser.Stmt stmt = DynamoDbPartiQLParser.parse(
s.path("Statement").asText(), toPartiQLParams(s.path("Parameters")));
transactItems.add(partiQLHandler.toTransactItem(stmt, region));
}
try {
dynamoDbService.transactWriteItems(transactItems, region);
ObjectNode resp = objectMapper.createObjectNode();
resp.set("Responses", objectMapper.createArrayNode());
return Response.ok(resp).build();
} catch (TransactionCanceledException e) {
ObjectNode body = objectMapper.createObjectNode();
body.put("__type", "TransactionCanceledException");
body.put("message", e.getMessage());
ArrayNode reasons = body.putArray("CancellationReasons");
for (TransactionCanceledException.CancellationReason reason : e.getCancellationReasons()) {
ObjectNode r = objectMapper.createObjectNode();
r.put("Code", reason.code().isEmpty() ? "None" : reason.code());
r.put("Message", reason.code().isEmpty() ? "" : "The conditional request failed");
if (reason.item() != null) {
r.set("Item", reason.item());
}
reasons.add(r);
}
return Response.status(400).entity(body).build();
}
}
private Response handleBatchExecuteStatement(JsonNode request, String region) {
JsonNode stmts = request.path("Statements");
if (stmts.isMissingNode() || !stmts.isArray() || stmts.isEmpty()) {
throw new AwsException("ValidationException", "Statements must not be empty", 400);
}
ArrayNode responses = objectMapper.createArrayNode();
for (JsonNode s : stmts) {
try {
DynamoDbPartiQLParser.Stmt stmt = DynamoDbPartiQLParser.parse(
s.path("Statement").asText(), toPartiQLParams(s.path("Parameters")));
JsonNode result = partiQLHandler.execute(stmt, region);
ObjectNode slot = objectMapper.createObjectNode();
JsonNode firstItem = result.path("Items").path(0);
if (!firstItem.isMissingNode()) {
slot.set("Item", firstItem);
}
responses.add(slot);
} catch (AwsException e) {
ObjectNode slot = objectMapper.createObjectNode();
ObjectNode err = objectMapper.createObjectNode();
err.put("Code", e.getErrorCode());
err.put("Message", e.getMessage());
slot.set("Error", err);
responses.add(slot);
}
}
ObjectNode resp = objectMapper.createObjectNode();
resp.set("Responses", responses);
return Response.ok(resp).build();
}
private List<JsonNode> toPartiQLParams(JsonNode node) {
if (node == null || node.isMissingNode() || !node.isArray()) {
return Collections.emptyList();
}
List<JsonNode> params = new ArrayList<>();
node.forEach(params::add);
return params;
}
}
@@ -0,0 +1,331 @@
package io.github.hectorvent.floci.services.dynamodb;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbPartiQLParser.*;
import io.github.hectorvent.floci.services.dynamodb.model.ConditionalCheckFailedException;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
import java.util.*;
class DynamoDbPartiQLHandler {
private final DynamoDbService service;
private final ObjectMapper mapper;
DynamoDbPartiQLHandler(DynamoDbService service, ObjectMapper mapper) {
this.service = service;
this.mapper = mapper;
}
JsonNode execute(Stmt stmt, String region) {
return switch (stmt) {
case Stmt.Select s -> executeSelect(s, region);
case Stmt.Insert s -> executeInsert(s, region);
case Stmt.Update s -> executeUpdate(s, region);
case Stmt.Delete s -> executeDelete(s, region);
};
}
// --- SELECT ---
private JsonNode executeSelect(Stmt.Select stmt, String region) {
TableDefinition table = service.describeTable(stmt.table(), region);
String pkName = table.getPartitionKeyName();
String skName = table.getSortKeyName();
Cond.Eq pkEq = null;
Cond skCond = null;
List<Cond> filterConds = new ArrayList<>();
for (Cond c : stmt.where()) {
String attr = condAttr(c);
if (pkName.equals(attr)) {
if (c instanceof Cond.Eq eq) {
pkEq = eq;
} else {
filterConds.add(c);
}
} else if (skName != null && skName.equals(attr)) {
skCond = c;
} else {
filterConds.add(c);
}
}
List<JsonNode> items;
// Only use GetItem when table has no sort key and we have a pk equality with no other conditions.
// When the table has a sort key, always use Query (GetItem requires both pk and sk).
if (pkEq != null && skName == null && skCond == null && filterConds.isEmpty()) {
ObjectNode key = mapper.createObjectNode();
key.set(pkName, toTypedNode(pkEq.val()));
JsonNode item = service.getItem(stmt.table(), key, region);
items = item != null ? List.of(item) : Collections.emptyList();
} else {
ExprAttrBuilder eav = new ExprAttrBuilder();
ExprAttrNameBuilder ean = new ExprAttrNameBuilder();
String kce = buildKce(pkEq, skCond, pkName, skName, eav, ean);
String fe = buildFe(filterConds, eav, ean);
DynamoDbService.QueryResult result = service.query(
stmt.table(), null, eav.toNode(mapper), kce, fe,
null, null, null, null, ean.isEmpty() ? null : ean.toNode(mapper), region);
items = result.items();
}
// Apply column projection for non-* SELECT
if (!stmt.columns().isEmpty()) {
ExprAttrNameBuilder projEan = new ExprAttrNameBuilder();
String proj = stmt.columns().stream()
.map(projEan::alias)
.reduce((a, b) -> a + "," + b)
.orElse("");
ObjectNode eanNode = projEan.isEmpty() ? null : projEan.toNode(mapper);
items = items.stream()
.map(item -> (JsonNode) ProjectionEvaluator.project(item, proj, eanNode))
.toList();
}
ArrayNode arr = mapper.createArrayNode();
items.forEach(arr::add);
ObjectNode resp = mapper.createObjectNode();
resp.set("Items", arr);
return resp;
}
private String buildKce(Cond.Eq pkEq, Cond skCond, String pkName, String skName,
ExprAttrBuilder eav, ExprAttrNameBuilder ean) {
if (pkEq == null) {
throw new AwsException("ValidationException",
"WHERE clause of a SELECT must include an equality condition on the partition key", 400);
}
String pkAlias = ean.alias(pkName);
String pkPlaceholder = eav.add(toTypedNode(pkEq.val()));
StringBuilder kce = new StringBuilder(pkAlias).append(" = ").append(pkPlaceholder);
if (skCond != null) {
kce.append(" AND ").append(buildCondExpr(skCond, eav, ean));
}
return kce.toString();
}
private String buildFe(List<Cond> filterConds, ExprAttrBuilder eav, ExprAttrNameBuilder ean) {
if (filterConds.isEmpty()) return null;
List<String> parts = filterConds.stream().map(c -> buildCondExpr(c, eav, ean)).toList();
return String.join(" AND ", parts);
}
private String buildCondExpr(Cond c, ExprAttrBuilder eav, ExprAttrNameBuilder ean) {
return switch (c) {
case Cond.Eq eq -> ean.alias(eq.attr()) + " = " + eav.add(toTypedNode(eq.val()));
case Cond.Cmp cmp -> ean.alias(cmp.attr()) + " " + cmp.op() + " " + eav.add(toTypedNode(cmp.val()));
case Cond.Between b ->
ean.alias(b.attr()) + " BETWEEN " + eav.add(toTypedNode(b.lo())) + " AND " + eav.add(toTypedNode(b.hi()));
case Cond.BeginsWith bw ->
"begins_with(" + ean.alias(bw.attr()) + ", " + eav.add(toTypedNode(bw.prefix())) + ")";
};
}
private static String condAttr(Cond c) {
return switch (c) {
case Cond.Eq eq -> eq.attr();
case Cond.Cmp cmp -> cmp.attr();
case Cond.Between b -> b.attr();
case Cond.BeginsWith bw -> bw.attr();
};
}
// --- INSERT ---
private JsonNode executeInsert(Stmt.Insert stmt, String region) {
TableDefinition table = service.describeTable(stmt.table(), region);
String pkName = table.getPartitionKeyName();
ObjectNode item = mapper.createObjectNode();
stmt.item().forEach((k, v) -> item.set(k, toTypedNode(v)));
try {
service.putItem(stmt.table(), item, "attribute_not_exists(" + pkName + ")", null, null, region, "NONE");
} catch (ConditionalCheckFailedException e) {
throw new AwsException("DuplicateItemException", "Duplicate primary key exists in table", 400);
}
return emptyItemsResponse();
}
// --- UPDATE ---
private JsonNode executeUpdate(Stmt.Update stmt, String region) {
TableDefinition table = service.describeTable(stmt.table(), region);
ObjectNode key = buildKey(table, stmt.where());
ExprAttrBuilder eav = new ExprAttrBuilder();
ExprAttrNameBuilder ean = new ExprAttrNameBuilder();
StringBuilder ue = new StringBuilder();
if (!stmt.sets().isEmpty()) {
ue.append("SET ");
List<String> parts = new ArrayList<>();
for (Assign a : stmt.sets()) {
parts.add(ean.alias(a.attr()) + " = " + eav.add(toTypedNode(a.val())));
}
ue.append(String.join(", ", parts));
}
if (!stmt.removes().isEmpty()) {
if (!ue.isEmpty()) ue.append(" ");
ue.append("REMOVE ");
ue.append(stmt.removes().stream().map(ean::alias).reduce((a, b) -> a + ", " + b).orElse(""));
}
service.updateItem(stmt.table(), key, null, ue.toString(),
ean.isEmpty() ? null : ean.toNode(mapper),
eav.isEmpty() ? null : eav.toNode(mapper), "NONE", region);
return emptyItemsResponse();
}
// --- DELETE ---
private JsonNode executeDelete(Stmt.Delete stmt, String region) {
TableDefinition table = service.describeTable(stmt.table(), region);
ObjectNode key = buildKey(table, stmt.where());
service.deleteItem(stmt.table(), key, null, null, null, region, "NONE");
return emptyItemsResponse();
}
// --- Transaction item builder ---
JsonNode toTransactItem(Stmt stmt, String region) {
ObjectNode txItem = mapper.createObjectNode();
switch (stmt) {
case Stmt.Insert ins -> {
TableDefinition table = service.describeTable(ins.table(), region);
String pkName = table.getPartitionKeyName();
ObjectNode item = mapper.createObjectNode();
ins.item().forEach((k, v) -> item.set(k, toTypedNode(v)));
ObjectNode put = mapper.createObjectNode();
put.put("TableName", ins.table());
put.set("Item", item);
put.put("ConditionExpression", "attribute_not_exists(" + pkName + ")");
txItem.set("Put", put);
}
case Stmt.Update upd -> {
TableDefinition table = service.describeTable(upd.table(), region);
ObjectNode key = buildKey(table, upd.where());
ExprAttrBuilder eav = new ExprAttrBuilder();
ExprAttrNameBuilder ean = new ExprAttrNameBuilder();
StringBuilder ue = new StringBuilder();
if (!upd.sets().isEmpty()) {
ue.append("SET ");
List<String> parts = new ArrayList<>();
for (Assign a : upd.sets()) {
parts.add(ean.alias(a.attr()) + " = " + eav.add(toTypedNode(a.val())));
}
ue.append(String.join(", ", parts));
}
if (!upd.removes().isEmpty()) {
if (!ue.isEmpty()) ue.append(" ");
ue.append("REMOVE ");
ue.append(upd.removes().stream().map(ean::alias).reduce((a, b) -> a + ", " + b).orElse(""));
}
ObjectNode update = mapper.createObjectNode();
update.put("TableName", upd.table());
update.set("Key", key);
update.put("UpdateExpression", ue.toString());
if (!eav.isEmpty()) update.set("ExpressionAttributeValues", eav.toNode(mapper));
if (!ean.isEmpty()) update.set("ExpressionAttributeNames", ean.toNode(mapper));
txItem.set("Update", update);
}
case Stmt.Delete del -> {
TableDefinition table = service.describeTable(del.table(), region);
ObjectNode key = buildKey(table, del.where());
ObjectNode delete = mapper.createObjectNode();
delete.put("TableName", del.table());
delete.set("Key", key);
txItem.set("Delete", delete);
}
case Stmt.Select ignored ->
throw new AwsException("ValidationException",
"SELECT is not supported inside ExecuteTransaction", 400);
}
return txItem;
}
// --- Shared helpers ---
private ObjectNode buildKey(TableDefinition table, List<Cond> where) {
String pkName = table.getPartitionKeyName();
String skName = table.getSortKeyName();
ObjectNode key = mapper.createObjectNode();
for (Cond c : where) {
if (c instanceof Cond.Eq eq) {
if (pkName.equals(eq.attr()) || (skName != null && skName.equals(eq.attr()))) {
key.set(eq.attr(), toTypedNode(eq.val()));
}
}
}
if (!key.has(pkName)) {
throw new AwsException("ValidationException",
"WHERE clause must include an equality condition on the partition key", 400);
}
return key;
}
JsonNode toTypedNode(PVal val) {
ObjectNode node = mapper.createObjectNode();
switch (val) {
case PVal.Str s -> node.put("S", s.v());
case PVal.Num n -> node.put("N", DynamoDbNumberUtils.validateAndNormalize(n.v()));
case PVal.Bool b -> node.put("BOOL", b.v());
case PVal.Null ignored -> node.put("NULL", true);
}
return node;
}
private ObjectNode emptyItemsResponse() {
ObjectNode resp = mapper.createObjectNode();
resp.set("Items", mapper.createArrayNode());
return resp;
}
// Builds ExpressionAttributeValues with positional :p0, :p1, … placeholders
private static class ExprAttrBuilder {
private final Map<String, JsonNode> values = new LinkedHashMap<>();
private int idx = 0;
String add(JsonNode val) {
String key = ":p" + idx++;
values.put(key, val);
return key;
}
boolean isEmpty() { return values.isEmpty(); }
ObjectNode toNode(ObjectMapper mapper) {
ObjectNode node = mapper.createObjectNode();
values.forEach(node::set);
return node;
}
}
// Builds ExpressionAttributeNames with #n0, #n1, … aliases
private static class ExprAttrNameBuilder {
private final Map<String, String> aliasToName = new LinkedHashMap<>();
private final Map<String, String> nameToAlias = new LinkedHashMap<>();
private int idx = 0;
String alias(String name) {
return nameToAlias.computeIfAbsent(name, n -> {
String a = "#n" + idx++;
aliasToName.put(a, n);
return a;
});
}
boolean isEmpty() { return aliasToName.isEmpty(); }
ObjectNode toNode(ObjectMapper mapper) {
ObjectNode node = mapper.createObjectNode();
aliasToName.forEach(node::put);
return node;
}
}
}
@@ -0,0 +1,314 @@
package io.github.hectorvent.floci.services.dynamodb;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsException;
import java.util.*;
class DynamoDbPartiQLParser {
enum TType {
SELECT, FROM, WHERE, INSERT, INTO, VALUE,
UPDATE, SET, REMOVE, DELETE, AND, BETWEEN,
IDENT, STRING, NUMBER, BOOL, NULL, QUESTION,
EQ, NE, LT, LE, GT, GE,
LPAREN, RPAREN, LBRACE, RBRACE, COMMA, COLON,
EOF
}
record Token(TType type, String value) {}
// --- AST node types ---
sealed interface Stmt permits Stmt.Select, Stmt.Insert, Stmt.Update, Stmt.Delete {
record Select(String table, List<String> columns, List<Cond> where) implements Stmt {}
record Insert(String table, Map<String, PVal> item) implements Stmt {}
record Update(String table, List<Assign> sets, List<String> removes, List<Cond> where) implements Stmt {}
record Delete(String table, List<Cond> where) implements Stmt {}
}
sealed interface PVal permits PVal.Str, PVal.Num, PVal.Bool, PVal.Null {
record Str(String v) implements PVal {}
record Num(String v) implements PVal {}
record Bool(boolean v) implements PVal {}
record Null() implements PVal {}
}
sealed interface Cond permits Cond.Eq, Cond.Cmp, Cond.Between, Cond.BeginsWith {
record Eq(String attr, PVal val) implements Cond {}
record Cmp(String attr, String op, PVal val) implements Cond {}
record Between(String attr, PVal lo, PVal hi) implements Cond {}
record BeginsWith(String attr, PVal prefix) implements Cond {}
}
record Assign(String attr, PVal val) {}
// --- Tokenizer ---
static List<Token> tokenize(String input) {
List<Token> tokens = new ArrayList<>();
int i = 0, n = input.length();
while (i < n) {
char c = input.charAt(i);
if (Character.isWhitespace(c)) { i++; continue; }
if (c == '\'') {
int start = ++i;
while (i < n && input.charAt(i) != '\'') i++;
tokens.add(new Token(TType.STRING, input.substring(start, i)));
i++;
continue;
}
if (c == '"') {
int start = ++i;
while (i < n && input.charAt(i) != '"') i++;
tokens.add(new Token(TType.IDENT, input.substring(start, i)));
i++;
continue;
}
if (c == '?') { tokens.add(new Token(TType.QUESTION, "?")); i++; continue; }
if (c == '*') { tokens.add(new Token(TType.IDENT, "*")); i++; continue; }
if (c == '=') { tokens.add(new Token(TType.EQ, "=")); i++; continue; }
if (c == '<') {
if (i + 1 < n && input.charAt(i + 1) == '>') { tokens.add(new Token(TType.NE, "<>")); i += 2; }
else if (i + 1 < n && input.charAt(i + 1) == '=') { tokens.add(new Token(TType.LE, "<=")); i += 2; }
else { tokens.add(new Token(TType.LT, "<")); i++; }
continue;
}
if (c == '>') {
if (i + 1 < n && input.charAt(i + 1) == '=') { tokens.add(new Token(TType.GE, ">=")); i += 2; }
else { tokens.add(new Token(TType.GT, ">")); i++; }
continue;
}
if (c == '(') { tokens.add(new Token(TType.LPAREN, "(")); i++; continue; }
if (c == ')') { tokens.add(new Token(TType.RPAREN, ")")); i++; continue; }
if (c == '{') { tokens.add(new Token(TType.LBRACE, "{")); i++; continue; }
if (c == '}') { tokens.add(new Token(TType.RBRACE, "}")); i++; continue; }
if (c == ',') { tokens.add(new Token(TType.COMMA, ",")); i++; continue; }
if (c == ':') { tokens.add(new Token(TType.COLON, ":")); i++; continue; }
if (Character.isDigit(c) || (c == '-' && i + 1 < n && Character.isDigit(input.charAt(i + 1)))) {
int start = i;
if (c == '-') i++;
while (i < n && (Character.isDigit(input.charAt(i)) || input.charAt(i) == '.')) i++;
tokens.add(new Token(TType.NUMBER, input.substring(start, i)));
continue;
}
if (Character.isLetter(c) || c == '_') {
int start = i;
while (i < n && (Character.isLetterOrDigit(input.charAt(i)) || input.charAt(i) == '_')) i++;
String word = input.substring(start, i);
TType type = switch (word.toUpperCase()) {
case "SELECT" -> TType.SELECT;
case "FROM" -> TType.FROM;
case "WHERE" -> TType.WHERE;
case "INSERT" -> TType.INSERT;
case "INTO" -> TType.INTO;
case "VALUE" -> TType.VALUE;
case "UPDATE" -> TType.UPDATE;
case "SET" -> TType.SET;
case "REMOVE" -> TType.REMOVE;
case "DELETE" -> TType.DELETE;
case "AND" -> TType.AND;
case "BETWEEN" -> TType.BETWEEN;
case "TRUE", "FALSE" -> TType.BOOL;
case "NULL" -> TType.NULL;
default -> TType.IDENT;
};
tokens.add(new Token(type, word));
continue;
}
throw validationEx("Unexpected character '" + c + "' in PartiQL statement");
}
tokens.add(new Token(TType.EOF, ""));
return tokens;
}
// --- Recursive-descent parser ---
private final List<Token> tokens;
private final List<JsonNode> parameters;
private int pos = 0;
private int paramIdx = 0;
private DynamoDbPartiQLParser(List<Token> tokens, List<JsonNode> parameters) {
this.tokens = tokens;
this.parameters = parameters;
}
static Stmt parse(String statement, List<JsonNode> parameters) {
return new DynamoDbPartiQLParser(tokenize(statement.trim()), parameters).parseStmt();
}
private Stmt parseStmt() {
return switch (peek().type()) {
case SELECT -> parseSelect();
case INSERT -> parseInsert();
case UPDATE -> parseUpdate();
case DELETE -> parseDelete();
default -> throw validationEx("Unsupported PartiQL statement: " + peek().value());
};
}
// SELECT col [, col …] | * FROM "Table" [WHERE cond [AND cond …]]
private Stmt.Select parseSelect() {
consume(TType.SELECT);
List<String> cols = new ArrayList<>();
if (peek().type() == TType.IDENT && "*".equals(peek().value())) {
advance();
} else {
cols.add(expectIdent());
while (peek().type() == TType.COMMA) { advance(); cols.add(expectIdent()); }
}
consume(TType.FROM);
String table = expectIdent();
List<Cond> where = new ArrayList<>();
if (peek().type() == TType.WHERE) { advance(); where = parseConditions(); }
return new Stmt.Select(table, cols, where);
}
// INSERT INTO "Table" VALUE {'key': val, …}
private Stmt.Insert parseInsert() {
consume(TType.INSERT);
consume(TType.INTO);
String table = expectIdent();
consume(TType.VALUE);
consume(TType.LBRACE);
Map<String, PVal> item = new LinkedHashMap<>();
while (peek().type() != TType.RBRACE && peek().type() != TType.EOF) {
String key = expectStringOrIdent();
consume(TType.COLON);
item.put(key, parseValue());
if (peek().type() == TType.COMMA) advance();
}
consume(TType.RBRACE);
return new Stmt.Insert(table, item);
}
// UPDATE "Table" SET attr=val [, …] [REMOVE attr [, …]] WHERE …
private Stmt.Update parseUpdate() {
consume(TType.UPDATE);
String table = expectIdent();
List<Assign> sets = new ArrayList<>();
List<String> removes = new ArrayList<>();
while (peek().type() == TType.SET || peek().type() == TType.REMOVE) {
if (peek().type() == TType.SET) {
advance();
sets.add(parseAssign());
while (peek().type() == TType.COMMA) { advance(); sets.add(parseAssign()); }
} else {
advance();
removes.add(expectIdent());
while (peek().type() == TType.COMMA) { advance(); removes.add(expectIdent()); }
}
}
consume(TType.WHERE);
return new Stmt.Update(table, sets, removes, parseConditions());
}
// DELETE FROM "Table" WHERE …
private Stmt.Delete parseDelete() {
consume(TType.DELETE);
consume(TType.FROM);
String table = expectIdent();
consume(TType.WHERE);
return new Stmt.Delete(table, parseConditions());
}
private List<Cond> parseConditions() {
List<Cond> conds = new ArrayList<>();
conds.add(parseCond());
while (peek().type() == TType.AND) { advance(); conds.add(parseCond()); }
return conds;
}
private Cond parseCond() {
if (peek().type() == TType.IDENT && "begins_with".equalsIgnoreCase(peek().value())) {
advance();
consume(TType.LPAREN);
String attr = expectIdent();
consume(TType.COMMA);
PVal prefix = parseValue();
consume(TType.RPAREN);
return new Cond.BeginsWith(attr, prefix);
}
String attr = expectIdent();
if (peek().type() == TType.BETWEEN) {
advance();
PVal lo = parseValue();
consume(TType.AND);
PVal hi = parseValue();
return new Cond.Between(attr, lo, hi);
}
String op = parseOp();
PVal val = parseValue();
return "=".equals(op) ? new Cond.Eq(attr, val) : new Cond.Cmp(attr, op, val);
}
private String parseOp() {
Token t = advance();
return switch (t.type()) {
case EQ -> "="; case NE -> "<>";
case LT -> "<"; case LE -> "<=";
case GT -> ">"; case GE -> ">=";
default -> throw validationEx("Expected comparison operator, got: " + t.value());
};
}
private Assign parseAssign() {
String attr = expectIdent();
consume(TType.EQ);
return new Assign(attr, parseValue());
}
private PVal parseValue() {
Token t = advance();
return switch (t.type()) {
case STRING -> new PVal.Str(t.value());
case NUMBER -> new PVal.Num(t.value());
case BOOL -> new PVal.Bool(Boolean.parseBoolean(t.value()));
case NULL -> new PVal.Null();
case QUESTION -> resolveParam();
default -> throw validationEx("Expected value literal or ?, got: " + t.value());
};
}
private PVal resolveParam() {
if (paramIdx >= parameters.size()) {
throw validationEx("Not enough parameters supplied for ? placeholders");
}
JsonNode p = parameters.get(paramIdx++);
if (p.has("S")) return new PVal.Str(p.get("S").asText());
if (p.has("N")) return new PVal.Num(p.get("N").asText());
if (p.has("BOOL")) return new PVal.Bool(p.get("BOOL").asBoolean());
if (p.has("NULL")) return new PVal.Null();
throw validationEx("Unsupported parameter type in parameters array");
}
private String expectIdent() {
Token t = advance();
if (t.type() != TType.IDENT) throw validationEx("Expected identifier, got: '" + t.value() + "'");
return t.value();
}
private String expectStringOrIdent() {
Token t = peek();
if (t.type() == TType.STRING || t.type() == TType.IDENT) { advance(); return t.value(); }
throw validationEx("Expected attribute name, got: '" + t.value() + "'");
}
private void consume(TType type) {
Token t = advance();
if (t.type() != type) throw validationEx("Expected " + type + ", got: '" + t.value() + "'");
}
private Token peek() { return tokens.get(pos); }
private Token advance() {
Token t = tokens.get(pos);
if (t.type() != TType.EOF) pos++;
return t;
}
static AwsException validationEx(String msg) {
return new AwsException("ValidationException", msg, 400);
}
}