fix(athena): answer no rows for a table whose location holds no data (#8575)

Athena answers a table whose S3 location holds no data with no rows.
Floci's view read the location with DuckDB's read_* glob, which refuses
to bind when nothing matches, so every query on such a table failed.

- GlueViewDdlBuilder checks the location a table is read from (its read
  path, so a projected table's partition folders) before building its
  view. One that holds no data gets a view of no rows with the table's
  declared columns as their declared types (GlueTableResolver
  .emptyProjection), nested and binary columns as the engine reads them
  (columnType: array<T> as T[], map, struct, binary as BLOB).
- TableLocation.holdsNoData lists the location in one scan: folder
  markers (keys ending in a slash) hold no data, and a read path with
  `*` segments is listed from its literal prefix, an object counting
  when its key matches the glob. A location holding another glob
  character, or whose bucket does not exist, is read as before.

GlueViewDdlBuilderTest covers an empty location, one holding only
folder markers, a projected location holding only objects its glob does
not reach, nested and binary column types, an unmodeled glob and a
missing bucket. AthenaDelimitedTextSidecarIntegrationTest
queries an empty location and a folder marker against the real engine.
athena.md says so.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-16 08:52:15 -04:00
1 parent f94d5e9e58
commit f0ee5d44a0
7 files changed
+223 -4

No files matched your search

+2
View File
@@ -141,6 +141,8 @@ A delimited-text table that declares its CSV options (`field.delim` or `separato
Only the tables a query names get views (by database and name; a name only a string literal or a comment holds doesn't count), since DuckDB binds every view of the batch before the query runs: a table whose view cannot be built (files that do not match its declared format or schema) then fails the queries that read it and no others. A query that reads `information_schema` or is a `SHOW` statement gets a view for every table.
A table whose location holds no data, or only folder markers (keys ending in `/`), answers no rows with its declared columns as their types, as Athena does: its view selects no rows rather than reading the empty location, which DuckDB refuses to bind. Nested and binary columns take the types the engine reads them as (`array<string>` as `VARCHAR[]`, `binary` as `BLOB`). For a table with partition projection, only the objects its read path reaches count. A location holding another glob character (`?`, a bracket or a brace), which Athena does not take in a location, is read as before.
## Partition projection
A Glue table with `projection.enabled` set to `true` is read the way Athena reads it, from its partition layout rather than from its whole location:
@@ -5,6 +5,7 @@ import io.floci.aws.services.glue.GlueTableResolver;
import io.floci.aws.services.glue.PartitionProjection;
import io.floci.aws.services.glue.model.Database;
import io.floci.aws.services.glue.model.Table;
import io.floci.aws.services.s3.S3Service;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -26,10 +27,12 @@ public class GlueViewDdlBuilder {
private static final String ICEBERG_EXTENSION_SETUP = "INSTALL iceberg; LOAD iceberg;\n";
private final GlueService glueService;
private final S3Service s3Service;
@Inject
public GlueViewDdlBuilder(GlueService glueService) {
public GlueViewDdlBuilder(GlueService glueService, S3Service s3Service) {
this.glueService = glueService;
this.s3Service = s3Service;
}
public String build(String contextDatabase) {
@@ -132,6 +135,13 @@ public class GlueViewDdlBuilder {
} else {
String readFn = GlueTableResolver.inferReadFunction(t);
String readPath = GlueTableResolver.readPath(t, normalizedLocation);
// Reading a location that holds no data fails to bind, where Athena answers no rows.
String empty = holdsNoData(readPath) ? GlueTableResolver.emptyProjection(t) : null;
if (empty != null) {
sb.append("CREATE OR REPLACE VIEW ").append(target).append(" AS SELECT ").append(empty)
.append(";\n");
continue;
}
fromClause = GlueTableResolver.readExpression(t, readFn, readPath);
}
sb.append("CREATE OR REPLACE VIEW ")
@@ -152,6 +162,12 @@ public class GlueViewDdlBuilder {
return usesIceberg;
}
/** Whether the S3 location a table is read from holds no data; false for one that is not in S3. */
private boolean holdsNoData(String readPath) {
TableLocation location = TableLocation.of(readPath);
return location != null && location.holdsNoData(s3Service);
}
/** Which views a query needs: a qualified view of a database's table, or an unqualified one of the context's. */
@FunctionalInterface
interface ViewFilter {
@@ -4,12 +4,17 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.services.s3.model.S3Object;
import java.util.Arrays;
import java.util.function.Consumer;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/** A table's {@code s3://bucket/prefix/} location split into its bucket and its key prefix, ending in a slash. */
record TableLocation(String bucket, String prefix) {
private static final int LIST_PAGE_SIZE = 1000;
/** The glob characters DuckDB reads in a path besides {@code *}. */
private static final Pattern UNMODELED_GLOB = Pattern.compile("[?\\[\\]{}\\\\]");
/** The location {@code location} names, or null when it is not an {@code s3://} location. */
static TableLocation of(String location) {
@@ -39,6 +44,34 @@ record TableLocation(String bucket, String prefix) {
}
}
/**
* Whether no object the read of {@code <location>/**} reaches holds data: there is none, or only the zero-byte
* folder markers (keys ending in a slash) the S3 console creates. A location with {@code *} in it, a projected
* table's read path, is listed from the literal prefix before its first {@code *}, an object counting when its
* key matches, each {@code *} taking part or all of one folder name. False when the location holds a glob
* character this does not model ({@code ?}, a bracket or brace expression, an escape), which the read keeps, and
* when the bucket does not exist, which reading the location reports as it did. The location is listed in one
* scan, as every page of a listing scans the whole prefix.
*/
boolean holdsNoData(S3Service s3) {
if (UNMODELED_GLOB.matcher(prefix).find()) {
return false;
}
int wildcard = prefix.indexOf('*');
String listed = wildcard < 0 ? prefix : prefix.substring(0, prefix.lastIndexOf('/', wildcard) + 1);
Pattern reached = wildcard < 0 ? null : Pattern.compile(Arrays.stream(prefix.split("\\*", -1))
.map(Pattern::quote).collect(Collectors.joining("[^/]*")) + ".+");
try {
return s3.listObjects(bucket, listed, null, Integer.MAX_VALUE).stream().map(S3Object::getKey)
.noneMatch(key -> !key.endsWith("/") && (reached == null || reached.matcher(key).matches()));
} catch (AwsException e) {
if ("NoSuchBucket".equals(e.getErrorCode())) {
return false;
}
throw e;
}
}
/** Hands each object under the location to {@code action}, a page at a time; the action may delete it. */
void forEachObject(S3Service s3, Consumer<S3Object> action) {
String continuation = null;
@@ -289,6 +289,76 @@ public final class GlueTableResolver {
return sb.toString();
}
/**
* A projection of no rows with the table's declared columns, each as its declared type, for a table whose
* location holds no data: Athena answers it with no rows, where a read of the empty location fails. Null for a
* table that declares no columns.
*/
public static String emptyProjection(Table table) {
List<Column> declared = declaredColumns(table);
if (declared.isEmpty()) {
return null;
}
return declared.stream()
.map(column -> "CAST(NULL AS " + columnType(column.getType()) + ") AS " + quote(column.getName()))
.collect(Collectors.joining(", ")) + " LIMIT 0";
}
/**
* The DuckDB type a Glue (Hive) column type reads as, {@code array<T>}, {@code map<K,V>} and
* {@code struct<name:T,...>} nested as far as they go, {@code binary} as a BLOB; a scalar type as
* {@link #scalarType} gives it, and VARCHAR for one this does not know.
*/
static String columnType(String glueType) {
String type = glueType == null ? "" : glueType.trim();
String lower = type.toLowerCase(Locale.ROOT);
if (lower.endsWith(">")) {
if (lower.startsWith("array<")) {
return columnType(type.substring("array<".length(), type.length() - 1)) + "[]";
}
if (lower.startsWith("map<")) {
List<String> keyAndValue = topLevelParts(type.substring("map<".length(), type.length() - 1));
if (keyAndValue.size() == 2) {
return "MAP(" + columnType(keyAndValue.get(0)) + ", " + columnType(keyAndValue.get(1)) + ")";
}
}
if (lower.startsWith("struct<")) {
List<String> fields = new ArrayList<>();
for (String field : topLevelParts(type.substring("struct<".length(), type.length() - 1))) {
int colon = field.indexOf(':');
if (colon <= 0) {
return "VARCHAR";
}
fields.add(quote(field.substring(0, colon).trim().replace("`", "")) + " "
+ columnType(field.substring(colon + 1)));
}
return fields.isEmpty() ? "VARCHAR" : "STRUCT(" + String.join(", ", fields) + ")";
}
return "VARCHAR";
}
return "binary".equals(lower) ? "BLOB" : scalarType(type);
}
/** The comma-separated parts of a type list, a comma inside {@code <>} or {@code ()} not separating two. */
private static List<String> topLevelParts(String list) {
List<String> parts = new ArrayList<>();
int depth = 0;
int start = 0;
for (int i = 0; i < list.length(); i++) {
char c = list.charAt(i);
if (c == '<' || c == '(') {
depth++;
} else if (c == '>' || c == ')') {
depth--;
} else if (c == ',' && depth == 0) {
parts.add(list.substring(start, i));
start = i + 1;
}
}
parts.add(list.substring(start));
return parts;
}
/**
* 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.
@@ -127,6 +127,30 @@ class AthenaDelimitedTextSidecarIntegrationTest {
Map.of("id", "4", "name", "dave", "name_null", "false", "note", "n")), rows);
}
/**
* A table whose location holds no data, or only a folder marker, answers no rows with its declared columns as
* their types, as Athena does, where reading the empty location fails to bind.
*/
@Test
void aTableWhoseLocationHoldsNoDataAnswersNoRows() {
put("marked/", new byte[0]);
tables.add(tsvTable("nothing", "nothing"));
tables.add(tsvTable("marked", "marked"));
for (String table : List.of("nothing", "marked")) {
assertEquals(List.of(Map.of("n", "0", "id_type", "BIGINT", "name_type", "VARCHAR")), query(
"SELECT count(*) AS n, typeof(max(id)) AS id_type, typeof(max(name)) AS name_type FROM "
+ view(table)), table);
}
Table nested = tsvTable("nested", "nested");
nested.getStorageDescriptor().setColumns(List.of(column("tags", "array<string>"),
column("who", "struct<name:string,age:int>")));
tables.add(nested);
assertEquals(List.of(Map.of("tags_type", "VARCHAR[]", "age_type", "INTEGER")),
query("SELECT typeof(any_value(tags)) AS tags_type, typeof(any_value(who).age) AS age_type FROM "
+ view("nested")));
}
// ---- helpers ----
private void put(String key, byte[] content) {
@@ -156,7 +180,7 @@ class AthenaDelimitedTextSidecarIntegrationTest {
database.setName(schema);
when(glue.getDatabases()).thenReturn(List.of(database));
when(glue.getTables(schema)).thenReturn(tables);
return new GlueViewDdlBuilder(glue);
return new GlueViewDdlBuilder(glue, s3Service);
}
private List<Map<String, String>> query(String sql) {
@@ -267,7 +267,7 @@ class AthenaPartitionTemplateSidecarIntegrationTest {
database.setName(schema);
when(glue.getDatabases()).thenReturn(List.of(database));
when(glue.getTables(schema)).thenReturn(tables);
String views = new GlueViewDdlBuilder(glue).build(null);
String views = new GlueViewDdlBuilder(glue, s3Service).build(null);
List<Map<String, String>> rows = new ArrayList<>();
for (Map<String, Object> row : duck.query(sql, views)) {
@@ -7,6 +7,8 @@ import io.floci.aws.services.glue.model.Column;
import io.floci.aws.services.glue.model.Database;
import io.floci.aws.services.glue.model.StorageDescriptor;
import io.floci.aws.services.glue.model.Table;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.services.s3.model.S3Object;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -20,17 +22,35 @@ import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.when;
class GlueViewDdlBuilderTest {
private GlueService glueService;
private S3Service s3;
private GlueViewDdlBuilder builder;
@BeforeEach
void setUp() {
glueService = Mockito.mock(GlueService.class);
builder = new GlueViewDdlBuilder(glueService);
s3 = Mockito.mock(S3Service.class);
// Every location holds a file each read glob here reaches, unless a test says otherwise.
when(s3.listObjects(anyString(), anyString(), isNull(), anyInt()))
.thenAnswer(call -> listing(call.getArgument(0), call.getArgument(1) + "region=a/dt=b/c/d/part-0"));
builder = new GlueViewDdlBuilder(glueService, s3);
}
private static List<S3Object> listing(String bucket, String... keys) {
return Arrays.stream(keys).map(key -> new S3Object(bucket, key, key.endsWith("/") ? 0 : 1, null, null))
.toList();
}
private void holds(String bucket, String prefix, String... keys) {
when(s3.listObjects(eq(bucket), eq(prefix), isNull(), anyInt())).thenReturn(listing(bucket, keys));
}
private Database createDatabase(String name) {
@@ -228,6 +248,60 @@ class GlueViewDdlBuilderTest {
+ "FROM read_parquet('s3://b/hive/region=*/dt=*/**', union_by_name = true);\n", ddl);
}
/**
* Athena answers a table whose location holds no data with no rows, where reading the empty location fails to
* bind: such a table gets a view of no rows with its declared columns as their types. Folder markers hold no
* data, and a projected table's location counts only the objects its read glob reaches.
*/
@Test
void aTableWhoseLocationHoldsNoDataGetsATypedViewOfNoRows() {
holds("lake", "events/");
String empty = "CREATE OR REPLACE VIEW \"audit\".\"events\" AS SELECT CAST(NULL AS BIGINT) AS \"id\", "
+ "CAST(NULL AS VARCHAR) AS \"name\", CAST(NULL AS VARCHAR) AS \"dt\" LIMIT 0;\n";
assertTrue(ddlFor(headerlessTsvTable("events", "s3://lake/events/")).contains(empty));
holds("lake", "events/", "events/", "events/dt=2026-11-16/");
assertTrue(ddlFor(headerlessTsvTable("events", "s3://lake/events")).contains(empty));
holds("b", "hive/", "hive/_SUCCESS", "hive/other/part-0");
assertTrue(ddlFor(projectingParquetTable("s3://b/hive/", Map.of("projection.enabled", "true")))
.contains("SELECT CAST(NULL AS VARCHAR) AS \"id\", CAST(NULL AS VARCHAR) AS \"region\", "
+ "CAST(NULL AS DATE) AS \"dt\" LIMIT 0;\n"));
holds("b", "hive/", "hive/region=eu/dt=2026-11-16/part-0");
assertTrue(ddlFor(projectingParquetTable("s3://b/hive/", Map.of("projection.enabled", "true")))
.contains("FROM read_parquet('s3://b/hive/region=*/dt=*/**'"));
}
/** A location whose bucket is gone is read as before, so the query reports it. */
@Test
void aTableInAMissingBucketIsReadAsBefore() {
when(s3.listObjects(eq("gone"), anyString(), isNull(), anyInt()))
.thenThrow(new AwsException("NoSuchBucket", "The specified bucket does not exist", 404));
assertTrue(ddlFor(headerlessTsvTable("events", "s3://gone/events/")).contains("read_csv('s3://gone/events/**'"));
}
/** A location holding a glob character the check does not model keeps the read, which the engine globs. */
@Test
void aLocationHoldingAnUnmodeledGlobIsReadAsBefore() {
holds("lake", "events?/");
holds("lake", "[ab]/");
assertTrue(ddlFor(headerlessTsvTable("events", "s3://lake/events?/")).contains("read_csv('s3://lake/events?/**'"));
assertTrue(ddlFor(headerlessTsvTable("events", "s3://lake/[ab]/")).contains("read_csv('s3://lake/[ab]/**'"));
}
/** The view of no rows types a nested or binary column as the engine reads it, not as text. */
@Test
void anEmptyViewTypesNestedAndBinaryColumns() {
holds("lake", "nested/");
Table table = tableWithColumns("nested", "s3://lake/nested/", List.of(column("tags", "array<string>"),
column("attrs", "map<string,int>"), column("who", "struct<name:string,ids:array<bigint>>"),
column("raw", "binary"), column("price", "decimal(10, 2)"), column("code", "varchar(8)")), null);
assertTrue(ddlFor(table).contains("AS SELECT CAST(NULL AS VARCHAR[]) AS \"tags\", "
+ "CAST(NULL AS MAP(VARCHAR, INTEGER)) AS \"attrs\", "
+ "CAST(NULL AS STRUCT(\"name\" VARCHAR, \"ids\" BIGINT[])) AS \"who\", CAST(NULL AS BLOB) AS \"raw\", "
+ "CAST(NULL AS DECIMAL(10, 2)) AS \"price\", CAST(NULL AS VARCHAR) AS \"code\" LIMIT 0;\n"));
}
private Table headerlessTsvTable(String name, String location) {
Table table = createTable(name, location, "org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe",
"org.apache.hadoop.mapred.TextInputFormat");