feat(iot): rule SQL message functions, isNull, isUndefined, IN and array literals (#3036)

Add clientid(), timestamp(), accountid() and newuuid(), the isNull() and
isUndefined() functions, the IN operator against a payload array or an
array literal, and array literals such as [lat, long], each following
the tables in the AWS IoT SQL reference. Equality extends to arrays
(element by element, in order) and objects (by key, in any order).

clientid() needs the MQTT client that published, so publish and
handlePublish carry the client id: the broker passes its session's
client id and an IoT Data Publish over HTTP passes none, which the
function reports as n/a as AWS does.

principal() stays unparsed: it returns the certificate a device
authenticated with, and the broker does not verify one yet.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-09-07 21:49:18 -05:00
1 parent 90fa707145
commit b88034cd1d
18 files changed
+665 -104

No files matched your search

@@ -354,6 +354,44 @@ class IotMqttEnabledIntegrationTest {
}
}
@Test
void clientidIsTheMqttClientThatPublishedTheMessage() throws Exception {
given()
.contentType("application/json")
.body("""
{
"topicRulePayload": {
"sql": "SELECT clientid() AS client, topic() AS topic FROM 'devices/phase8/mqtt/clientid'",
"actions": [
{
"republish": {
"roleArn": "arn:aws:iam::000000000000:role/iot-rule-role",
"topic": "devices/phase8/mqtt/clientid-target"
}
}
]
}
}
""")
.when()
.put("/rules/phase8MqttClientIdRule")
.then()
.statusCode(200);
try (MqttTestClient subscriber = connectMqtt("phase8-clientid-sub")) {
subscriber.subscribe("devices/phase8/mqtt/clientid-target");
String publisherId = uniqueClientId("phase8-clientid-pub");
try (MqttTestClient publisher = connectMqttClientId(publisherId)) {
publisher.publish("devices/phase8/mqtt/clientid", "{}".getBytes(StandardCharsets.UTF_8));
}
MqttPublish republished = subscriber.takePublish();
assertEquals("{\"client\":\"" + publisherId + "\",\"topic\":\"devices/phase8/mqtt/clientid\"}",
new String(republished.payload(), StandardCharsets.UTF_8));
}
}
private MqttTestClient connectMqtt(String clientId) throws MqttException {
return connectMqttClientId(uniqueClientId(clientId));
}
@@ -138,7 +138,7 @@ class IotServiceTest {
}
private void publish(String payload) {
service.handlePublish(TOPIC, payload.getBytes(StandardCharsets.UTF_8), true, REGION);
service.handlePublish(TOPIC, payload.getBytes(StandardCharsets.UTF_8), true, REGION, null);
}
private JsonNode capturedInvocationPayload(String functionArn) throws Exception {
@@ -14,6 +14,7 @@ import org.junit.jupiter.params.provider.CsvSource;
import java.nio.charset.StandardCharsets;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
@@ -52,7 +53,7 @@ class IotTopicRuleSqlIntegrationTest {
@Test
void aStatementOutsideTheSubsetKeepsFiringWithTheWholePayload() {
createRule("sqlPassthroughRule", "SELECT clientid() as client FROM 'sqltest/passthrough/+'",
createRule("sqlPassthroughRule", "SELECT principal() as p FROM 'sqltest/passthrough/+'",
"sqltest/passthrough-out");
publish("sqltest/passthrough/a", "{\"any\":1}");
@@ -139,6 +140,42 @@ class IotTopicRuleSqlIntegrationTest {
assertSame(parsed, compiledQuery("sqlToggleRule"));
}
@Test
void messageFunctionsSeeTheRuleAccountAndNoMqttClientOnTheServicePath() {
createRule("sqlFunctionsRule", "SELECT clientid() AS client, accountid() AS account, isUndefined(missing) AS u "
+ "FROM 'sqltest/functions/+' WHERE topic(2) IN ['functions'] AND isNull(n)", "sqltest/functions-out");
publish("sqltest/functions/a", "{\"n\":null}");
assertEquals(List.of("{\"client\":\"n/a\",\"account\":\"000000000000\",\"u\":true}"),
republished("sqltest/functions-out"));
}
@Test
void clientidIsTheMqttClientWhenThePublishCarriesOne() {
createRule("sqlClientIdRule", "SELECT clientid() AS client FROM 'sqltest/clientid/+'", "sqltest/clientid-out");
iotService.handlePublish("sqltest/clientid/a", "{}".getBytes(StandardCharsets.UTF_8), true, REGION, "sensor-9");
assertEquals(List.of("{\"client\":\"sensor-9\"}"), republished("sqltest/clientid-out"));
}
@Test
void anIotDataPublishOverHttpHasNoMqttClient() {
createRule("sqlHttpClientIdRule", "SELECT clientid() AS client FROM 'sqltest/httpclient/+'",
"sqltest/httpclient-out");
given()
.contentType("application/json")
.body("{}")
.when()
.post("/topics/sqltest/httpclient/a")
.then()
.statusCode(200);
assertEquals(List.of("{\"client\":\"n/a\"}"), republished("sqltest/httpclient-out"));
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"SELECT *, topic() as topic FROM '$aws/things/+/shadow/name/building/update/accepted' WHERE endswith(clientToken, 'inbound') | $aws/things/sensor-1/shadow/name/building/update/accepted | {\"clientToken\":\"job:inbound\"} | true",
@@ -188,7 +225,7 @@ class IotTopicRuleSqlIntegrationTest {
}
private void publish(String topic, String payload) {
iotService.handlePublish(topic, payload.getBytes(StandardCharsets.UTF_8), true, REGION);
iotService.handlePublish(topic, payload.getBytes(StandardCharsets.UTF_8), true, REGION, null);
}
private List<String> republished(String targetTopic) {
@@ -19,13 +19,13 @@ class IotTopicRuleSqlStrictIntegrationTest {
void strictModeRejectsAStatementOutsideTheSubset() {
given()
.contentType("application/json")
.body(rule("SELECT clientid() as client FROM 'strict/rules/+'"))
.body(rule("SELECT principal() as p FROM 'strict/rules/+'"))
.when()
.put("/rules/strictRejectedRule")
.then()
.statusCode(400)
.body("__type", equalTo("SqlParseException"))
.body("message", containsString("clientid"));
.body("message", containsString("principal"));
}
@Test
@@ -51,6 +51,16 @@ class RuleSqlCorpusTest {
"SELECT * FROM 'topic/subtopic' WHERE startswith(topic(), 'topic') AND endswith(topic(2), 'topic')",
"SELECT * FROM 'a/b' WHERE temperature > -10 AND temperature < 100.5",
"SELECT * FROM 'a/b' WHERE name = 'o''brien'",
"SELECT [lat,long] as lat_long FROM 'topic/subtopic'",
"SELECT * FROM 'a/b' WHERE 3 IN arr",
"SELECT clientid() AS client FROM 'a/b'",
"SELECT *, timestamp() AS ts FROM 'a/b'",
"SELECT *, accountid() AS account FROM 'a/b'",
"SELECT newuuid() AS id FROM 'a/b'",
"SELECT * FROM 'a/b' WHERE isUndefined(x)",
"SELECT * FROM 'a/b' WHERE isNull(x)",
"SELECT * FROM 'a/b' WHERE clientid() <> 'n/a' AND timestamp() > 0 AND accountid() = '123456789012'",
"SELECT [lat, long] AS position, newuuid() AS id, isNull(x) AS n, isUndefined(y) AS u FROM 'a/b' WHERE x IN [1, 2] OR y IN arr",
"SELECT *\n FROM 'topic/subtopic'\n WHERE temperature > 50\n AND color <> 'red'"
})
void aStatementInsideTheSubsetParses(String sql) {
@@ -64,17 +74,9 @@ class RuleSqlCorpusTest {
"SELECT temperature * 1.8 + 32 AS f FROM 'a/b' | +",
"SELECT VALUE color FROM 'topic/subtopic' | color",
"SELECT {'latitude': get(lat_long, 0)} as lat_long FROM 'topic/subtopic' | {",
"SELECT [lat,long] as lat_long FROM 'topic/subtopic' | [",
"SELECT * FROM 'a/b' WHERE 3 IN arr | IN",
"SELECT * FROM 'a/b' WHERE exists (select * from arr as a where a = 3) | exists",
"SELECT clientid() AS client FROM 'a/b' | clientid",
"SELECT *, timestamp() AS ts FROM 'a/b' | timestamp",
"SELECT *, accountid() AS account FROM 'a/b' | accountid",
"SELECT newuuid() AS id FROM 'a/b' | newuuid",
"SELECT principal() AS p FROM 'a/b' | principal",
"SELECT * FROM 'a/b' WHERE traceid() <> '' | traceid",
"SELECT * FROM 'a/b' WHERE isUndefined(x) | isUndefined",
"SELECT * FROM 'a/b' WHERE isNull(x) | isNull",
"SELECT get(get(get(mydata,\"item2\"),\"0\"),\"my-key\") FROM 'iot/rules' | get",
"SELECT temp, md5(deviceid) AS hashed_id FROM 'topic/#' | md5",
"SELECT encode(*, 'base64') AS data FROM 'a/b' | encode",
@@ -7,6 +7,7 @@ import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
@@ -18,7 +19,7 @@ class RuleSqlEvaluatorTest {
private static final String SHADOW_TOPIC = "$aws/things/sensor-1/shadow/name/building/update/accepted";
private final RuleSqlEvaluator evaluator = new RuleSqlEvaluator(new ObjectMapper());
private final RuleSqlEvaluator evaluator = new RuleSqlEvaluator(new ObjectMapper(), Clock.systemUTC());
@Test
void selectAllWithoutWhereForwardsTheOriginalBytes() {
@@ -286,7 +287,7 @@ class RuleSqlEvaluatorTest {
}
private Optional<byte[]> evaluate(String sql, String topic, byte[] payload) {
return evaluator.evaluate("test-rule", RuleSqlParser.parse(sql), topic, payload);
return evaluator.evaluate("test-rule", RuleSqlParser.parse(sql), new RuleSqlContext(topic, null, "000000000000"), payload);
}
private String text(Optional<byte[]> result) {
@@ -0,0 +1,200 @@
package io.github.hectorvent.floci.services.iot.rules;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.Optional;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The message functions, {@code isNull}, {@code isUndefined}, the {@code IN} operator and
* array literals, against the tables in the AWS IoT SQL reference.
*/
class RuleSqlFunctionsTest {
private static final long NOW = 1481825251155L;
private static final Clock CLOCK = Clock.fixed(Instant.ofEpochMilli(NOW), ZoneOffset.UTC);
private static final RuleSqlContext MQTT = new RuleSqlContext("a/b", "sensor-7", "123456789012");
private static final RuleSqlContext HTTP = new RuleSqlContext("a/b", null, "123456789012");
private final ObjectMapper objectMapper = new ObjectMapper();
private final RuleSqlEvaluator evaluator = new RuleSqlEvaluator(objectMapper, CLOCK);
@Test
void timestampIsTheClockInMillisecondsSinceTheEpoch() {
assertEquals("{\"ts\":" + NOW + "}", text(evaluate("SELECT timestamp() AS ts FROM 'a/b'", MQTT, "{}")));
}
@Test
void timestampComparesAsANumber() {
assertTrue(evaluate("SELECT * FROM 'a/b' WHERE timestamp() > 1481825251154", MQTT, "{}").isPresent());
assertFalse(evaluate("SELECT * FROM 'a/b' WHERE timestamp() > 1481825251155", MQTT, "{}").isPresent());
}
@Test
void newuuidIsAFreshUuidEachTime() throws Exception {
String first = json(evaluate("SELECT newuuid() AS id FROM 'a/b'", MQTT, "{}")).get("id").textValue();
String second = json(evaluate("SELECT newuuid() AS id FROM 'a/b'", MQTT, "{}")).get("id").textValue();
assertDoesNotThrow(() -> UUID.fromString(first));
assertDoesNotThrow(() -> UUID.fromString(second));
assertNotEquals(first, second);
}
@Test
void accountidIsTheAccountThatOwnsTheRule() {
assertEquals("{\"account\":\"123456789012\"}",
text(evaluate("SELECT accountid() AS account FROM 'a/b'", MQTT, "{}")));
assertTrue(evaluate("SELECT * FROM 'a/b' WHERE accountid() = '123456789012'", HTTP, "{}").isPresent());
}
@Test
void clientidIsTheMqttClientOrNaWhenTheMessageDidNotComeOverMqtt() {
assertEquals("{\"client\":\"sensor-7\"}", text(evaluate("SELECT clientid() AS client FROM 'a/b'", MQTT, "{}")));
assertEquals("{\"client\":\"n/a\"}", text(evaluate("SELECT clientid() AS client FROM 'a/b'", HTTP, "{}")));
assertTrue(evaluate("SELECT * FROM 'a/b' WHERE startswith(clientid(), 'sensor-')", MQTT, "{}").isPresent());
assertFalse(evaluate("SELECT * FROM 'a/b' WHERE startswith(clientid(), 'sensor-')", HTTP, "{}").isPresent());
}
@Test
void functionsWithoutAnAliasAreWrittenUnderTheirOwnName() throws Exception {
JsonNode document = json(evaluate(
"SELECT timestamp(), accountid(), clientid(), isNull(n), isUndefined(missing) FROM 'a/b'",
MQTT, "{\"n\":null}"));
assertEquals(NOW, document.get("timestamp").longValue());
assertEquals("123456789012", document.get("accountid").textValue());
assertEquals("sensor-7", document.get("clientid").textValue());
assertTrue(document.get("isNull").booleanValue());
assertTrue(document.get("isUndefined").booleanValue());
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"i | false | false",
"d | false | false",
"b | false | false",
"s | false | false",
"a | false | false",
"o | false | false",
"n | true | false",
"missing | false | true",
"o.missing | false | true",
"s.deeper | false | true",
"NULL | true | false",
"5 | false | false",
"topic(9) | false | true",
"topic(1) | false | false",
"clientid() | false | false"
})
void isNullAndIsUndefinedFollowTheReferenceTables(String argument, boolean isNull, boolean isUndefined) {
String payload = "{\"i\":1,\"d\":1.5,\"b\":true,\"s\":\"x\",\"a\":[1],\"o\":{},\"n\":null}";
assertEquals("{\"n\":" + isNull + ",\"u\":" + isUndefined + "}", text(evaluate(
"SELECT isNull(" + argument + ") AS n, isUndefined(" + argument + ") AS u FROM 'a/b'", MQTT, payload)));
}
@ParameterizedTest
@CsvSource(delimiter = '|', quoteCharacter = '"', value = {
"3 IN arr | true",
"4 IN arr | false",
"'three' IN arr | true",
"5.7 IN arr | true",
"3.0 IN arr | true",
"NULL IN arr | true",
"TRUE IN arr | false",
"[1] IN arr | true",
"num IN arr | true",
"three IN arr | true",
"s IN arr | false",
"missing IN arr | false",
"3 IN s | false",
"3 IN missing | false",
"3 IN o | false",
"3 IN [1, 2, 3] | true",
"'x' IN ['x', 'y'] | true",
"'z' IN ['x', 'y'] | false",
"3 IN [] | false",
"s IN [s] | true",
"NOT 3 IN [1] | true",
"NOT missing IN [1] | false",
"3 IN [1] OR num = 3 | true",
"num IN arr AND s = 'x' | true",
"topic(1) IN ['a', 'x'] | true",
"'3' IN arr | false",
"3 IN ['3'] | false"
})
void inChecksMembershipOfAnArrayWithTheEqualityRules(String predicate, boolean fires) {
String payload = "{\"arr\":[1,2,3,\"three\",5.7,null,[1],{\"k\":1}],\"three\":\"three\",\"s\":\"x\",\"num\":3,\"o\":{}}";
assertEquals(fires, evaluate("SELECT * FROM 'a/b' WHERE " + predicate, MQTT, payload).isPresent());
}
@Test
void anArrayLiteralProjectsAsAnArray() {
String payload = "{\"lat\":47.606,\"long\":-122.332}";
assertEquals("{\"lat_long\":[47.606,-122.332]}",
text(evaluate("SELECT [lat, long] AS lat_long FROM 'a/b'", MQTT, payload)));
assertEquals("{\"mixed\":[1,\"a\",true,null,\"a\",[2],[]]}",
text(evaluate("SELECT [1, 'a', TRUE, NULL, topic(1), [2], []] AS mixed FROM 'a/b'", MQTT, payload)));
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"1 IN list | true",
"2 IN list | false",
"NOT 2 IN list | true",
"pair = [9007199254740993.0] | true",
"pair = [9007199254740992] | false",
"NOT pair = [9007199254740992] | true",
"pair <> [9007199254740992] | true",
"obj = obj | true",
"NOT obj = obj | false",
"list = [9007199254740993, 1.0] | true",
"list = [9007199254740993, 1.00001] | false",
"pair = [1, 2] | false",
"pair = 'x' | false",
"small = [0.30000000000000004] | true",
"small = [0.3] | false"
})
void comparesNumbersInsideArraysAndObjectsExactly(String predicate, boolean fires) {
String payload = "{\"list\":[9007199254740993.0, 1],\"pair\":[9007199254740993.0],"
+ "\"obj\":{\"k\":0.30000000000000004},\"small\":[0.30000000000000004]}";
assertEquals(fires, evaluate("SELECT * FROM 'a/b' WHERE " + predicate, MQTT, payload).isPresent());
}
@Test
void anArrayLiteralWithAnUndefinedElementIsUndefined() {
assertEquals("{\"lat\":47.606}",
text(evaluate("SELECT lat, [lat, missing] AS lat_long FROM 'a/b'", MQTT, "{\"lat\":47.606}")));
assertFalse(evaluate("SELECT * FROM 'a/b' WHERE 1 IN [1, missing]", MQTT, "{}").isPresent());
}
private Optional<byte[]> evaluate(String sql, RuleSqlContext context, String payload) {
return evaluator.evaluate("test-rule", RuleSqlParser.parse(sql), context, payload.getBytes(StandardCharsets.UTF_8));
}
private JsonNode json(Optional<byte[]> result) throws Exception {
return objectMapper.readTree(text(result));
}
private String text(Optional<byte[]> result) {
assertTrue(result.isPresent(), "Expected the rule to fire");
return new String(result.get(), StandardCharsets.UTF_8);
}
}
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -35,14 +36,17 @@ class RuleSqlFuzzTest {
"SELECT * FROM 'a/b' WHERE NOT active = FALSE AND (size > 10 OR weight <= -2.5) AND name <> NULL",
"select level, name from \"a/b\" where level != 3 and name = \"o''brien\"",
"SELECT NULL AS n, TRUE AS t, 'x' AS s, 1 AS i FROM 'topic/subtopic'",
"SELECT * FROM 'a/#' WHERE startswith(topic(2), 'b') AND endswith(topic(), 'c')");
"SELECT * FROM 'a/#' WHERE startswith(topic(2), 'b') AND endswith(topic(), 'c')",
"SELECT clientid() AS client, timestamp() AS ts, accountid() AS account, newuuid() AS id FROM 'a/b' WHERE clientid() <> 'n/a'",
"SELECT [a, b, 1, 'x', NULL] AS list, isNull(n) AS n, isUndefined(missing) AS u FROM 'a/b' WHERE a IN arr OR 3 IN [1, 2, 3]");
private static final String ALPHABET = " \t\n'\"(),.*=<>!-+[]{}$/#_abcXYZ019äé😀\\;:%";
private static final List<String> TOKENS = List.of(
"SELECT", "FROM", "WHERE", "AS", "AND", "OR", "NOT", "TRUE", "FALSE", "NULL", "topic()", "topic(2)",
"topic(0)", "startswith(", "endswith(", "clientid()", "'x'", "\"y\"", "''", "42", "-1.5", "1e400",
"99999999999999999999", "*", ",", "(", ")", ".", "=", "<>", "!=", "<", "<=", ">", ">=", "a.b", "IN", "[", "]");
"topic(0)", "startswith(", "endswith(", "clientid()", "timestamp()", "accountid()", "newuuid()", "isNull(",
"isUndefined(", "principal()", "'x'", "\"y\"", "''", "42", "-1.5", "1e400", "99999999999999999999",
"*", ",", "(", ")", ".", "=", "<>", "!=", "<", "<=", ">", ">=", "a.b", "IN", "[", "]", "[1, 'a']", "arr");
private static final List<String> TOPICS = List.of("a/b/c", "$aws/things/x/shadow/update/accepted", "", "a");
@@ -59,7 +63,7 @@ class RuleSqlFuzzTest {
bytes(""),
new byte[] {(byte) 0xff, (byte) 0xfe, 0x00, 0x7b});
private final RuleSqlEvaluator evaluator = new RuleSqlEvaluator(new ObjectMapper());
private final RuleSqlEvaluator evaluator = new RuleSqlEvaluator(new ObjectMapper(), Clock.systemUTC());
@Test
void theParserOnlyEverThrowsRuleSqlParseExceptionAndTheEvaluatorNeverThrows() {
@@ -109,7 +113,8 @@ class RuleSqlFuzzTest {
}
for (String topic : TOPICS) {
for (byte[] payload : PAYLOADS) {
assertDoesNotThrow(() -> evaluator.evaluate("fuzz", query, topic, payload),
assertDoesNotThrow(() -> evaluator.evaluate("fuzz", query,
new RuleSqlContext(topic, topic.isEmpty() ? null : "fuzz-client", "000000000000"), payload),
() -> "Evaluator threw for statement [" + sql + "] on topic [" + topic + "] with payload "
+ new String(payload, StandardCharsets.UTF_8));
}
@@ -0,0 +1,126 @@
package io.github.hectorvent.floci.services.iot.rules;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Aliased;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.ArrayLiteral;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Call;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Comparison;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Conjunction;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Disjunction;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Membership;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Negation;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Operator;
import io.github.hectorvent.floci.services.iot.rules.RuleSql.Path;
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.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class RuleSqlParserFunctionsTest {
@ParameterizedTest
@CsvSource({
"clientid, clientid",
"CLIENTID, clientid",
"timestamp, timestamp",
"accountid, accountid",
"newuuid, newuuid",
"NewUUID, newuuid"
})
void parsesTheMessageFunctionsWithoutArgumentsUnderTheirCanonicalName(String written, String canonical) {
RuleSql query = RuleSqlParser.parse("SELECT " + written + "() FROM 'a/b' WHERE " + written + "() = 'x'");
assertEquals(List.of(new Aliased(new Call(canonical, List.of()), canonical)), query.projections());
assertEquals(new Comparison(new Call(canonical, List.of()), Operator.EQUAL, RuleSql.text("x")), query.where());
}
@ParameterizedTest
@CsvSource({
"isNull, isNull",
"isnull, isNull",
"ISNULL, isNull",
"isUndefined, isUndefined",
"isundefined, isUndefined"
})
void parsesIsNullAndIsUndefinedWithOneArgumentUnderTheirCanonicalName(String written, String canonical) {
RuleSql query = RuleSqlParser.parse("SELECT " + written + "(a.b) FROM 'a/b' WHERE " + written + "(topic(3))");
assertEquals(List.of(new Aliased(new Call(canonical, List.of(new Path(List.of("a", "b")))), canonical)),
query.projections());
assertEquals(new Call(canonical, List.of(new Call("topic", List.of(RuleSql.number(3))))), query.where());
}
@Test
void parsesInAgainstAFieldAndAgainstAnArrayLiteral() {
assertEquals(new Membership(new Path(List.of("x")), new Path(List.of("arr"))),
RuleSqlParser.parse("SELECT * FROM 't' WHERE x IN arr").where());
assertEquals(new Membership(RuleSql.number(3), new ArrayLiteral(List.of(RuleSql.number(1), RuleSql.text("a")))),
RuleSqlParser.parse("SELECT * FROM 't' WHERE 3 in [1, 'a']").where());
}
@Test
void inBindsLikeAComparison() {
Membership membership = new Membership(new Path(List.of("a")), new ArrayLiteral(List.of(RuleSql.number(1))));
Comparison comparison = new Comparison(new Path(List.of("b")), Operator.EQUAL, RuleSql.number(2));
assertEquals(new Conjunction(membership, comparison),
RuleSqlParser.parse("SELECT * FROM 't' WHERE a IN [1] AND b = 2").where());
assertEquals(new Disjunction(comparison, membership),
RuleSqlParser.parse("SELECT * FROM 't' WHERE b = 2 OR a IN [1]").where());
assertEquals(new Negation(membership),
RuleSqlParser.parse("SELECT * FROM 't' WHERE NOT a IN [1]").where());
}
@Test
void parsesArrayLiteralsOfAnyShapeAndRequiresAnAliasToSelectOne() {
RuleSql query = RuleSqlParser.parse("SELECT [] AS empty, [1, 'a', TRUE, NULL, x.y, topic(1), [2]] AS mixed FROM 't'");
assertEquals(List.of(
new Aliased(new ArrayLiteral(List.of()), "empty"),
new Aliased(new ArrayLiteral(List.of(
RuleSql.number(1), RuleSql.text("a"), RuleSql.bool(true), RuleSql.nullValue(),
new Path(List.of("x", "y")), new Call("topic", List.of(RuleSql.number(1))),
new ArrayLiteral(List.of(RuleSql.number(2))))), "mixed")), query.projections());
assertEquals("[", assertThrows(RuleSqlParseException.class,
() -> RuleSqlParser.parse("SELECT [1] FROM 't'")).token());
}
@ParameterizedTest
@ValueSource(strings = {"index", "inbound", "int_value", "IN_flag", "isNullable", "isUndefinedYet", "timestamps"})
void aWordThatBeginsWithANewKeywordOrFunctionIsStillAFieldName(String field) {
assertEquals(List.of(new Aliased(new Path(List.of(field)), field)),
RuleSqlParser.parse("SELECT " + field + " FROM 't'").projections());
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"SELECT in FROM 't' | in",
"SELECT * FROM 't' WHERE x IN | ''",
"SELECT * FROM 't' WHERE IN [1] | IN",
"SELECT * FROM 't' WHERE x IN [1, | ''",
"SELECT * FROM 't' WHERE x IN [,] | ,",
"SELECT * FROM 't' WHERE x IN [1 2] | 2",
"SELECT * FROM 't' WHERE x IN [1]] | ]",
"SELECT * FROM 't' WHERE x IN (1, 2) | (",
"SELECT * FROM 't' WHERE x IN [1] IN [2] | IN",
"SELECT * FROM 't' WHERE x = 1 IN [1] | IN",
"SELECT * FROM 't' WHERE x NOT IN [1] | NOT",
"SELECT timestamp(1) FROM 't' | timestamp",
"SELECT clientid('x') FROM 't' | clientid",
"SELECT accountid(a) FROM 't' | accountid",
"SELECT newuuid(1) FROM 't' | newuuid",
"SELECT isNull() AS n FROM 't' | isNull",
"SELECT isNull(a, b) AS n FROM 't' | isNull",
"SELECT isUndefined() AS u FROM 't' | isUndefined",
"SELECT timestamp FROM 't' WHERE timestamp( | ''"
})
void rejectsMalformedUsesNamingTheToken(String sql, String token) {
RuleSqlParseException failure = assertThrows(RuleSqlParseException.class, () -> RuleSqlParser.parse(sql));
assertEquals(token, failure.token(), failure.getMessage());
}
}
@@ -143,16 +143,16 @@ class RuleSqlParserTest {
@Test
void reportsTheOffendingTokenAndPositionOfAnUnsupportedFunction() {
RuleSqlParseException failure = assertThrows(RuleSqlParseException.class,
() -> RuleSqlParser.parse("SELECT clientid() FROM 'a/b'"));
() -> RuleSqlParser.parse("SELECT principal() FROM 'a/b'"));
assertEquals("clientid", failure.token());
assertEquals("principal", failure.token());
assertEquals(7, failure.position());
assertTrue(failure.getMessage().contains("clientid"), failure.getMessage());
assertTrue(failure.getMessage().contains("principal"), failure.getMessage());
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"SELECT * FROM 'a/b' WHERE state IN ('on') | IN",
"SELECT * FROM 'a/b' WHERE state IN ('on') | (",
"SELECT * FROM 'a/b' WHERE state IS NULL | IS",
"SELECT CASE WHEN a THEN 1 END FROM 'a/b' | WHEN",
"SELECT * FROM 'a/b' WHERE encode(a, 'base64') = 'x'| encode",