mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(athena): run Trino's multi-argument UNNEST on DuckDB (#8683)
* fix(athena): run Trino's multi-argument UNNEST on DuckDB * test(athena): pin an array of rows as one UNNEST column, as on Athena * refactor(athena): share identifierEnd and skipSpaceAndComments with AthenaIcebergStatements
This commit is contained in:
1 parent
8349e690ca
commit
f0b8368a9e
6 files changed
+395
-50
No files matched your search
@@ -122,6 +122,7 @@ Athena engine version 3 runs Trino SQL; Floci runs it on DuckDB, so a few Trino
|
||||
|
||||
- **JSON functions.** `json_extract_scalar`, `json_parse`, `json_format`, `json_size` and `is_json_scalar` are defined for every query and answer as Trino does: `json_extract_scalar` returns a scalar as text and `NULL` for an object, an array, a JSON `null` or a missing path, and `json_parse` and `json_format` give compact JSON. Their paths accept Trino's bracketed member names (`$["a b"]`). `json_extract` and `json_array_length` are DuckDB's own and already match. `json_array_get` and `json_array_contains` are not bridged.
|
||||
- **Types in `CAST` and `TRY_CAST`.** `ARRAY<T>` and `ARRAY(T)` become DuckDB's `T[]`, `MAP<K, V>` becomes `MAP(K, V)` and `ROW(name T, ...)` becomes `STRUCT(name T, ...)`, so `CROSS JOIN UNNEST(CAST(json_parse(col) AS ARRAY<JSON>)) AS t(item)` works.
|
||||
- **Multi-argument `UNNEST`.** `CROSS JOIN UNNEST(a, b) AS t (x, y)`, which zips the arrays by position and pads the shorter with `NULL` (a `NULL` array counting as empty), runs as `CROSS JOIN LATERAL (SELECT unnest(a), unnest(b)) AS t (x, y)`, which DuckDB zips and pads the same way, under `LEFT JOIN ... ON TRUE` too. The alias and a column list naming one column per array are needed; a source without them is left for DuckDB to reject. A single-argument `UNNEST` of an array, with or without `WITH ORDINALITY`, runs as written. Not yet bridged: a multi-argument `UNNEST ... WITH ORDINALITY`, and `UNNEST` of a `MAP` into key and value columns.
|
||||
- **Result types.** A JSON result column is reported as `json` and an unsigned count such as `json_array_length` as `bigint`, as Athena reports them.
|
||||
|
||||
## Format inference
|
||||
|
||||
@@ -359,7 +359,7 @@ public class AthenaIcebergStatements {
|
||||
* statement, or one writing another catalog's table.
|
||||
*/
|
||||
static Target target(String query) {
|
||||
int start = statementStart(query);
|
||||
int start = TrinoSqlCompatibility.skipSpaceAndComments(query, 0);
|
||||
Matcher dml = DML.matcher(query).region(start, query.length());
|
||||
if (!dml.lookingAt()) {
|
||||
return null;
|
||||
@@ -369,7 +369,7 @@ public class AthenaIcebergStatements {
|
||||
int nameStart = i;
|
||||
int nameEnd;
|
||||
while (true) {
|
||||
int partEnd = identifierEnd(query, i);
|
||||
int partEnd = TrinoSqlCompatibility.identifierEnd(query, i);
|
||||
if (partEnd == i) {
|
||||
return null;
|
||||
}
|
||||
@@ -394,23 +394,6 @@ public class AthenaIcebergStatements {
|
||||
};
|
||||
}
|
||||
|
||||
/** Where the statement starts, past leading whitespace and comments. */
|
||||
private static int statementStart(String query) {
|
||||
int i = 0;
|
||||
while (true) {
|
||||
i = skipSpaces(query, i);
|
||||
if (query.startsWith("--", i)) {
|
||||
int lineEnd = query.indexOf('\n', i);
|
||||
i = lineEnd < 0 ? query.length() : lineEnd + 1;
|
||||
} else if (query.startsWith("/*", i)) {
|
||||
int commentEnd = query.indexOf("*/", i + 2);
|
||||
i = commentEnd < 0 ? query.length() : commentEnd + 2;
|
||||
} else {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int skipSpaces(String query, int i) {
|
||||
while (i < query.length() && Character.isWhitespace(query.charAt(i))) {
|
||||
i++;
|
||||
@@ -418,32 +401,6 @@ public class AthenaIcebergStatements {
|
||||
return i;
|
||||
}
|
||||
|
||||
/** The index just past the identifier at {@code i}, or {@code i} when none starts there. */
|
||||
private static int identifierEnd(String query, int i) {
|
||||
if (i >= query.length()) {
|
||||
return i;
|
||||
}
|
||||
if (query.charAt(i) == '"') {
|
||||
int j = i + 1;
|
||||
while (j < query.length()) {
|
||||
if (query.charAt(j) == '"') {
|
||||
if (j + 1 < query.length() && query.charAt(j + 1) == '"') {
|
||||
j += 2;
|
||||
continue;
|
||||
}
|
||||
return j + 1;
|
||||
}
|
||||
j++;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
int j = i;
|
||||
while (j < query.length() && (Character.isLetterOrDigit(query.charAt(j)) || query.charAt(j) == '_')) {
|
||||
j++;
|
||||
}
|
||||
return j;
|
||||
}
|
||||
|
||||
// ─── VACUUM ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.floci.aws.services.athena;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
@@ -27,6 +28,8 @@ import java.util.regex.Pattern;
|
||||
* which can name any member, a bracketed {@code ["a\"b"]} included. A path with a wildcard
|
||||
* keeps its JSONPath form, and the macros still turn a computed path's bracketed members
|
||||
* ({@code $["a b"]}) into DuckDB's {@code $."a b"}.</li>
|
||||
* <li>a multi-argument {@code UNNEST} source, which DuckDB's one-argument {@code unnest} rejects, into a
|
||||
* lateral subquery holding one {@code unnest} per array (see {@link #multiArgumentUnnest}).</li>
|
||||
* </ul>
|
||||
*/
|
||||
final class TrinoSqlCompatibility {
|
||||
@@ -49,6 +52,10 @@ final class TrinoSqlCompatibility {
|
||||
|
||||
private static final List<String> CAST_FUNCTIONS = List.of("TRY_CAST", "CAST");
|
||||
private static final List<String> PATH_FUNCTIONS = List.of("JSON_EXTRACT_SCALAR", "JSON_EXTRACT", "JSON_SIZE");
|
||||
/** Words that can follow a {@code FROM} source without naming it, so never an alias given without {@code AS}. */
|
||||
private static final Set<String> CLAUSE_KEYWORDS = Set.of("WHERE", "ON", "USING", "JOIN", "CROSS", "INNER",
|
||||
"LEFT", "RIGHT", "FULL", "NATURAL", "GROUP", "HAVING", "ORDER", "LIMIT", "OFFSET", "FETCH", "UNION",
|
||||
"INTERSECT", "EXCEPT", "WINDOW", "WITH");
|
||||
private static final Pattern MULTI_WORD_TYPE = Pattern.compile(
|
||||
"DOUBLE\\s+PRECISION|(TIMESTAMP|TIME)(\\s*\\(\\s*\\d+\\s*\\))?\\s+WITH(OUT)?\\s+TIME\\s+ZONE",
|
||||
Pattern.CASE_INSENSITIVE);
|
||||
@@ -56,7 +63,7 @@ final class TrinoSqlCompatibility {
|
||||
private TrinoSqlCompatibility() {
|
||||
}
|
||||
|
||||
/** {@code sql} with Trino's cast types and literal JSON paths in DuckDB's syntax. */
|
||||
/** {@code sql} with Trino's cast types, literal JSON paths and multi-argument UNNEST in DuckDB's syntax. */
|
||||
static String translate(String sql) {
|
||||
if (sql == null) {
|
||||
return null;
|
||||
@@ -70,6 +77,12 @@ final class TrinoSqlCompatibility {
|
||||
i = skipped;
|
||||
continue;
|
||||
}
|
||||
Rewrite unnest = multiArgumentUnnest(sql, i);
|
||||
if (unnest != null) {
|
||||
out.append(unnest.text());
|
||||
i = unnest.end();
|
||||
continue;
|
||||
}
|
||||
String function = functionAt(sql, i);
|
||||
int open = function == null ? -1 : sql.indexOf('(', i + function.length());
|
||||
int close = open < 0 ? -1 : matchingParen(sql, open);
|
||||
@@ -106,6 +119,131 @@ final class TrinoSqlCompatibility {
|
||||
return translate(arguments.get(0)) + "," + (pointer == null ? translate(path) : " " + pointer);
|
||||
}
|
||||
|
||||
/** The text replacing a construct, and the index just past the construct it replaces. */
|
||||
private record Rewrite(String text, int end) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The multi-argument {@code UNNEST} source starting at {@code i}, rewritten for DuckDB; null for anything else.
|
||||
*
|
||||
* <p>Trino zips the arrays of a multi-argument {@code UNNEST} into one row per position, padding the shorter ones
|
||||
* with NULL, a NULL array counting as an empty one:
|
||||
*
|
||||
* <pre>CROSS JOIN UNNEST(names, vals) AS facet (column_name, value)</pre>
|
||||
*
|
||||
* DuckDB's {@code unnest} takes one argument, but a {@code SELECT} holding several {@code unnest} calls zips them
|
||||
* the same way, NULL padding included, so the source becomes a lateral subquery with one call per array:
|
||||
*
|
||||
* <pre>CROSS JOIN LATERAL (SELECT unnest(names), unnest(vals)) AS facet (column_name, value)</pre>
|
||||
*
|
||||
* Checked against Athena (engine v3): the shorter array on either side, a NULL array beside another, both empty
|
||||
* under {@code CROSS JOIN} (no rows) and under {@code LEFT JOIN ... ON TRUE} (one row of NULLs). The column list
|
||||
* names the subquery's columns, as in Trino, rather than aliases inside it: DuckDB would resolve an array that
|
||||
* names an outer column called like an earlier alias to that alias. Each array is translated too, so a
|
||||
* {@code CAST(... AS ARRAY<JSON>)} in one still becomes DuckDB's, and comments in the arrays or the column list are
|
||||
* dropped, so a line comment cannot run on over the text around it.
|
||||
*
|
||||
* <p>Any {@code UNNEST(} with two or more arguments, an alias and a column list naming one column per array is
|
||||
* rewritten; that is only ever a {@code FROM} source. Without a column list, with one that doesn't name every
|
||||
* array, or with a clause keyword where an alias given without {@code AS} would be, the source is left as written
|
||||
* for DuckDB to reject. A single-argument {@code UNNEST} of an array needs nothing: DuckDB runs it as Athena does,
|
||||
* {@code WITH ORDINALITY} included.
|
||||
*
|
||||
* <p>TODO: left as written are a multi-argument {@code UNNEST ... WITH ORDINALITY}, one without a column list,
|
||||
* which Trino names by position, and a {@code MAP} argument, which Athena expands into key and value columns (a
|
||||
* single-argument {@code UNNEST} of a {@code MAP} fails on DuckDB too).
|
||||
*/
|
||||
private static Rewrite multiArgumentUnnest(String sql, int i) {
|
||||
// A name ending in unnest, or a qualified one (schema.unnest), is some other function.
|
||||
if (!sql.regionMatches(true, i, "UNNEST", 0, 6)
|
||||
|| i > 0 && (isIdentifierChar(sql.charAt(i - 1)) || sql.charAt(i - 1) == '.')) {
|
||||
return null;
|
||||
}
|
||||
int open = skipSpaceAndComments(sql, i + 6);
|
||||
int close = open < sql.length() && sql.charAt(open) == '(' ? matchingParen(sql, open) : -1;
|
||||
if (close < 0) {
|
||||
return null;
|
||||
}
|
||||
List<String> arrays = splitTopLevel(sql.substring(open + 1, close), true);
|
||||
if (arrays.size() < 2) {
|
||||
return null;
|
||||
}
|
||||
// The alias, after an optional AS; without AS, a word that ends the source is not one.
|
||||
int aliasStart = skipSpaceAndComments(sql, close + 1);
|
||||
boolean as = sql.regionMatches(true, aliasStart, "AS", 0, 2) && identifierEnd(sql, aliasStart) == aliasStart + 2;
|
||||
if (as) {
|
||||
aliasStart = skipSpaceAndComments(sql, aliasStart + 2);
|
||||
}
|
||||
int aliasEnd = identifierEnd(sql, aliasStart);
|
||||
String alias = sql.substring(aliasStart, aliasEnd);
|
||||
if (alias.isEmpty() || !as && CLAUSE_KEYWORDS.contains(alias.toUpperCase(Locale.ROOT))) {
|
||||
return null;
|
||||
}
|
||||
int columnsOpen = skipSpaceAndComments(sql, aliasEnd);
|
||||
int columnsClose = columnsOpen < sql.length() && sql.charAt(columnsOpen) == '(' ? matchingParen(sql, columnsOpen) : -1;
|
||||
if (columnsClose < 0) {
|
||||
return null;
|
||||
}
|
||||
String columnList = withoutComments(sql.substring(columnsOpen + 1, columnsClose));
|
||||
List<String> columns = splitTopLevel(columnList, true).stream().map(String::strip).toList();
|
||||
if (columns.size() != arrays.size()
|
||||
|| !columns.stream().allMatch(column -> !column.isEmpty() && identifierEnd(column, 0) == column.length())) {
|
||||
return null;
|
||||
}
|
||||
StringBuilder lateral = new StringBuilder("LATERAL (SELECT ");
|
||||
for (int k = 0; k < arrays.size(); k++) {
|
||||
lateral.append(k > 0 ? ", " : "").append("unnest(")
|
||||
.append(translate(withoutComments(arrays.get(k))).strip()).append(')');
|
||||
}
|
||||
return new Rewrite(lateral.append(") AS ").append(alias).append(" (").append(String.join(", ", columns))
|
||||
.append(')').toString(), columnsClose + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* The index of the first character at or after {@code i} that is neither whitespace nor in a comment.
|
||||
* {@link AthenaIcebergStatements} finds where a statement starts with it.
|
||||
*/
|
||||
static int skipSpaceAndComments(String sql, int i) {
|
||||
while (i < sql.length()) {
|
||||
if (Character.isWhitespace(sql.charAt(i))) {
|
||||
i++;
|
||||
} else if (sql.startsWith("--", i) || sql.startsWith("/*", i)) {
|
||||
i = skipLiteralOrComment(sql, i);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
/**
|
||||
* The index just past the bare or double-quoted identifier at {@code i}, or {@code i} when none starts there.
|
||||
* A double quote that never closes starts none, so neither an {@code UNNEST} alias nor a table name can run on
|
||||
* to the end of the query. {@link AthenaIcebergStatements} reads the table a statement writes with it.
|
||||
*/
|
||||
static int identifierEnd(String sql, int i) {
|
||||
if (i < sql.length() && sql.charAt(i) == '"') {
|
||||
// Not skipQuoted, which runs to the end of an unclosed quote rather than reporting it.
|
||||
int j = i + 1;
|
||||
while (j < sql.length()) {
|
||||
if (sql.charAt(j) == '"') {
|
||||
if (j + 1 < sql.length() && sql.charAt(j + 1) == '"') {
|
||||
j += 2;
|
||||
continue;
|
||||
}
|
||||
return j + 1;
|
||||
}
|
||||
j++;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
int end = i;
|
||||
while (end < sql.length() && isIdentifierChar(sql.charAt(end))) {
|
||||
end++;
|
||||
}
|
||||
return end;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code literal}, a SQL string holding a Trino JSONPath made of member names ({@code .a},
|
||||
* {@code ["a b"]}) and array indexes, as a SQL string holding the JSON Pointer to the same value;
|
||||
@@ -404,8 +542,8 @@ final class TrinoSqlCompatibility {
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code parameters} split at its top-level commas, skipping quoted identifiers and, for
|
||||
* function arguments, string literals and comments too.
|
||||
* {@code parameters} split at its top-level commas, outside parentheses and brackets, skipping quoted
|
||||
* identifiers and, for function arguments, string literals and comments too.
|
||||
*/
|
||||
private static List<String> splitTopLevel(String parameters, boolean sql) {
|
||||
List<String> parts = new ArrayList<>();
|
||||
@@ -419,9 +557,9 @@ final class TrinoSqlCompatibility {
|
||||
i = skipped;
|
||||
continue;
|
||||
}
|
||||
if (c == '<' && !sql || c == '(') {
|
||||
if (c == '<' && !sql || c == '(' || c == '[') {
|
||||
depth++;
|
||||
} else if (c == '>' && !sql || c == ')') {
|
||||
} else if (c == '>' && !sql || c == ')' || c == ']') {
|
||||
depth--;
|
||||
} else if (c == ',' && depth == 0) {
|
||||
parts.add(parameters.substring(start, i));
|
||||
|
||||
@@ -109,6 +109,7 @@ class AthenaIcebergStatementsTest {
|
||||
assertNull(AthenaIcebergStatements.target("UPDATE other_catalog.lake.events SET a = 1"));
|
||||
assertNull(AthenaIcebergStatements.target("SELECT * FROM events"));
|
||||
assertNull(AthenaIcebergStatements.target("INSERT INTO"));
|
||||
assertNull(AthenaIcebergStatements.target("INSERT INTO \"events VALUES (1)"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
package io.floci.aws.services.athena;
|
||||
|
||||
import io.floci.aws.services.floci.duck.FlociDuckClient;
|
||||
import io.floci.aws.testing.SidecarContainersProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Trino's multi-argument {@code UNNEST}, run on the real floci-duck sidecar through {@link TrinoSqlCompatibility}. The
|
||||
* tests marked so expect the rows Athena (engine v3) returned for the same query.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(SidecarContainersProfile.class)
|
||||
class AthenaMultiArgumentUnnestSidecarIntegrationTest {
|
||||
|
||||
@Inject
|
||||
FlociDuckClient duck;
|
||||
|
||||
@BeforeAll
|
||||
static void requireDocker() {
|
||||
SidecarContainersProfile.requireDocker();
|
||||
}
|
||||
|
||||
/**
|
||||
* Each row's values in {@code columns} order, as text, {@code null} for NULL. A number is given in its plain
|
||||
* form, since the sidecar's JSON gives DuckDB's HUGEINT counts as {@code 1.0}.
|
||||
*/
|
||||
private List<List<String>> rows(String trinoSql, String... columns) {
|
||||
List<List<String>> rows = new ArrayList<>();
|
||||
for (Map<String, Object> row : duck.query(TrinoSqlCompatibility.translate(trinoSql),
|
||||
TrinoSqlCompatibility.FUNCTION_MACROS)) {
|
||||
rows.add(Arrays.stream(columns).map(column -> text(row.get(column))).toList());
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
private static String text(Object value) {
|
||||
if (value instanceof Number number) {
|
||||
return new BigDecimal(number.toString()).stripTrailingZeros().toPlainString();
|
||||
}
|
||||
return value == null ? null : String.valueOf(value);
|
||||
}
|
||||
|
||||
/** As on Athena. */
|
||||
@Test
|
||||
void theArraysAreZippedByPositionAndTheShorterPaddedWithNull() {
|
||||
assertEquals(List.of(List.of("1", "a"), Arrays.asList("2", null), Arrays.asList("3", null)),
|
||||
rows("SELECT x, y FROM UNNEST(ARRAY[1, 2, 3], ARRAY['a']) AS t (x, y) ORDER BY x", "x", "y"));
|
||||
}
|
||||
|
||||
/** As on Athena. */
|
||||
@Test
|
||||
void aCrossJoinedUnnestReadsTheColumnsOfEachRowItJoins() {
|
||||
assertEquals(List.of(List.of("1", "1", "a"), List.of("1", "2", "b"), Arrays.asList("1", null, "c")),
|
||||
rows("SELECT s.id, t.x, t.y FROM (VALUES (1, ARRAY[1, 2], ARRAY['a', 'b', 'c'])) AS s (id, xs, ys) "
|
||||
+ "CROSS JOIN UNNEST(xs, ys) AS t (x, y) ORDER BY t.y", "id", "x", "y"));
|
||||
}
|
||||
|
||||
/** As on Athena: a NULL array is an empty one, padded beside another. */
|
||||
@Test
|
||||
void aNullArrayIsPaddedBesideAnother() {
|
||||
assertEquals(List.of(Arrays.asList("1", "1", null), Arrays.asList("1", "2", null)),
|
||||
rows("SELECT s.id, t.x, t.y FROM (VALUES (1, ARRAY[1, 2], CAST(NULL AS ARRAY(VARCHAR)))) "
|
||||
+ "AS s (id, xs, ys) CROSS JOIN UNNEST(xs, ys) AS t (x, y) ORDER BY t.x", "id", "x", "y"));
|
||||
}
|
||||
|
||||
/** As on Athena: empty arrays give no rows to a cross join and one row of NULLs to a left join. */
|
||||
@Test
|
||||
void emptyArraysGiveNoRowsToACrossJoinAndOneOfNullsToALeftJoin() {
|
||||
String source = "FROM (VALUES (2, CAST(ARRAY[] AS ARRAY(INTEGER)), CAST(ARRAY[] AS ARRAY(VARCHAR)))) "
|
||||
+ "AS s (id, xs, ys) ";
|
||||
|
||||
assertEquals(List.of(), rows("SELECT s.id, t.x, t.y " + source + "CROSS JOIN UNNEST(xs, ys) AS t (x, y)",
|
||||
"id", "x", "y"));
|
||||
assertEquals(List.of(Arrays.asList("2", null, null)),
|
||||
rows("SELECT s.id, t.x, t.y " + source + "LEFT JOIN UNNEST(xs, ys) AS t (x, y) ON TRUE", "id", "x", "y"));
|
||||
}
|
||||
|
||||
/**
|
||||
* As on Athena: an array naming an outer column reads that column, even when an earlier column of the source has
|
||||
* its name. Aliases inside the subquery would have taken it.
|
||||
*/
|
||||
@Test
|
||||
void anArrayReadsTheOuterColumnItNamesWhateverTheSourcesColumnsAreCalled() {
|
||||
assertEquals(List.of(List.of("id", "i1"), List.of("name", "n1")),
|
||||
rows("SELECT f.name, f.value FROM (VALUES (ARRAY['id', 'name'], 'i1', 'n1')) AS s (keys, id, name) "
|
||||
+ "CROSS JOIN UNNEST(keys, ARRAY[id, name]) AS f (name, value) ORDER BY 1", "name", "value"));
|
||||
}
|
||||
|
||||
/**
|
||||
* As on Athena: an array of rows unnests into one row column beside another array, its fields not expanded,
|
||||
* whether they are named or not. Athena returns {@code {v=1}} for {@code x}, typed {@code row(v integer)}; the
|
||||
* sidecar's JSON gives no struct values, so its type is compared.
|
||||
*/
|
||||
@Test
|
||||
void anArrayOfRowsUnnestsIntoOneRowColumn() {
|
||||
assertEquals(List.of(List.of("STRUCT(v INTEGER)", "a")),
|
||||
rows("SELECT typeof(x) AS tx, y FROM UNNEST(ARRAY[CAST(ROW(1) AS ROW(v INTEGER))], ARRAY['a']) "
|
||||
+ "AS t (x, y)", "tx", "y"));
|
||||
}
|
||||
|
||||
/** Access Graph's facet query: each scanned row unpivoted into (column name, value) pairs, then counted. */
|
||||
@Test
|
||||
void aFacetQueryCountsEachColumnsValues() {
|
||||
assertEquals(List.of(List.of("identity", "u1", "1", "1"), List.of("identity", "u2", "1", "0"),
|
||||
List.of("target_resource", "r1", "1", "1")),
|
||||
rows("WITH raw_data AS (SELECT * FROM (VALUES ('u1', 'r1', 'db'), ('u2', NULL, 'ssh')) "
|
||||
+ "AS v (identity, target_resource, target_kind)), "
|
||||
+ "flagged_raw_data AS (SELECT identity, target_resource, target_kind, "
|
||||
+ "(target_kind = 'db') AS matched FROM \"raw_data\") "
|
||||
+ "SELECT facet.column_name, facet.value, COUNT(*) AS unfiltered_count, "
|
||||
+ "COUNT_IF(matched) AS filtered_count FROM \"flagged_raw_data\" "
|
||||
+ "CROSS JOIN UNNEST(ARRAY['identity', 'target_resource'], ARRAY[CAST(identity AS VARCHAR), "
|
||||
+ "CASE WHEN target_kind IN ('ssh') THEN NULL ELSE CAST(target_resource AS VARCHAR) END]) "
|
||||
+ "AS facet (column_name, value) WHERE facet.value <> '' "
|
||||
+ "GROUP BY facet.column_name, facet.value ORDER BY 1, 2",
|
||||
"column_name", "value", "unfiltered_count", "filtered_count"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anArrayCastFromJsonUnnestsBesideAnotherArray() {
|
||||
assertEquals(List.of(List.of("1", "a"), List.of("2", "b")),
|
||||
rows("SELECT json_extract_scalar(item, '$.id') AS id, tag FROM (VALUES ('[{\"id\":1},{\"id\":2}]')) "
|
||||
+ "AS t (col) CROSS JOIN UNNEST(CAST(json_parse(col) AS ARRAY<JSON>), ARRAY['a', 'b']) "
|
||||
+ "AS u (item, tag) ORDER BY id", "id", "tag"));
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package io.floci.aws.services.athena;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class TrinoSqlCompatibilityTest {
|
||||
@@ -76,6 +78,114 @@ class TrinoSqlCompatibilityTest {
|
||||
assertEquals(sql, TrinoSqlCompatibility.translate(sql));
|
||||
}
|
||||
|
||||
/** The shape of a facet query: one row per (column name, value) pair of each source row. */
|
||||
@Test
|
||||
void aMultiArgumentUnnestBecomesALateralSubqueryWithOneUnnestPerArray() {
|
||||
assertEquals("SELECT facet.column_name, facet.value FROM events "
|
||||
+ "CROSS JOIN LATERAL (SELECT unnest(ARRAY['region', 'status']), "
|
||||
+ "unnest(ARRAY[CAST(region AS VARCHAR), status])) AS facet (column_name, value) "
|
||||
+ "WHERE facet.value <> ''",
|
||||
TrinoSqlCompatibility.translate("SELECT facet.column_name, facet.value FROM events "
|
||||
+ "CROSS JOIN UNNEST(ARRAY['region', 'status'], ARRAY[CAST(region AS VARCHAR), status]) "
|
||||
+ "AS facet (column_name, value) WHERE facet.value <> ''"));
|
||||
}
|
||||
|
||||
/** Access Graph's facet query writes the source over several lines, as some clients send CRLF. */
|
||||
@Test
|
||||
void aMultiLineUnnestIsRewrittenWhateverItsLineBreaks() {
|
||||
for (String lineBreak : List.of("\n", "\r\n")) {
|
||||
String sql = String.join(lineBreak, "FROM \"flagged_raw_data\"", "\tCROSS JOIN UNNEST(",
|
||||
"\t\tARRAY['identity', 'target_resource'],", "\t\tARRAY[CAST(identity AS VARCHAR), target_resource]",
|
||||
"\t) AS facet (column_name, value)", "\tWHERE facet.value <> ''");
|
||||
|
||||
assertEquals("FROM \"flagged_raw_data\"" + lineBreak + "\tCROSS JOIN LATERAL (SELECT "
|
||||
+ "unnest(ARRAY['identity', 'target_resource']), "
|
||||
+ "unnest(ARRAY[CAST(identity AS VARCHAR), target_resource])) AS facet (column_name, value)"
|
||||
+ lineBreak + "\tWHERE facet.value <> ''",
|
||||
TrinoSqlCompatibility.translate(sql));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFirstCommaOrLeftJoinSourceAndAnAliasWithoutAsAreRewrittenToo() {
|
||||
assertEquals("SELECT * FROM LATERAL (SELECT unnest(a), unnest(b)) AS u (x, y)",
|
||||
TrinoSqlCompatibility.translate("SELECT * FROM UNNEST(a, b) AS u (x, y)"));
|
||||
assertEquals("SELECT * FROM t, LATERAL (SELECT unnest(a), unnest(b)) AS u (x, y)",
|
||||
TrinoSqlCompatibility.translate("SELECT * FROM t, UNNEST(a, b) u (x, y)"));
|
||||
assertEquals("SELECT * FROM t LEFT JOIN LATERAL (SELECT unnest(a), unnest(b)) AS u (x, y) ON TRUE",
|
||||
TrinoSqlCompatibility.translate("SELECT * FROM t LEFT JOIN unnest (a, b) AS u (x, y) ON TRUE"));
|
||||
}
|
||||
|
||||
/** Commas inside an array, a call, a literal or a CASE belong to that argument, not to UNNEST's list. */
|
||||
@Test
|
||||
void commasInsideAnUnnestArgumentDoNotSplitIt() {
|
||||
assertEquals("SELECT * FROM t CROSS JOIN LATERAL (SELECT unnest(ARRAY[f(a, b), 'c,d']), "
|
||||
+ "unnest(ARRAY[CASE WHEN k IN ('x', 'y') THEN NULL ELSE k END, z])) AS u (p, q)",
|
||||
TrinoSqlCompatibility.translate("SELECT * FROM t CROSS JOIN UNNEST(ARRAY[f(a, b), 'c,d'], "
|
||||
+ "ARRAY[CASE WHEN k IN ('x', 'y') THEN NULL ELSE k END, z]) AS u (p, q)"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void eachUnnestArgumentIsTranslatedItself() {
|
||||
assertEquals("SELECT * FROM t CROSS JOIN LATERAL (SELECT unnest(CAST(json_parse(a) AS JSON[])), "
|
||||
+ "unnest(b)) AS u (x, y)",
|
||||
TrinoSqlCompatibility.translate(
|
||||
"SELECT * FROM t CROSS JOIN UNNEST(CAST(json_parse(a) AS ARRAY<JSON>), b) AS u (x, y)"));
|
||||
}
|
||||
|
||||
/** A line comment in an argument would otherwise run on over the rest of the rewritten source. */
|
||||
@Test
|
||||
void commentsInAnUnnestSourceAreDroppedAndQuotedNamesKeepTheirQuoting() {
|
||||
assertEquals("SELECT * FROM t CROSS JOIN LATERAL (SELECT unnest(a), unnest(b)) AS \"U\" (\"Key\", \"v w\")",
|
||||
TrinoSqlCompatibility.translate("SELECT * FROM t CROSS JOIN UNNEST(a -- names\n, b /* values */) "
|
||||
+ "/* c */ AS -- d\n \"U\" (\"Key\" /* k */, \"v w\" -- v\n)"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Without a column list there is nothing to name the subquery's columns; with WITH ORDINALITY, a list that
|
||||
* doesn't name every array, a clause keyword where an alias would be, or an alias whose quote never closes, the
|
||||
* source is left for DuckDB to report. So is a function only named like it.
|
||||
*/
|
||||
@Test
|
||||
void unnestSourcesTheRewriteCannotKeepFaithfulAreLeftAsWritten() {
|
||||
for (String sql : List.of(
|
||||
"SELECT * FROM t CROSS JOIN UNNEST(a, b) AS u",
|
||||
"SELECT * FROM t CROSS JOIN UNNEST(a, b) WHERE (x, y) = (1, 2)",
|
||||
"SELECT * FROM t CROSS JOIN UNNEST(a, b) WITH ORDINALITY AS u (x, y, n)",
|
||||
"SELECT * FROM t CROSS JOIN UNNEST(a, b) AS u (x)",
|
||||
"SELECT * FROM t CROSS JOIN UNNEST(a, b) AS u (x, y + 1)",
|
||||
"SELECT * FROM t CROSS JOIN UNNEST(a, b) AS \"u (x, y)",
|
||||
"SELECT * FROM t CROSS JOIN UNNEST(a) AS u (x)",
|
||||
"SELECT * FROM t CROSS JOIN my_unnest(a, b) AS u (x, y)",
|
||||
"SELECT * FROM t CROSS JOIN my_schema.unnest(a, b) AS u (x, y)",
|
||||
"SELECT * FROM t CROSS JOIN UNNEST(a, b")) {
|
||||
assertEquals(sql, TrinoSqlCompatibility.translate(sql));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void unnestInsideALiteralAQuotedIdentifierOrACommentIsNotRewritten() {
|
||||
String sql = "SELECT 'UNNEST(a, b) AS u (x, y)' AS \"UNNEST(a, b) AS u (x, y)\" "
|
||||
+ "/* UNNEST(a, b) AS u (x, y) */ FROM t -- UNNEST(a, b) AS u (x, y)";
|
||||
|
||||
assertEquals(sql, TrinoSqlCompatibility.translate(sql));
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyMultiArgumentUnnestInTheQueryIsRewritten() {
|
||||
assertEquals("SELECT * FROM t CROSS JOIN LATERAL (SELECT unnest(a), unnest(b)) AS u (x, y) "
|
||||
+ "CROSS JOIN LATERAL (SELECT unnest(c), unnest(d)) AS v (p, q)",
|
||||
TrinoSqlCompatibility.translate("SELECT * FROM t CROSS JOIN UNNEST(a, b) AS u (x, y) "
|
||||
+ "CROSS JOIN UNNEST(c, d) AS v (p, q)"));
|
||||
}
|
||||
|
||||
/** Brackets count when splitting arguments, so a JSON function given an array element still gets its path. */
|
||||
@Test
|
||||
void aJsonPathAfterAnArrayElementArgumentIsTranslated() {
|
||||
assertEquals("SELECT json_extract_scalar(ARRAY['{\"a\":1}', '{}'][1], '/a')",
|
||||
TrinoSqlCompatibility.translate("SELECT json_extract_scalar(ARRAY['{\"a\":1}', '{}'][1], '$.a')"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnbalancedCastIsReturnedAsWritten() {
|
||||
assertEquals("SELECT CAST(x AS ARRAY<JSON>", TrinoSqlCompatibility.translate("SELECT CAST(x AS ARRAY<JSON>"));
|
||||
|
||||
Reference in new issue
Block a user