fix(athena): read headerless delimited text by its Glue columns and keep one bad view from failing every query (#8427)

A LazySimpleSerDe table over headerless TSV came back as column00,
column01 and the view's projection failed to bind: Athena's views were
built with readExpression, which ignored the table's CSV options
(field.delim, skip.header.line.count) that only Redshift Spectrum's
read plan applied. Views now read such a table with read_csv and those
options, naming the file columns after the declared data columns, and
give each data column its declared type with TRY_CAST, NULL for a value
the type cannot hold, as LazySimpleSerDe does.

Every query also built a view for every Glue table, and DuckDB binds
each view before running the query, so one table whose view could not
be built failed all queries. Views are now built only for the tables
the query names, or for every table when it reads information_schema or
is a SHOW statement.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-15 08:13:19 -04:00
1 parent 53ebf2a18c
commit 31c86c05e9
7 files changed
+531 -22

No files matched your search

@@ -228,7 +228,7 @@ public class AthenaService {
List<Table> projectionTables = tablesForProjectionCheck(database);
PartitionProjection.assertLocationTemplatesComplete(query, projectionTables);
PartitionProjection.assertInjectedColumnsFiltered(query, projectionTables);
String setupDdl = TrinoSqlCompatibility.FUNCTION_MACROS + ddlBuilder.build(database);
String setupDdl = TrinoSqlCompatibility.FUNCTION_MACROS + ddlBuilder.build(database, query);
String duckQuery = TrinoSqlCompatibility.translate(query);
if (outputLocation != null) {
ensureOutputBucket(outputLocation);
@@ -9,7 +9,9 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@ApplicationScoped
public class GlueViewDdlBuilder {
@@ -31,6 +33,18 @@ public class GlueViewDdlBuilder {
}
public String build(String contextDatabase) {
return build(contextDatabase, null);
}
/**
* Views for the Glue tables {@code query} names, or for every table when {@code query} is null,
* reads {@code information_schema} or is a {@code SHOW} statement, all of which list tables.
* DuckDB binds each view of the batch before the query runs, so a table whose view cannot bind
* (files that do not match its declared schema) fails only the queries that read it rather than
* every query.
*/
public String build(String contextDatabase, String query) {
ViewFilter wanted = viewFilter(query);
StringBuilder sb = new StringBuilder();
boolean usesIceberg = false;
boolean contextDbHandled = false;
@@ -47,9 +61,9 @@ public class GlueViewDdlBuilder {
sb.append("CREATE SCHEMA IF NOT EXISTS ").append(quote(schema)).append(";\n");
try {
List<Table> tables = glueService.getTables(schema);
usesIceberg |= appendViews(sb, schema, tables, true);
usesIceberg |= appendViews(sb, schema, tables, true, wanted);
if (schema.equals(contextDatabase)) {
usesIceberg |= appendViews(sb, schema, tables, false);
usesIceberg |= appendViews(sb, schema, tables, false, wanted);
contextDbHandled = true;
}
} catch (Exception e) {
@@ -61,7 +75,7 @@ public class GlueViewDdlBuilder {
if (!contextDbHandled && contextDatabase != null && !contextDatabase.isBlank()) {
try {
List<Table> tables = glueService.getTables(contextDatabase);
usesIceberg |= appendViews(sb, contextDatabase, tables, false);
usesIceberg |= appendViews(sb, contextDatabase, tables, false, wanted);
} catch (Exception e) {
LOG.debugv("Could not fetch tables for context database {0}: {1}", contextDatabase, e.getMessage());
}
@@ -75,7 +89,8 @@ public class GlueViewDdlBuilder {
}
/** @return true if at least one of the appended views reads an Iceberg table. */
private boolean appendViews(StringBuilder sb, String schemaOrNull, List<Table> tables, boolean qualified) {
private boolean appendViews(StringBuilder sb, String schemaOrNull, List<Table> tables, boolean qualified,
ViewFilter wanted) {
if (tables == null) {
return false;
}
@@ -85,7 +100,8 @@ public class GlueViewDdlBuilder {
if (t == null) {
continue;
}
if (t.getName() == null || t.getName().isBlank()) {
if (t.getName() == null || t.getName().isBlank()
|| !wanted.wants(schemaOrNull, t.getName(), qualified)) {
continue;
}
if (t.getStorageDescriptor() == null
@@ -136,6 +152,134 @@ public class GlueViewDdlBuilder {
return usesIceberg;
}
/** Which views a query needs: a qualified view of a database's table, or an unqualified one of the context's. */
@FunctionalInterface
interface ViewFilter {
boolean wants(String schema, String table, boolean qualified);
}
/**
* The views {@code query} needs, from the names it references (see {@link #references}): a qualified view
* {@code "db"."t"} for a reference whose parts include {@code db} then {@code t} ({@code db.t},
* {@code awsdatacatalog.db.t}, a column {@code db.t.c}), and an unqualified one for a reference starting with
* {@code t}, which resolves in the context database. Every view when {@code query} is null, starts with
* {@code SHOW} or references {@code information_schema}, all of which list tables.
*/
static ViewFilter viewFilter(String query) {
if (query == null) {
return (schema, table, qualified) -> true;
}
List<List<String>> references = references(query);
boolean lists = references.stream().anyMatch(name -> name.contains("information_schema"))
|| (!references.isEmpty() && references.getFirst().getFirst().equals("show"));
if (lists) {
return (schema, table, qualified) -> true;
}
return (schema, table, qualified) -> {
String db = schema == null ? null : schema.toLowerCase(Locale.ROOT);
String name = table.toLowerCase(Locale.ROOT);
for (List<String> reference : references) {
if (!qualified && names(reference.getFirst(), name)) {
return true;
}
for (int i = 0; qualified && i + 1 < reference.size(); i++) {
if (reference.get(i).equals(db) && names(reference.get(i + 1), name)) {
return true;
}
}
}
return false;
};
}
/** Whether a referenced name names the table: itself, or one of its Iceberg metadata tables ({@code "t$files"}). */
private static boolean names(String referenced, String table) {
return referenced.equals(table) || referenced.startsWith(table + "$");
}
/**
* The dotted names {@code query} references, each part lowercased, a quoted part decoded ({@code "a""b"} is
* {@code a"b}), in the order they appear: keywords too, since a table may share a keyword's name. String
* literals and comments are skipped, so a name only they hold is no reference.
*/
static List<List<String>> references(String query) {
List<List<String>> names = new ArrayList<>();
List<String> current = null;
boolean dotted = false;
int i = 0;
int n = query.length();
while (i < n) {
char c = query.charAt(i);
if (c == '-' && i + 1 < n && query.charAt(i + 1) == '-') {
int end = query.indexOf('\n', i);
i = end < 0 ? n : end + 1;
current = null;
} else if (c == '/' && i + 1 < n && query.charAt(i + 1) == '*') {
int end = query.indexOf("*/", i + 2);
i = end < 0 ? n : end + 2;
current = null;
} else if (c == '\'') {
i = skipQuoted(query, i, '\'');
current = null;
} else if (c == '"' || Character.isLetter(c) || c == '_') {
String part;
if (c == '"') {
int end = skipQuoted(query, i, '"');
part = query.substring(i + 1, Math.max(i + 1, end - 1)).replace("\"\"", "\"");
i = end;
} else {
int start = i;
while (i < n && isIdentifierChar(query.charAt(i))) {
i++;
}
part = query.substring(start, i);
}
part = part.toLowerCase(Locale.ROOT);
if (dotted && current != null) {
current.add(part);
} else {
current = new ArrayList<>(List.of(part));
names.add(current);
}
dotted = false;
continue;
} else if (c == '.' && current != null) {
dotted = true;
i++;
continue;
} else if (Character.isWhitespace(c)) {
// A name may span whitespace around its dots (db . t); anything else between parts ends it.
i++;
continue;
} else {
current = null;
i++;
}
dotted = false;
}
return names;
}
/** The index just past the quoted text starting at {@code start}, a doubled {@code quote} inside it kept. */
private static int skipQuoted(String query, int start, char quote) {
int i = start + 1;
while (i < query.length()) {
if (query.charAt(i) == quote) {
if (i + 1 < query.length() && query.charAt(i + 1) == quote) {
i += 2;
continue;
}
return i + 1;
}
i++;
}
return query.length();
}
private static boolean isIdentifierChar(char c) {
return Character.isLetterOrDigit(c) || c == '_' || c == '$';
}
static String quote(String id) {
return "\"" + id.replace("\"", "\"\"") + "\"";
}
@@ -5,6 +5,7 @@ import io.floci.aws.services.glue.model.StorageDescriptor;
import io.floci.aws.services.glue.model.Table;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
@@ -34,6 +35,8 @@ public final class GlueTableResolver {
/** Hive table property naming how many header lines a delimited file carries. */
private static final String PARAM_SKIP_HEADER = "skip.header.line.count";
/** The null marker Hive's LazySimpleSerDe reads when a table declares none ({@code serialization.null.format}). */
private static final String LAZY_SIMPLE_NULL_FORMAT = "\\N";
/**
* The column a templated table's read adds to carry each row's object path, from which its
@@ -132,6 +135,10 @@ public final class GlueTableResolver {
}
private static String csvReadExpressionForInput(Table table, String inputExpression) {
return csvReadExpressionForInput(table, inputExpression, "");
}
private static String csvReadExpressionForInput(Table table, String inputExpression, String extraOptions) {
Map<String, String> options = csvParameters(table);
int skip = skipCount(options.get(PARAM_SKIP_HEADER));
StringBuilder sql = new StringBuilder("read_csv(").append(inputExpression);
@@ -141,11 +148,24 @@ public final class GlueTableResolver {
}
String delimiter = options.containsKey("field.delim") ? options.get("field.delim") : options.get("separatorChar");
sql.append(", delim = '").append(escape(delimiter == null || delimiter.isEmpty() ? "," : delimiter)).append("'");
appendOption(sql, "quote", options.get("quoteChar"));
boolean lazySimple = isLazySimpleSerDe(table);
String quote = options.get("quoteChar");
if (quote != null && !quote.isEmpty()) {
appendOption(sql, "quote", quote);
} else if (lazySimple) {
// LazySimpleSerDe reads a quote as text: Athena points quoted fields to OpenCSVSerDe.
sql.append(", quote = ''");
}
appendOption(sql, "escape", options.get("escapeChar"));
appendOption(sql, "nullstr", options.get("serialization.null.format"));
String nullFormat = options.get("serialization.null.format");
// LazySimpleSerDe's null marker is \N unless the table says otherwise, so an empty field reads as ''.
appendOption(sql, "nullstr", nullFormat == null && lazySimple ? LAZY_SIMPLE_NULL_FORMAT : nullFormat);
List<Column> dataColumns = table.getStorageDescriptor().getColumns();
if (dataColumns != null && !dataColumns.isEmpty()) {
// The declared columns are the files' columns, as Hive reads them: a row with fewer fields gets NULL for
// the rest (a file written before ALTER TABLE ADD COLUMNS), and one with more drops the extra ones. The
// dialect is the one declared, not sniffed, since DuckDB's sniffer refuses rows of varying length.
sql.append(", auto_detect = false, null_padding = true, strict_mode = false");
// Every column is read as VARCHAR: DuckDB's own type sniffing would disagree with the Glue types,
// and the caller casts each column to its declared type afterwards.
sql.append(", columns = {");
@@ -157,7 +177,15 @@ public final class GlueTableResolver {
}
sql.append('}');
}
return sql.append(')').toString();
return sql.append(extraOptions).append(')').toString();
}
/** Whether the table reads its text with Hive's LazySimpleSerDe, the default when it names no SerDe. */
private static boolean isLazySimpleSerDe(Table table) {
String serde = table.getStorageDescriptor().getSerdeInfo() != null
? table.getStorageDescriptor().getSerdeInfo().getSerializationLibrary()
: null;
return serde == null || serde.isBlank() || serde.endsWith(".LazySimpleSerDe");
}
private static void appendOption(StringBuilder sql, String name, String value) {
@@ -244,6 +272,7 @@ public final class GlueTableResolver {
PartitionProjection.LocationTemplate template = locationTemplate(table);
Map<String, Column> templatedKeys = templatedKeys(table, template);
Map<String, Column> textColumns = readsDelimitedText(table) ? columnsByName(declared) : Map.of();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < names.size(); i++) {
if (i > 0) {
@@ -251,12 +280,42 @@ public final class GlueTableResolver {
}
String name = names.get(i);
Column key = templatedKeys.get(name.toLowerCase(Locale.ROOT));
String value = key == null ? quote(name) : partitionValue(template, key);
Column text = textColumns.get(name.toLowerCase(Locale.ROOT));
String value = key != null ? partitionValue(template, key)
: text != null ? typedText(quote(name), text.getType())
: quote(name);
sb.append(value).append(" AS ").append(quote(name));
}
return sb.toString();
}
/**
* Whether the table is read as text with its own CSV options, which leaves every data column and
* Hive partition value a VARCHAR for {@link #buildProjection} to give its declared type.
*/
private static boolean readsDelimitedText(Table table) {
return !isIcebergTable(table) && "read_csv_auto".equals(inferReadFunction(table)) && hasCsvOptions(table);
}
private static Map<String, Column> columnsByName(List<Column> declared) {
Map<String, Column> columns = new HashMap<>();
for (Column column : declared) {
if (column != null && column.getName() != null) {
columns.putIfAbsent(column.getName().toLowerCase(Locale.ROOT), column);
}
}
return columns;
}
/**
* A text value as its declared type. Like Hive's LazySimpleSerDe, which Athena reads delimited
* text with, a value the type cannot hold reads as NULL rather than failing the query.
*/
private static String typedText(String text, String glueType) {
String type = scalarType(glueType);
return "VARCHAR".equals(type) ? text : "TRY_CAST(" + text + " AS " + type + ")";
}
/**
* The condition a templated table's view keeps rows by, or {@code null} for any other table: that
* the object's path is one Athena could address through the template.
@@ -287,7 +346,7 @@ public final class GlueTableResolver {
terms.add(pathSegment(template, groups.getFirst()) + " = "
+ pathSegment(template, groups.get(occurrence)));
}
if (!"VARCHAR".equals(partitionValueType(key.getType()))) {
if (!"VARCHAR".equals(scalarType(key.getType()))) {
terms.add(partitionValue(template, key) + " IS NOT NULL");
}
}
@@ -345,8 +404,7 @@ public final class GlueTableResolver {
*/
private static String partitionValue(PartitionProjection.LocationTemplate template, Column key) {
String text = pathSegment(template, template.groups().get(key.getName().toLowerCase(Locale.ROOT)).getFirst());
String type = partitionValueType(key.getType());
return "VARCHAR".equals(type) ? text : "TRY_CAST(" + text + " AS " + type + ")";
return typedText(text, key.getType());
}
/**
@@ -357,7 +415,7 @@ public final class GlueTableResolver {
* other than ISO ({@code yyyy-MM-dd}, {@code yyyy-MM-dd HH:mm:ss}) needs {@code strptime} with the
* Java pattern translated; until then its values do not parse and its objects are not read.
*/
private static String partitionValueType(String glueType) {
private static String scalarType(String glueType) {
String type = glueType == null ? "" : glueType.trim().toLowerCase(Locale.ROOT);
if (DECIMAL_TYPE.matcher(type).matches()) {
return type.toUpperCase(Locale.ROOT);
@@ -424,14 +482,18 @@ public final class GlueTableResolver {
* also reads each row's object path, which {@link #buildProjection} takes its partition values
* from. Hive partitioning is switched off for it: the template is the only source of those
* values, and a {@code col=value} segment it happens to contain would otherwise be read as a
* second, untyped column.
* second, untyped column. A table that declares CSV options (a delimiter, header lines) is read
* with them and its declared column names, as {@link #hasCsvOptions} explains.
*/
public static String readExpression(Table table, String readFn, String normalizedLocation) {
if (locationTemplate(table) == null) {
return readExpression(readFn, normalizedLocation);
boolean templated = locationTemplate(table) != null;
String options = templated ? ", hive_partitioning = false, filename = '" + escape(OBJECT_PATH_COLUMN) + "'" : "";
if ("read_csv_auto".equals(readFn) && hasCsvOptions(table)) {
// Hive partition values stay text too, so they take their declared type like the data columns.
return csvReadExpressionForInput(table, "'" + escape(normalizedLocation) + "/**'",
templated ? options : ", hive_types_autocast = false");
}
return readExpression(readFn, normalizedLocation,
", hive_partitioning = false, filename = '" + escape(OBJECT_PATH_COLUMN) + "'");
return readExpression(readFn, normalizedLocation, options);
}
private static String readExpression(String readFn, String normalizedLocation, String options) {