fix(athena): answer Trino JSON functions and ARRAY<JSON> casts (#8407)

Athena queries go straight to DuckDB, which has no json_extract_scalar,
json_parse or json_format and cannot parse Trino's ARRAY<T> type
syntax, so `json_extract_scalar(col, '$.a')` and
`CAST(json_parse(col) AS ARRAY<JSON>)` both failed.

Every query now gets DuckDB macros for json_extract_scalar (a scalar as
text, NULL for an object, array, JSON null or missing path, as Trino),
json_parse, json_format, json_size and is_json_scalar, with Trino's
bracketed path members accepted. CAST and TRY_CAST target types are
rewritten to DuckDB's syntax: ARRAY<T> and ARRAY(T) to T[], MAP<K, V> to
MAP(K, V), ROW(...) to STRUCT(...). JSON result columns are reported as
json and unsigned counts as bigint, as Athena types them.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-15 00:19:11 -04:00
1 parent 982b1fb5ba
commit 9bee320d83
6 files changed
+670 -5

No files matched your search

+8
View File
@@ -116,6 +116,14 @@ results storage.
3. **Query execution**: The user's SQL is wrapped in `COPY (...) TO 's3://...' (FORMAT CSV, HEADER)` and executed. Results are written directly to the output S3 path.
4. **Results retrieval**: `GetQueryResults` reads the CSV back from S3 and returns it in the standard Athena `ResultSet` shape. Each column's `Type` comes from DuckDB describing the query, mapped to the Athena name (`bigint`, `integer`, `double`, `boolean`, `date`, `time`, `timestamp`, `decimal` and so on), with `Precision` and `Scale` for a decimal; a column whose type has no Athena name, such as an interval, and every column of a query DuckDB cannot describe are reported as `varchar`. DuckDB widens `sum` and `count_if` over integers to `HUGEINT`, which is reported as `bigint`, Trino's type for them; a sum past `bigint`'s range, which Athena fails with `NUMERIC_VALUE_OUT_OF_RANGE`, is returned instead.
## Trino SQL on DuckDB
Athena engine version 3 runs Trino SQL; Floci runs it on DuckDB, so a few Trino constructs are bridged before the query reaches the sidecar:
- **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.
- **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
**Iceberg tables are checked first**, ahead of the `StorageDescriptor` heuristic below: a table whose `Parameters.table_type` is `ICEBERG` (case-insensitive), as set by `pyiceberg`'s `GlueCatalog` and AWS's own Glue-Iceberg integration, is read via `iceberg_scan('<metadata_location>')`, using `Parameters.metadata_location` from the same Glue table. Iceberg tables never populate `InputFormat`/`SerializationLibrary` (they aren't read via a Hive input format), so without this check they always fell through to `read_csv_auto` and failed on the table's binary Parquet data files. `iceberg_scan` resolves the table through its real manifest list, so multi-snapshot tables (after updates, deletes, or repeated appends) read correctly instead of a naive glob picking up every data file ever written under the table's location. The `iceberg` DuckDB extension is installed and loaded once when the generated DDL contains at least one Iceberg table. A table flagged `ICEBERG` but missing `metadata_location` falls back to the format-sniffed heuristic below instead of emitting an unusable `iceberg_scan('')`.
@@ -228,13 +228,14 @@ public class AthenaService {
List<Table> projectionTables = tablesForProjectionCheck(database);
PartitionProjection.assertLocationTemplatesComplete(query, projectionTables);
PartitionProjection.assertInjectedColumnsFiltered(query, projectionTables);
String setupDdl = ddlBuilder.build(database);
String setupDdl = TrinoSqlCompatibility.FUNCTION_MACROS + ddlBuilder.build(database);
String duckQuery = TrinoSqlCompatibility.translate(query);
if (outputLocation != null) {
ensureOutputBucket(outputLocation);
}
duckClient.execute(query, setupDdl, outputLocation, accountId);
duckClient.execute(duckQuery, setupDdl, outputLocation, accountId);
if (outputLocation != null) {
resultColumnTypeStore.put(id, describeColumnTypes(query, setupDdl, accountId));
resultColumnTypeStore.put(id, describeColumnTypes(duckQuery, setupDdl, accountId));
}
return null;
})
@@ -1207,7 +1208,7 @@ public class AthenaService {
// TODO: Athena (engine v3) fails a sum past BIGINT's range with NUMERIC_VALUE_OUT_OF_RANGE;
// DuckDB's HUGEINT holds it, so floci returns the out-of-range value typed bigint instead.
// Casting HUGEINT result columns back to BIGINT would make DuckDB fail the query too.
case "BIGINT", "HUGEINT" -> "bigint";
case "BIGINT", "HUGEINT", "UBIGINT" -> "bigint";
case "INTEGER" -> "integer";
case "SMALLINT" -> "smallint";
case "TINYINT" -> "tinyint";
@@ -1223,6 +1224,7 @@ public class AthenaService {
case "BLOB" -> "varbinary";
case "STRUCT" -> "row";
case "MAP" -> "map";
case "JSON" -> "json";
default -> "varchar";
};
}
@@ -0,0 +1,439 @@
package io.floci.aws.services.athena;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
/**
* Bridges Trino SQL, the dialect Athena engine version 3 runs, and the DuckDB sidecar Floci runs
* it on.
*
* <p>{@link #FUNCTION_MACROS} defines, as DuckDB macros, the Trino JSON functions DuckDB lacks or
* answers differently: {@code json_extract_scalar} (NULL for an object or array, where DuckDB's
* {@code json_extract_string} returns its text), {@code json_parse}, {@code json_format},
* {@code json_size} and {@code is_json_scalar}. {@code json_extract} and {@code json_array_length}
* are DuckDB's own and already answer as Trino does. DuckDB keeps macros and views apart, so a Glue
* table named like one of them still gets its view.
*
* <p>{@link #translate} rewrites, outside string literals, quoted identifiers and comments:
* <ul>
* <li>the target type of every {@code CAST} and {@code TRY_CAST}: {@code ARRAY<T>} and
* {@code ARRAY(T)} become {@code T[]}, {@code MAP<K, V>} becomes {@code MAP(K, V)} and
* {@code ROW(name T, ...)} becomes {@code STRUCT(name T, ...)}, an unnamed field taking the
* name {@code field<n>}, so {@code CAST(json_parse(col) AS ARRAY<JSON>)} parses;</li>
* <li>a literal JSON path given to {@code json_extract_scalar}, {@code json_extract} or
* {@code json_size}, from Trino's JSONPath into a JSON Pointer, which DuckDB also takes and
* 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>
* </ul>
*/
final class TrinoSqlCompatibility {
private static final String JSON_PATH = "regexp_replace(p, '\\[\\s*\"([^\"]*)\"\\s*\\]', '.\"\\1\"', 'g')";
static final String FUNCTION_MACROS = String.join("\n",
"CREATE OR REPLACE MACRO json_extract_scalar(j, p) AS CASE WHEN json_type(json_extract(j, "
+ JSON_PATH + ")) IN ('OBJECT', 'ARRAY') THEN NULL ELSE json_extract_string(j, " + JSON_PATH
+ ") END;",
"CREATE OR REPLACE MACRO json_parse(s) AS json(s);",
"CREATE OR REPLACE MACRO json_format(j) AS CAST(json(j) AS VARCHAR);",
"CREATE OR REPLACE MACRO json_size(j, p) AS CAST(CASE WHEN json_extract(j, " + JSON_PATH + ") IS NULL"
+ " THEN NULL WHEN json_type(json_extract(j, " + JSON_PATH + ")) = 'ARRAY'"
+ " THEN json_array_length(j, " + JSON_PATH + ")"
+ " WHEN json_type(json_extract(j, " + JSON_PATH + ")) = 'OBJECT'"
+ " THEN len(json_keys(j, " + JSON_PATH + ")) ELSE 0 END AS BIGINT);",
"CREATE OR REPLACE MACRO is_json_scalar(j) AS json_type(json(j)) NOT IN ('OBJECT', 'ARRAY');",
"");
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");
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);
private TrinoSqlCompatibility() {
}
/** {@code sql} with Trino's cast types and literal JSON paths in DuckDB's syntax. */
static String translate(String sql) {
if (sql == null) {
return null;
}
StringBuilder out = new StringBuilder(sql.length());
int i = 0;
while (i < sql.length()) {
int skipped = skipLiteralOrComment(sql, i);
if (skipped > i) {
out.append(sql, i, skipped);
i = skipped;
continue;
}
String function = functionAt(sql, i);
int open = function == null ? -1 : sql.indexOf('(', i + function.length());
int close = open < 0 ? -1 : matchingParen(sql, open);
if (close < 0) {
out.append(sql.charAt(i));
i++;
continue;
}
String inner = sql.substring(open + 1, close);
out.append(sql, i, open + 1)
.append(CAST_FUNCTIONS.contains(function) ? translateCast(inner) : translatePathCall(inner))
.append(')');
i = close + 1;
}
return out.toString();
}
private static String translateCast(String inner) {
int as = lastTopLevelAs(inner);
if (as < 0) {
return translate(inner);
}
return translate(inner.substring(0, as)) + inner.substring(as, as + 2) + " "
+ translateType(withoutComments(inner.substring(as + 2)).trim());
}
private static String translatePathCall(String inner) {
List<String> arguments = splitTopLevel(inner, true);
if (arguments.size() != 2) {
return translate(inner);
}
String path = arguments.get(1);
String pointer = jsonPointerLiteral(path.trim());
return translate(arguments.get(0)) + "," + (pointer == null ? translate(path) : " " + pointer);
}
/**
* {@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;
* null for anything else, a wildcard, a filter or a computed path included.
*/
static String jsonPointerLiteral(String literal) {
if (literal.length() < 2 || literal.charAt(0) != '\'' || literal.charAt(literal.length() - 1) != '\''
|| skipLiteralOrComment(literal, 0) != literal.length()) {
return null;
}
String path = literal.substring(1, literal.length() - 1).replace("''", "'").trim();
if (!path.startsWith("$")) {
return null;
}
StringBuilder pointer = new StringBuilder();
int i = 1;
while (i < path.length()) {
char c = path.charAt(i);
if (c == '.') {
int end = i + 1;
while (end < path.length() && (Character.isLetterOrDigit(path.charAt(end)) || path.charAt(end) == '_')) {
end++;
}
if (end == i + 1) {
return null;
}
pointer.append('/').append(pointerToken(path.substring(i + 1, end)));
i = end;
} else if (c == '[') {
int end = path.indexOf(']', i);
String member = end < 0 ? null : bracketMember(path, i + 1);
if (member != null) {
pointer.append('/').append(pointerToken(member));
i = bracketMemberEnd(path, i + 1);
} else if (end > i + 1 && path.substring(i + 1, end).trim().chars().allMatch(Character::isDigit)) {
pointer.append('/').append(path.substring(i + 1, end).trim());
i = end + 1;
} else {
return null;
}
} else {
return null;
}
if (i < 0) {
return null;
}
}
return "'" + pointer.toString().replace("'", "''") + "'";
}
/** The name of a {@code ["..."]} member starting at {@code start}, its escapes undone, or null. */
private static String bracketMember(String path, int start) {
int i = start;
while (i < path.length() && Character.isWhitespace(path.charAt(i))) {
i++;
}
if (i >= path.length() || path.charAt(i) != '"') {
return null;
}
StringBuilder name = new StringBuilder();
for (i++; i < path.length(); i++) {
char c = path.charAt(i);
if (c == '\\' && i + 1 < path.length()) {
name.append(path.charAt(++i));
} else if (c == '"') {
return name.toString();
} else {
name.append(c);
}
}
return null;
}
/** Index just past the {@code ]} closing a {@code ["..."]} member starting at {@code start}, or -1. */
private static int bracketMemberEnd(String path, int start) {
int i = path.indexOf('"', start) + 1;
while (i < path.length() && path.charAt(i) != '"') {
i += path.charAt(i) == '\\' ? 2 : 1;
}
int close = i + 1;
while (close < path.length() && Character.isWhitespace(path.charAt(close))) {
close++;
}
return close < path.length() && path.charAt(close) == ']' ? close + 1 : -1;
}
private static String pointerToken(String name) {
return name.replace("~", "~0").replace("/", "~1");
}
/** A Trino type name in DuckDB's syntax. */
static String translateType(String type) {
int open = firstGenericOpen(type);
if (open < 0) {
return type;
}
String head = type.substring(0, open).trim().toUpperCase(Locale.ROOT);
int close = matchingGenericClose(type, open);
if (close != type.length() - 1) {
return type;
}
List<String> parameters = splitTopLevel(type.substring(open + 1, close), false);
return switch (head) {
case "ARRAY" -> parameters.size() == 1 ? translateType(parameters.getFirst().trim()) + "[]" : type;
case "MAP" -> parameters.size() == 2
? "MAP(" + translateType(parameters.get(0).trim()) + ", " + translateType(parameters.get(1).trim()) + ")"
: type;
case "ROW" -> rowType(parameters);
default -> type;
};
}
private static String rowType(List<String> fields) {
List<String> translated = new ArrayList<>();
for (int i = 0; i < fields.size(); i++) {
String field = fields.get(i).trim();
int nameEnd = nameEnd(field);
boolean unnamed = nameEnd < 0 || MULTI_WORD_TYPE.matcher(field).matches()
|| field.substring(nameEnd).trim().startsWith("<") || field.substring(nameEnd).trim().startsWith("(");
translated.add(unnamed
? "field" + i + " " + translateType(field)
: field.substring(0, nameEnd) + " " + translateType(field.substring(nameEnd).trim()));
}
return "STRUCT(" + String.join(", ", translated) + ")";
}
/** End of a ROW field's name: after a quoted name, or at the first whitespace; -1 for a lone type. */
private static int nameEnd(String field) {
if (field.startsWith("\"")) {
int end = skipQuoted(field, 0);
return end < field.length() ? end : -1;
}
for (int i = 0; i < field.length(); i++) {
char c = field.charAt(i);
if (c == '<' || c == '(') {
return -1;
}
if (Character.isWhitespace(c)) {
return i;
}
}
return -1;
}
/** The CAST or path-taking function whose name starts at {@code i} and is followed by {@code (}, or null. */
private static String functionAt(String sql, int i) {
if (i > 0 && isIdentifierChar(sql.charAt(i - 1))) {
return null;
}
for (List<String> names : List.of(CAST_FUNCTIONS, PATH_FUNCTIONS)) {
for (String name : names) {
if (sql.regionMatches(true, i, name, 0, name.length())) {
int j = i + name.length();
while (j < sql.length() && Character.isWhitespace(sql.charAt(j))) {
j++;
}
if (j < sql.length() && sql.charAt(j) == '(') {
return name;
}
}
}
}
return null;
}
private static int matchingParen(String sql, int open) {
int depth = 0;
int i = open;
while (i < sql.length()) {
int skipped = skipLiteralOrComment(sql, i);
if (skipped > i) {
i = skipped;
continue;
}
char c = sql.charAt(i);
if (c == '(') {
depth++;
} else if (c == ')' && --depth == 0) {
return i;
}
i++;
}
return -1;
}
/** Index of the last {@code AS} keyword outside parentheses, literals and comments, or -1. */
private static int lastTopLevelAs(String inner) {
int depth = 0;
int found = -1;
int i = 0;
while (i < inner.length()) {
int skipped = skipLiteralOrComment(inner, i);
if (skipped > i) {
i = skipped;
continue;
}
char c = inner.charAt(i);
if (c == '(') {
depth++;
} else if (c == ')') {
depth--;
} else if (depth == 0 && inner.regionMatches(true, i, "AS", 0, 2)
&& (i == 0 || !isIdentifierChar(inner.charAt(i - 1)))
&& (i + 2 == inner.length() || !isIdentifierChar(inner.charAt(i + 2)))) {
found = i;
}
i++;
}
return found;
}
/** {@code text} with each comment outside literals and quoted identifiers turned into a space. */
private static String withoutComments(String text) {
StringBuilder out = new StringBuilder(text.length());
int i = 0;
while (i < text.length()) {
int skipped = skipLiteralOrComment(text, i);
if (skipped > i) {
boolean comment = text.startsWith("--", i) || text.startsWith("/*", i);
out.append(comment ? " " : text.substring(i, skipped));
i = skipped;
} else {
out.append(text.charAt(i));
i++;
}
}
return out.toString();
}
private static int skipLiteralOrComment(String sql, int i) {
char c = sql.charAt(i);
if (c == '\'' || c == '"') {
return skipQuoted(sql, i);
}
if (sql.startsWith("--", i)) {
int end = sql.indexOf('\n', i);
return end < 0 ? sql.length() : end + 1;
}
if (sql.startsWith("/*", i)) {
int end = sql.indexOf("*/", i + 2);
return end < 0 ? sql.length() : end + 2;
}
return i;
}
/** Index just past the literal or quoted identifier starting at {@code i}, doubled quotes included. */
private static int skipQuoted(String sql, int i) {
char quote = sql.charAt(i);
int j = i + 1;
while (j < sql.length()) {
if (sql.charAt(j) == quote) {
if (j + 1 < sql.length() && sql.charAt(j + 1) == quote) {
j += 2;
continue;
}
return j + 1;
}
j++;
}
return sql.length();
}
private static int firstGenericOpen(String type) {
int i = 0;
while (i < type.length()) {
char c = type.charAt(i);
if (c == '"') {
i = skipQuoted(type, i);
continue;
}
if (c == '<' || c == '(') {
return i;
}
i++;
}
return -1;
}
private static int matchingGenericClose(String type, int open) {
int depth = 0;
int i = open;
while (i < type.length()) {
char c = type.charAt(i);
if (c == '"') {
i = skipQuoted(type, i);
continue;
}
if (c == '<' || c == '(') {
depth++;
} else if ((c == '>' || c == ')') && --depth == 0) {
return i;
}
i++;
}
return -1;
}
/**
* {@code parameters} split at its top-level commas, 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<>();
int depth = 0;
int start = 0;
int i = 0;
while (i < parameters.length()) {
char c = parameters.charAt(i);
int skipped = sql ? skipLiteralOrComment(parameters, i) : c == '"' ? skipQuoted(parameters, i) : i;
if (skipped > i) {
i = skipped;
continue;
}
if (c == '<' && !sql || c == '(') {
depth++;
} else if (c == '>' && !sql || c == ')') {
depth--;
} else if (c == ',' && depth == 0) {
parts.add(parameters.substring(start, i));
start = i + 1;
}
i++;
}
parts.add(parameters.substring(start));
return parts;
}
private static boolean isIdentifierChar(char c) {
return Character.isLetterOrDigit(c) || c == '_';
}
}
@@ -81,7 +81,8 @@ class AthenaQueryScopeTest {
String id = RequestScopes.callAs(account, REGION,
() -> athena.startQueryExecution("SELECT 1", "primary", context, null));
assertEquals(List.of(expected, account), handedToDuck.get(10, TimeUnit.SECONDS));
assertEquals(List.of(TrinoSqlCompatibility.FUNCTION_MACROS + expected, account),
handedToDuck.get(10, TimeUnit.SECONDS));
await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(50)).untilAsserted(() ->
assertEquals(QueryExecutionState.SUCCEEDED, RequestScopes.callAs(account, REGION,
() -> athena.getQueryExecution(id).getStatus().getState())));
@@ -0,0 +1,132 @@
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.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* The Trino JSON functions Athena queries call, answered by the real floci-duck sidecar through
* {@link TrinoSqlCompatibility}, with the results Trino gives.
*/
@QuarkusTest
@TestProfile(SidecarContainersProfile.class)
class AthenaTrinoJsonFunctionsSidecarIntegrationTest {
@Inject
FlociDuckClient duck;
@BeforeAll
static void requireDocker() {
SidecarContainersProfile.requireDocker();
}
private Map<String, Object> row(String trinoSql) {
return duck.query(TrinoSqlCompatibility.translate(trinoSql), TrinoSqlCompatibility.FUNCTION_MACROS).getFirst();
}
@Test
void jsonExtractScalarReturnsScalarsAsTextAndNullForAnythingElse() {
Map<String, Object> row = row("SELECT json_extract_scalar('{\"a\":\"x\"}', '$.a') AS s, "
+ "json_extract_scalar('{\"a\":2}', '$.a') AS n, json_extract_scalar('{\"a\":true}', '$.a') AS b, "
+ "json_extract_scalar('{\"a\":{\"b\":1}}', '$.a') AS o, json_extract_scalar('{\"a\":[1]}', '$.a') AS arr, "
+ "json_extract_scalar('{\"a\":null}', '$.a') AS nul, json_extract_scalar('{\"a\":1}', '$.b') AS missing, "
+ "json_extract_scalar('{\"a b\":{\"c\":[5]}}', '$[\"a b\"].c[0]') AS bracket");
assertEquals("x", row.get("s"));
assertEquals("2", row.get("n"));
assertEquals("true", row.get("b"));
assertNull(row.get("o"));
assertNull(row.get("arr"));
assertNull(row.get("nul"));
assertNull(row.get("missing"));
assertEquals("5", row.get("bracket"));
}
@Test
void jsonParseFormatSizeAndScalarCheckAnswerAsTrinoDoes() {
Map<String, Object> row = row("SELECT json_format(json_parse('{ \"a\" : [1, 2] }')) AS f, "
+ "json_size('{\"x\":[1,2,3]}', '$.x') AS arr, json_size('{\"x\":{\"a\":1}}', '$.x') AS obj, "
+ "json_size('{\"x\":1}', '$.x') AS scalar, is_json_scalar('1') AS yes, is_json_scalar('[1]') AS no, "
+ "json_array_length('[1,2,3]') AS len, json_extract_scalar(json_extract('{\"a\":{\"b\":\"c\"}}', '$.a'), '$.b') AS e");
assertEquals("{\"a\":[1,2]}", row.get("f"));
assertEquals(3, ((Number) row.get("arr")).intValue());
assertEquals(1, ((Number) row.get("obj")).intValue());
assertEquals(0, ((Number) row.get("scalar")).intValue());
assertEquals(true, row.get("yes"));
assertEquals(false, row.get("no"));
assertEquals(3, ((Number) row.get("len")).intValue());
assertEquals("c", row.get("e"));
}
@Test
void jsonSizeIsNullForANullArgumentOrAMissingPathAndZeroForAJsonNull() {
Map<String, Object> row = row("SELECT json_size(NULL, '$.x') AS null_json, json_size('{\"x\":1}', NULL) AS null_path, "
+ "json_size('{\"x\":1}', '$.y') AS missing, json_size('{\"x\":null}', '$.x') AS json_null");
assertNull(row.get("null_json"));
assertNull(row.get("null_path"));
assertNull(row.get("missing"));
assertEquals(0, ((Number) row.get("json_null")).intValue());
}
@Test
void aBracketedMemberNameCanHoldAnEscapedQuoteOrASlash() {
Map<String, Object> row = row("SELECT json_extract_scalar('{\"a\\\"b\":7}', '$[\"a\\\"b\"]') AS quote, "
+ "json_extract_scalar('{\"a/b\":{\"c~d\":8}}', '$[\"a/b\"][\"c~d\"]') AS slash");
assertEquals("7", row.get("quote"));
assertEquals("8", row.get("slash"));
}
@Test
void aTableNamedLikeAMacroKeepsBothItsViewAndTheFunction() {
Map<String, Object> row = duck.query("SELECT (SELECT n FROM json_size) AS view_value, "
+ "json_size('[1,2]', '$') AS function_value",
TrinoSqlCompatibility.FUNCTION_MACROS + "CREATE OR REPLACE VIEW \"json_size\" AS SELECT 42 AS n;").getFirst();
assertEquals(42, ((Number) row.get("view_value")).intValue());
assertEquals(2, ((Number) row.get("function_value")).intValue());
}
@Test
void aCastToAnUnnamedRowTypeRuns() {
Map<String, Object> row = row("SELECT typeof(CAST(ROW(1, 'x') AS ROW(BIGINT, VARCHAR))) AS t");
assertEquals("STRUCT(field0 BIGINT, field1 VARCHAR)", row.get("t"));
}
@Test
void aCastToArrayOfJsonUnnestsIntoJsonValues() {
List<Map<String, Object>> rows = duck.query(TrinoSqlCompatibility.translate(
"SELECT json_extract_scalar(item, '$.id') AS id "
+ "FROM (VALUES ('[{\"id\":1},{\"id\":2}]')) AS t(col) "
+ "CROSS JOIN UNNEST(CAST(json_parse(col) AS ARRAY<JSON>)) AS u(item) ORDER BY id"),
TrinoSqlCompatibility.FUNCTION_MACROS);
assertEquals(List.of("1", "2"), rows.stream().map(r -> r.get("id")).toList());
}
@Test
void jsonResultColumnsAreTypedAsAthenaTypesThem() {
List<String> types = duck.query("DESCRIBE " + TrinoSqlCompatibility.translate(
"SELECT json_parse('[1]') AS p, json_extract_scalar('{\"a\":1}', '$.a') AS s, "
+ "json_array_length('[1]') AS n, json_size('[1]', '$') AS z, "
+ "CAST(json_parse('[1]') AS ARRAY<JSON>) AS a"), TrinoSqlCompatibility.FUNCTION_MACROS)
.stream()
.map(column -> AthenaService.athenaType(String.valueOf(column.get("column_type"))))
.toList();
assertEquals(List.of("json", "varchar", "bigint", "bigint", "array"), types);
}
}
@@ -0,0 +1,83 @@
package io.floci.aws.services.athena;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class TrinoSqlCompatibilityTest {
@Test
void castToATrinoArrayTypeBecomesADuckDbList() {
assertEquals("SELECT CAST(json_parse(col) AS JSON[]) FROM t",
TrinoSqlCompatibility.translate("SELECT CAST(json_parse(col) AS ARRAY<JSON>) FROM t"));
assertEquals("SELECT cast(x as BIGINT[])", TrinoSqlCompatibility.translate("SELECT cast(x as ARRAY(BIGINT))"));
}
@Test
void mapsRowsAndNestingAreTranslatedToo() {
assertEquals("SELECT TRY_CAST(x AS MAP(VARCHAR, BIGINT[]))",
TrinoSqlCompatibility.translate("SELECT TRY_CAST(x AS MAP<VARCHAR, ARRAY(BIGINT)>)"));
assertEquals("SELECT CAST(x AS STRUCT(a BIGINT, \"b c\" VARCHAR[]))",
TrinoSqlCompatibility.translate("SELECT CAST(x AS ROW(a BIGINT, \"b c\" ARRAY<VARCHAR>))"));
assertEquals("SELECT CAST(CAST(x AS JSON[]) AS VARCHAR[])",
TrinoSqlCompatibility.translate("SELECT CAST(CAST(x AS ARRAY<JSON>) AS ARRAY<VARCHAR>)"));
}
@Test
void typesDuckDbAlreadySpellsTheSameWayAreKept() {
assertEquals("SELECT CAST(p AS DECIMAL(10,2)), CAST(s AS VARCHAR(5)), CAST(t AS TIMESTAMP)",
TrinoSqlCompatibility.translate(
"SELECT CAST(p AS DECIMAL(10,2)), CAST(s AS VARCHAR(5)), CAST(t AS TIMESTAMP)"));
}
@Test
void literalsQuotedIdentifiersCommentsAndLookalikeNamesAreLeftAlone() {
String sql = "SELECT 'CAST(x AS ARRAY<JSON>)' AS s, \"cast(\" AS q, podcast(1), x AS y -- CAST(x AS ARRAY<JSON>)\n"
+ "FROM t /* CAST(y AS ARRAY<JSON>) */";
assertEquals(sql, TrinoSqlCompatibility.translate(sql));
}
@Test
void quotedRowFieldNamesKeepTheirEscapedQuotesAndCommas() {
assertEquals("SELECT CAST(x AS STRUCT(\"a\"\"b\" INTEGER[], \"c,d\" BIGINT))",
TrinoSqlCompatibility.translate("SELECT CAST(x AS ROW(\"a\"\"b\" ARRAY<INTEGER>, \"c,d\" BIGINT))"));
}
@Test
void commentsInsideATargetTypeDoNotStopItsTranslation() {
assertEquals("SELECT CAST(x AS JSON[])", TrinoSqlCompatibility.translate("SELECT CAST(x AS ARRAY /* note */ <JSON>)"));
assertEquals("SELECT CAST(x AS STRUCT(a VARCHAR[]))",
TrinoSqlCompatibility.translate("SELECT CAST(x AS ROW(a -- note\n ARRAY<VARCHAR>))"));
}
@Test
void unnamedRowFieldsGetPositionalNames() {
assertEquals("SELECT CAST(ROW(1, 'x') AS STRUCT(field0 BIGINT, field1 VARCHAR[], field2 DOUBLE PRECISION))",
TrinoSqlCompatibility.translate(
"SELECT CAST(ROW(1, 'x') AS ROW(BIGINT, ARRAY<VARCHAR>, DOUBLE PRECISION))"));
}
@Test
void literalJsonPathsBecomeJsonPointersThatCanNameAnyMember() {
assertEquals("SELECT json_extract_scalar(col, '/a/b c/0')",
TrinoSqlCompatibility.translate("SELECT json_extract_scalar(col, '$.a[\"b c\"][0]')"));
assertEquals("SELECT JSON_EXTRACT(col, '/a\"b'), json_size(col, '/x~1y~0z'), json_extract(col, '')",
TrinoSqlCompatibility.translate(
"SELECT JSON_EXTRACT(col, '$[\"a\\\"b\"]'), json_size(col, '$[\"x/y~z\"]'), json_extract(col, '$')"));
assertEquals("SELECT json_extract_scalar(col, '/it''s')",
TrinoSqlCompatibility.translate("SELECT json_extract_scalar(col, '$[\"it''s\"]')"));
}
@Test
void wildcardAndComputedPathsAreLeftForDuckDb() {
String sql = "SELECT json_extract(col, '$.a[*]'), json_extract_scalar(col, p), json_size(col, '$..a')";
assertEquals(sql, TrinoSqlCompatibility.translate(sql));
}
@Test
void anUnbalancedCastIsReturnedAsWritten() {
assertEquals("SELECT CAST(x AS ARRAY<JSON>", TrinoSqlCompatibility.translate("SELECT CAST(x AS ARRAY<JSON>"));
}
}