mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(athena): read a partitioned table through its registered partitions (#8587)
Athena reads a partitioned table through the partitions the Glue Data Catalog holds for it, each from its own location, and a table whose partitions are not loaded answers no rows. Floci read the table's whole location with Hive partitioning instead: a folder no partition names was read, a dropped partition's files still were, and a partition at a location outside the table's, or in a non-Hive layout, was not. - A Hive table with partition keys and no partition projection (GlueTableResolver.readsRegisteredPartitions) is read through the registered partitions holding data, each at its storage descriptor's location or <table location>/key=value/... for one that gives none (AthenaHiveDdlExecutor.defaultLocation). - They are read together (registeredPartitionsSelect): one read of every partition's location, columns matched by name, so a partition written before a column was added reads NULL for it, each row joined by its file's path to a VALUES row of its partition's location and values, cast to the keys' types. Hive's __HIVE_DEFAULT_PARTITION__ is NULL, and a value the type cannot hold fails the query with Athena's HIVE_INVALID_PARTITION_VALUE. - One listing of the table's location tells which partitions under it hold data; one elsewhere is listed on its own. The view is built once per batch for the qualified and unqualified views. - A partition that does not give one value for each key, which Glue refuses on AWS, is skipped. No partition holding data answers no rows, typed as the declared columns. AthenaDelimitedTextSidecarIntegrationTest reads a partition at its default folder and one outside the table's location, skips an unregistered folder, answers no rows with none registered, and fails a date key holding 'soon' with HIVE_INVALID_PARTITION_VALUE; it fails without this change. GlueViewDdlBuilderTest covers the view, typed keys, Hive's default partition, a Parquet read by name, a skipped malformed partition and the single listing. athena.md says so.
This commit is contained in:
1 parent
2842fe4eeb
commit
c05769395c
8 files changed
+365
-20
No files matched your search
@@ -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 partitioned table without partition projection is read through the partitions registered for it in Glue, as Athena reads it: each partition from its own location, with its values as the partition keys. The partitions come from `ALTER TABLE ADD PARTITION`, `MSCK REPAIR TABLE` or Glue's `CreatePartition` and `BatchCreatePartition`. A partition without a location of its own is read at `<table location>/key=value/...`. A folder under the table's location that no partition names isn't read, a partition's location may lie outside it, a non-Hive layout (`2026/11/16/`) is read through the partitions added for it, and a table with no partitions registered answers no rows until they are loaded. The partitions are read together with their columns matched by name, so a partition written before a column was added reads NULL for it. A partition value its key's type cannot hold fails the query with Athena's `HIVE_INVALID_PARTITION_VALUE`, and a partition that does not give one value for each key, which Glue refuses on AWS, is not read.
|
||||
|
||||
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
|
||||
|
||||
@@ -275,7 +275,7 @@ final class AthenaHiveDdlExecutor {
|
||||
}
|
||||
|
||||
/** Athena's location for a partition added without one: {@code <table location>/key=value/...}. */
|
||||
private static String defaultLocation(Table table, List<String> values) {
|
||||
static String defaultLocation(Table table, List<String> values) {
|
||||
String location = table.getStorageDescriptor() != null && table.getStorageDescriptor().getLocation() != null
|
||||
? table.getStorageDescriptor().getLocation() : "";
|
||||
StringBuilder path = new StringBuilder(location.endsWith("/") ? location : location + "/");
|
||||
|
||||
@@ -4,6 +4,7 @@ import io.floci.aws.services.glue.GlueService;
|
||||
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.Partition;
|
||||
import io.floci.aws.services.glue.model.Table;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -11,8 +12,11 @@ import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.NavigableSet;
|
||||
|
||||
@ApplicationScoped
|
||||
public class GlueViewDdlBuilder {
|
||||
@@ -48,6 +52,8 @@ public class GlueViewDdlBuilder {
|
||||
*/
|
||||
public String build(String contextDatabase, String query) {
|
||||
ViewFilter wanted = viewFilter(query);
|
||||
// A table read through its registered partitions is built once for its qualified and unqualified views.
|
||||
Map<String, String> partitionReads = new HashMap<>();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
boolean usesIceberg = false;
|
||||
boolean contextDbHandled = false;
|
||||
@@ -64,9 +70,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, wanted);
|
||||
usesIceberg |= appendViews(sb, schema, tables, true, wanted, partitionReads);
|
||||
if (schema.equals(contextDatabase)) {
|
||||
usesIceberg |= appendViews(sb, schema, tables, false, wanted);
|
||||
usesIceberg |= appendViews(sb, schema, tables, false, wanted, partitionReads);
|
||||
contextDbHandled = true;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
@@ -78,7 +84,7 @@ public class GlueViewDdlBuilder {
|
||||
if (!contextDbHandled && contextDatabase != null && !contextDatabase.isBlank()) {
|
||||
try {
|
||||
List<Table> tables = glueService.getTables(contextDatabase);
|
||||
usesIceberg |= appendViews(sb, contextDatabase, tables, false, wanted);
|
||||
usesIceberg |= appendViews(sb, contextDatabase, tables, false, wanted, partitionReads);
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Could not fetch tables for context database {0}: {1}", contextDatabase, e.getMessage());
|
||||
}
|
||||
@@ -93,7 +99,7 @@ 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,
|
||||
ViewFilter wanted) {
|
||||
ViewFilter wanted, Map<String, String> partitionReads) {
|
||||
if (tables == null) {
|
||||
return false;
|
||||
}
|
||||
@@ -132,6 +138,10 @@ public class GlueViewDdlBuilder {
|
||||
&& !GlueTableResolver.icebergMetadataLocation(t).isBlank()) {
|
||||
fromClause = GlueTableResolver.icebergReadExpression(GlueTableResolver.icebergMetadataLocation(t));
|
||||
usesIceberg = true;
|
||||
} else if (GlueTableResolver.readsRegisteredPartitions(t)) {
|
||||
sb.append("CREATE OR REPLACE VIEW ").append(target).append(" AS ")
|
||||
.append(registeredPartitionsSelect(schemaOrNull, t, partitionReads)).append(";\n");
|
||||
continue;
|
||||
} else {
|
||||
String readFn = GlueTableResolver.inferReadFunction(t);
|
||||
String readPath = GlueTableResolver.readPath(t, normalizedLocation);
|
||||
@@ -162,6 +172,66 @@ public class GlueViewDdlBuilder {
|
||||
return usesIceberg;
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows of a table Athena reads through its registered partitions, built once per batch for the table's
|
||||
* qualified and unqualified views: the partitions holding data, each at its own location (its storage
|
||||
* descriptor's, or {@code <table location>/key=value/...} for one that gives none) with its values as the
|
||||
* partition keys, read together ({@link GlueTableResolver#registeredPartitionsSelect}); no rows when none holds
|
||||
* data, as a table whose partitions are not loaded answers on Athena. A partition that does not give one value for
|
||||
* each key, which Glue refuses on AWS, is skipped rather than hiding the table.
|
||||
*/
|
||||
private String registeredPartitionsSelect(String database, Table table, Map<String, String> built) {
|
||||
String builtKey = database + "/" + table.getName();
|
||||
String select = built.get(builtKey);
|
||||
if (select != null) {
|
||||
return select;
|
||||
}
|
||||
String tableLocation = normalized(table.getStorageDescriptor().getLocation());
|
||||
TableLocation root = TableLocation.of(tableLocation);
|
||||
NavigableSet<String> rootKeys = null;
|
||||
boolean rootListed = false;
|
||||
List<GlueTableResolver.RegisteredPartition> holdingData = new ArrayList<>();
|
||||
List<Partition> partitions = glueService.getPartitions(database, table.getName());
|
||||
for (Partition partition : partitions == null ? List.<Partition>of() : partitions) {
|
||||
if (!GlueTableResolver.valuesEachKey(table, partition.getValues())) {
|
||||
LOG.debugv("skip a partition of Glue table {0}.{1}: values {2} do not match its keys",
|
||||
database, table.getName(), partition.getValues());
|
||||
continue;
|
||||
}
|
||||
String location = normalized(partition.getStorageDescriptor() != null
|
||||
&& partition.getStorageDescriptor().getLocation() != null
|
||||
&& !partition.getStorageDescriptor().getLocation().isBlank()
|
||||
? partition.getStorageDescriptor().getLocation()
|
||||
: AthenaHiveDdlExecutor.defaultLocation(table, partition.getValues()));
|
||||
TableLocation at = TableLocation.of(location);
|
||||
boolean holds;
|
||||
if (at == null) {
|
||||
holds = true;
|
||||
} else if (root != null && root.covers(at)) {
|
||||
// One listing of the table's location answers for every partition under it.
|
||||
if (!rootListed) {
|
||||
rootKeys = root.keysHoldingData(s3Service);
|
||||
rootListed = true;
|
||||
}
|
||||
String next = rootKeys == null ? null : rootKeys.ceiling(at.prefix());
|
||||
holds = rootKeys == null || next != null && next.startsWith(at.prefix());
|
||||
} else {
|
||||
holds = !at.holdsNoData(s3Service);
|
||||
}
|
||||
if (holds) {
|
||||
holdingData.add(new GlueTableResolver.RegisteredPartition(location, partition.getValues()));
|
||||
}
|
||||
}
|
||||
select = holdingData.isEmpty() ? "SELECT " + GlueTableResolver.emptyProjection(table)
|
||||
: GlueTableResolver.registeredPartitionsSelect(table, holdingData);
|
||||
built.put(builtKey, select);
|
||||
return select;
|
||||
}
|
||||
|
||||
private static String normalized(String location) {
|
||||
return location.endsWith("/") ? location.substring(0, location.length() - 1) : location;
|
||||
}
|
||||
|
||||
/** 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);
|
||||
|
||||
@@ -5,6 +5,8 @@ import io.floci.aws.services.s3.S3Service;
|
||||
import io.floci.aws.services.s3.model.S3Object;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.NavigableSet;
|
||||
import java.util.TreeSet;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -72,6 +74,31 @@ record TableLocation(String bucket, String prefix) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether {@code other} lies at or under this location, in the same bucket. */
|
||||
boolean covers(TableLocation other) {
|
||||
return bucket.equals(other.bucket) && other.prefix.startsWith(prefix);
|
||||
}
|
||||
|
||||
/**
|
||||
* The keys under the location that hold data, folder markers left out, from one scan, so the locations it covers
|
||||
* can be told apart without a listing each. Null when the location holds a glob character or its bucket does not
|
||||
* exist, which reading it reports as it did.
|
||||
*/
|
||||
NavigableSet<String> keysHoldingData(S3Service s3) {
|
||||
if (UNMODELED_GLOB.matcher(prefix).find() || prefix.indexOf('*') >= 0) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return s3.listObjects(bucket, prefix, null, Integer.MAX_VALUE).stream().map(S3Object::getKey)
|
||||
.filter(key -> !key.endsWith("/")).collect(Collectors.toCollection(TreeSet::new));
|
||||
} catch (AwsException e) {
|
||||
if ("NoSuchBucket".equals(e.getErrorCode())) {
|
||||
return null;
|
||||
}
|
||||
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;
|
||||
|
||||
@@ -45,6 +45,11 @@ public final class GlueTableResolver {
|
||||
*/
|
||||
private static final String OBJECT_PATH_COLUMN = "$path";
|
||||
|
||||
/** The value Hive gives a partition whose key is NULL. */
|
||||
private static final String HIVE_DEFAULT_PARTITION = "__HIVE_DEFAULT_PARTITION__";
|
||||
/** The column of a registered-partition read's value list holding each partition's location. */
|
||||
private static final String PARTITION_LOCATION_COLUMN = "$location";
|
||||
|
||||
/** The largest group index DuckDB's scalar {@code regexp_extract} accepts. */
|
||||
private static final int MAX_SCALAR_GROUP = 9;
|
||||
|
||||
@@ -304,6 +309,98 @@ public final class GlueTableResolver {
|
||||
.collect(Collectors.joining(", ")) + " LIMIT 0";
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether Athena reads the table through the partitions registered for it, each from its own location: a Hive
|
||||
* table with partition keys and no partition projection. A folder under its location that no partition names is
|
||||
* not read, and a partition's location may lie anywhere.
|
||||
*/
|
||||
public static boolean readsRegisteredPartitions(Table table) {
|
||||
return table != null && !isIcebergTable(table) && table.getPartitionKeys() != null
|
||||
&& !table.getPartitionKeys().isEmpty() && !PartitionProjection.enabled(table);
|
||||
}
|
||||
|
||||
/** A registered partition of a table: its location, without a trailing slash, and its values in key order. */
|
||||
public record RegisteredPartition(String location, List<String> values) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows of a table read through its registered partitions, Athena's way of reading a partitioned table: one read
|
||||
* of every partition's location, the files' columns matched by name across them ({@code union_by_name}, so a
|
||||
* partition written before a column was added reads NULL for it), each row joined by its file's path to the
|
||||
* partition whose location holds it, which gives its key values. The values are not in the files, and a
|
||||
* partition's location need not spell them.
|
||||
*/
|
||||
public static String registeredPartitionsSelect(Table table, List<RegisteredPartition> partitions) {
|
||||
List<Column> keys = new ArrayList<>();
|
||||
for (Column key : table.getPartitionKeys()) {
|
||||
if (key != null && key.getName() != null) {
|
||||
keys.add(key);
|
||||
}
|
||||
}
|
||||
Set<String> keyNames = new HashSet<>();
|
||||
keys.forEach(key -> keyNames.add(key.getName().toLowerCase(Locale.ROOT)));
|
||||
Map<String, Column> textColumns = readsDelimitedText(table) ? columnsByName(declaredColumns(table)) : Map.of();
|
||||
List<String> projected = new ArrayList<>();
|
||||
for (Column column : declaredColumns(table)) {
|
||||
String name = column.getName();
|
||||
if (keyNames.contains(name.toLowerCase(Locale.ROOT))) {
|
||||
projected.add("p." + quote(name) + " AS " + quote(name));
|
||||
continue;
|
||||
}
|
||||
Column text = textColumns.get(name.toLowerCase(Locale.ROOT));
|
||||
String read = "r." + quote(name);
|
||||
projected.add((text != null ? typedText(read, text.getType()) : read) + " AS " + quote(name));
|
||||
}
|
||||
List<String> rows = new ArrayList<>();
|
||||
List<String> globs = new ArrayList<>();
|
||||
for (RegisteredPartition partition : partitions) {
|
||||
globs.add("'" + escape(partition.location()) + "/**'");
|
||||
List<String> row = new ArrayList<>();
|
||||
row.add("'" + escape(partition.location()) + "/'");
|
||||
for (int i = 0; i < keys.size(); i++) {
|
||||
row.add(partitionValue(keys.get(i), partition.values().get(i)));
|
||||
}
|
||||
rows.add("(" + String.join(", ", row) + ")");
|
||||
}
|
||||
List<String> aliases = new ArrayList<>();
|
||||
aliases.add(quote(PARTITION_LOCATION_COLUMN));
|
||||
keys.forEach(key -> aliases.add(quote(key.getName())));
|
||||
String files = "[" + String.join(", ", globs) + "]";
|
||||
String options = ", filename = '" + escape(OBJECT_PATH_COLUMN) + "', hive_partitioning = false";
|
||||
String readFunction = inferReadFunction(table);
|
||||
String read = "read_csv_auto".equals(readFunction) && hasCsvOptions(table)
|
||||
? csvReadExpressionForInput(table, files, options)
|
||||
: readFunction + "(" + files + ", union_by_name = true" + options + ")";
|
||||
return "SELECT " + String.join(", ", projected) + " FROM " + read + " AS r JOIN (VALUES "
|
||||
+ String.join(", ", rows) + ") AS p(" + String.join(", ", aliases) + ") ON starts_with(r."
|
||||
+ quote(OBJECT_PATH_COLUMN) + ", p." + quote(PARTITION_LOCATION_COLUMN) + ")";
|
||||
}
|
||||
|
||||
/**
|
||||
* A registered partition's value as its key's type: Hive's {@code __HIVE_DEFAULT_PARTITION__} as NULL, and a value
|
||||
* the type cannot hold failing the query as Athena's does ({@code HIVE_INVALID_PARTITION_VALUE}).
|
||||
*/
|
||||
private static String partitionValue(Column key, String value) {
|
||||
String type = scalarType(key.getType());
|
||||
if (value == null || HIVE_DEFAULT_PARTITION.equals(value)) {
|
||||
return "CAST(NULL AS " + type + ")";
|
||||
}
|
||||
String literal = "'" + escape(value) + "'";
|
||||
if ("VARCHAR".equals(type)) {
|
||||
return literal;
|
||||
}
|
||||
String message = "HIVE_INVALID_PARTITION_VALUE: Invalid partition value '" + value + "' for " + type
|
||||
+ " partition key: " + key.getName() + "=" + value;
|
||||
return "CASE WHEN TRY_CAST(" + literal + " AS " + type + ") IS NULL THEN error('" + escape(message)
|
||||
+ "') ELSE CAST(" + literal + " AS " + type + ") END";
|
||||
}
|
||||
|
||||
/** Whether a registered partition gives one value for each of the table's partition keys. */
|
||||
public static boolean valuesEachKey(Table table, List<String> values) {
|
||||
return values != null && table.getPartitionKeys() != null && values.size() == table.getPartitionKeys().size()
|
||||
&& values.stream().allMatch(value -> value != null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
||||
+55
-2
@@ -4,6 +4,7 @@ import io.floci.aws.services.floci.duck.FlociDuckClient;
|
||||
import io.floci.aws.services.glue.GlueService;
|
||||
import io.floci.aws.services.glue.model.Column;
|
||||
import io.floci.aws.services.glue.model.Database;
|
||||
import io.floci.aws.services.glue.model.Partition;
|
||||
import io.floci.aws.services.glue.model.StorageDescriptor;
|
||||
import io.floci.aws.services.glue.model.Table;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
@@ -20,12 +21,16 @@ import org.mockito.Mockito;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
@@ -51,6 +56,7 @@ class AthenaDelimitedTextSidecarIntegrationTest {
|
||||
private String schema;
|
||||
private final List<String> keys = new ArrayList<>();
|
||||
private final List<Table> tables = new ArrayList<>();
|
||||
private final Map<String, List<Partition>> partitions = new HashMap<>();
|
||||
|
||||
@BeforeAll
|
||||
static void requireDocker() {
|
||||
@@ -65,6 +71,8 @@ class AthenaDelimitedTextSidecarIntegrationTest {
|
||||
put("events/dt=2026-11-14/part-00000.tsv", "1\talice\n2\tbob\n".getBytes(StandardCharsets.UTF_8));
|
||||
put("events/dt=2026-11-15/part-00001.tsv.zst", ZSTD_ROW);
|
||||
tables.add(tsvTable("events", "events"));
|
||||
register("events", "2026-11-14", null);
|
||||
register("events", "2026-11-15", null);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
@@ -97,6 +105,7 @@ class AthenaDelimitedTextSidecarIntegrationTest {
|
||||
broken.getStorageDescriptor().getSerdeInfo()
|
||||
.setSerializationLibrary("org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe");
|
||||
tables.add(broken);
|
||||
register("not_parquet", "2026-11-14", null);
|
||||
String sql = "SELECT count(*) AS n FROM " + view("events");
|
||||
|
||||
assertThrows(RuntimeException.class, () -> duck.query(sql, builder().build(null)),
|
||||
@@ -116,6 +125,7 @@ class AthenaDelimitedTextSidecarIntegrationTest {
|
||||
evolved.getStorageDescriptor().setColumns(List.of(column("id", "bigint"), column("name", "string"),
|
||||
column("note", "string")));
|
||||
tables.add(evolved);
|
||||
register("evolved", "2026-11-16", null);
|
||||
|
||||
List<Map<String, String>> rows = query("SELECT id, name, name IS NULL AS name_null, note FROM "
|
||||
+ view("evolved") + " ORDER BY id");
|
||||
@@ -134,8 +144,11 @@ class AthenaDelimitedTextSidecarIntegrationTest {
|
||||
@Test
|
||||
void aTableWhoseLocationHoldsNoDataAnswersNoRows() {
|
||||
put("marked/", new byte[0]);
|
||||
tables.add(tsvTable("nothing", "nothing"));
|
||||
tables.add(tsvTable("marked", "marked"));
|
||||
for (String name : List.of("nothing", "marked")) {
|
||||
Table table = tsvTable(name, name);
|
||||
table.setPartitionKeys(List.of());
|
||||
tables.add(table);
|
||||
}
|
||||
|
||||
for (String table : List.of("nothing", "marked")) {
|
||||
assertEquals(List.of(Map.of("n", "0", "id_type", "BIGINT", "name_type", "VARCHAR")), query(
|
||||
@@ -143,6 +156,7 @@ class AthenaDelimitedTextSidecarIntegrationTest {
|
||||
+ view(table)), table);
|
||||
}
|
||||
Table nested = tsvTable("nested", "nested");
|
||||
nested.setPartitionKeys(List.of());
|
||||
nested.getStorageDescriptor().setColumns(List.of(column("tags", "array<string>"),
|
||||
column("who", "struct<name:string,age:int>")));
|
||||
tables.add(nested);
|
||||
@@ -151,8 +165,45 @@ class AthenaDelimitedTextSidecarIntegrationTest {
|
||||
+ view("nested")));
|
||||
}
|
||||
|
||||
/**
|
||||
* A partitioned table is read through its registered partitions, as Athena reads it: a partition at its default
|
||||
* folder and one whose location lies outside the table's are read, with the partition's value as the key, and a
|
||||
* folder under the table's location that no partition names is not.
|
||||
*/
|
||||
@Test
|
||||
void aPartitionedTableIsReadThroughItsRegisteredPartitions() {
|
||||
put("loaded/dt=2026-11-14/part-0.tsv", "1\talice\n".getBytes(StandardCharsets.UTF_8));
|
||||
put("loaded/dt=2026-11-15/part-0.tsv", "2\tbob\n".getBytes(StandardCharsets.UTF_8));
|
||||
put("archive/2026/11/16/part-0.tsv", "3\tcarol\n".getBytes(StandardCharsets.UTF_8));
|
||||
tables.add(tsvTable("loaded", "loaded"));
|
||||
register("loaded", "2026-11-14", null);
|
||||
register("loaded", "2026-11-16", "s3://" + bucket + "/archive/2026/11/16/");
|
||||
|
||||
assertEquals(List.of(Map.of("id", "1", "name", "alice", "dt", "2026-11-14"),
|
||||
Map.of("id", "3", "name", "carol", "dt", "2026-11-16")),
|
||||
query("SELECT id, name, dt FROM " + view("loaded") + " ORDER BY id"));
|
||||
tables.add(tsvTable("unloaded", "loaded"));
|
||||
assertEquals(List.of(Map.of("n", "0")), query("SELECT count(*) AS n FROM " + view("unloaded")));
|
||||
|
||||
// A value its key's type cannot hold fails the query as Athena's does.
|
||||
Table typed = tsvTable("typed", "loaded");
|
||||
typed.setPartitionKeys(List.of(column("dt", "date")));
|
||||
tables.add(typed);
|
||||
register("typed", "soon", "s3://" + bucket + "/archive/2026/11/16/");
|
||||
RuntimeException invalid = assertThrows(RuntimeException.class,
|
||||
() -> query("SELECT count(*) AS n FROM " + view("typed")));
|
||||
assertTrue(invalid.getMessage().contains(
|
||||
"HIVE_INVALID_PARTITION_VALUE: Invalid partition value 'soon' for DATE partition key: dt=soon"),
|
||||
invalid.getMessage());
|
||||
}
|
||||
|
||||
// ---- helpers ----
|
||||
|
||||
/** Registers a partition of {@code table} for {@code dt}, at {@code location} or, when null, its default folder. */
|
||||
private void register(String table, String dt, String location) {
|
||||
partitions.computeIfAbsent(table, ignored -> new ArrayList<>()).add(GluePartitions.partition(location, dt));
|
||||
}
|
||||
|
||||
private void put(String key, byte[] content) {
|
||||
s3Service.putObject(bucket, key, content, "application/octet-stream", null);
|
||||
keys.add(key);
|
||||
@@ -180,6 +231,8 @@ class AthenaDelimitedTextSidecarIntegrationTest {
|
||||
database.setName(schema);
|
||||
when(glue.getDatabases()).thenReturn(List.of(database));
|
||||
when(glue.getTables(schema)).thenReturn(tables);
|
||||
when(glue.getPartitions(eq(schema), anyString()))
|
||||
.thenAnswer(call -> partitions.getOrDefault(call.getArgument(1), List.of()));
|
||||
return new GlueViewDdlBuilder(glue, s3Service);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package io.floci.aws.services.athena;
|
||||
|
||||
import io.floci.aws.services.glue.model.Partition;
|
||||
import io.floci.aws.services.glue.model.StorageDescriptor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** Glue partitions for the Athena tests. */
|
||||
final class GluePartitions {
|
||||
|
||||
private GluePartitions() {
|
||||
}
|
||||
|
||||
/** A partition with {@code values}, at {@code location} or, when it is null, with no location of its own. */
|
||||
static Partition partition(String location, String... values) {
|
||||
Partition partition = new Partition();
|
||||
partition.setValues(List.of(values));
|
||||
if (location != null) {
|
||||
StorageDescriptor descriptor = new StorageDescriptor();
|
||||
descriptor.setLocation(location);
|
||||
partition.setStorageDescriptor(descriptor);
|
||||
}
|
||||
return partition;
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.floci.aws.services.athena.GluePartitions.partition;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -26,6 +27,8 @@ 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.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class GlueViewDdlBuilderTest {
|
||||
@@ -104,6 +107,8 @@ class GlueViewDdlBuilderTest {
|
||||
*/
|
||||
@Test
|
||||
void testDeclaredColumnsAreProjectedInsteadOfStar() {
|
||||
holds("audit", "", "tenant=acme/year=2026/part-0");
|
||||
when(glueService.getPartitions("audit", "audit_events")).thenReturn(List.of(partition(null, "acme", "2026")));
|
||||
String ddl = ddlFor(tableWithColumns("audit_events", "s3://audit/",
|
||||
List.of(column("eventid"), column("tenantid")),
|
||||
List.of(column("tenant"), column("year"))));
|
||||
@@ -116,13 +121,17 @@ class GlueViewDdlBuilderTest {
|
||||
/** Partition keys are part of the schema and are what partition predicates filter on. */
|
||||
@Test
|
||||
void testPartitionKeysAreProjectedAlongsideDataColumns() {
|
||||
holds("audit", "", "tenant=acme/year=2026/month=11/day=16/part-0");
|
||||
when(glueService.getPartitions("audit", "audit_events"))
|
||||
.thenReturn(List.of(partition(null, "acme", "2026", "11", "16")));
|
||||
String ddl = ddlFor(tableWithColumns("audit_events", "s3://audit/",
|
||||
List.of(column("eventid")),
|
||||
List.of(column("tenant"), column("year"), column("month"), column("day"))));
|
||||
|
||||
for (String name : List.of("eventid", "tenant", "year", "month", "day")) {
|
||||
assertTrue(ddl.contains("\"" + name + "\" AS \"" + name + "\""), name + " missing from: " + ddl);
|
||||
}
|
||||
assertTrue(ddl.contains("AS SELECT r.\"eventid\" AS \"eventid\", p.\"tenant\" AS \"tenant\", p.\"year\" AS \"year\", "
|
||||
+ "p.\"month\" AS \"month\", p.\"day\" AS \"day\" FROM read_json_auto(['s3://audit/tenant=acme/year=2026/month=11/day=16/**'], "
|
||||
+ "union_by_name = true, filename = '$path', hive_partitioning = false) AS r JOIN (VALUES "
|
||||
+ "('s3://audit/tenant=acme/year=2026/month=11/day=16/', 'acme', '2026', '11', '16'))"), ddl);
|
||||
}
|
||||
|
||||
/** A partition key repeating a data column would bind twice and make the view ambiguous. */
|
||||
@@ -257,11 +266,11 @@ class GlueViewDdlBuilderTest {
|
||||
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));
|
||||
+ "CAST(NULL AS VARCHAR) AS \"name\" LIMIT 0;\n";
|
||||
assertTrue(ddlFor(unpartitioned(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));
|
||||
assertTrue(ddlFor(unpartitioned(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")))
|
||||
@@ -272,12 +281,61 @@ class GlueViewDdlBuilderTest {
|
||||
.contains("FROM read_parquet('s3://b/hive/region=*/dt=*/**'"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A partitioned table is read through its registered partitions: each holding data from its own location, its
|
||||
* default folder or one outside the table's, with its values as the keys (Hive's default partition as NULL); none
|
||||
* registered or none holding data answers no rows.
|
||||
*/
|
||||
@Test
|
||||
void aPartitionedTableIsReadThroughItsRegisteredPartitions() {
|
||||
Table table = headerlessTsvTable("events", "s3://lake/events/");
|
||||
assertTrue(ddlFor(table).contains("\"events\" AS SELECT CAST(NULL AS BIGINT) AS \"id\", "
|
||||
+ "CAST(NULL AS VARCHAR) AS \"name\", CAST(NULL AS VARCHAR) AS \"dt\" LIMIT 0;\n"));
|
||||
|
||||
holds("lake", "events/", "events/dt=2026-11-14/part-0", "events/dt=2026-11-17/part-0");
|
||||
when(glueService.getPartitions("audit", "events")).thenReturn(List.of(partition(null, "2026-11-14"),
|
||||
partition("s3://archive/2026/11/16", "__HIVE_DEFAULT_PARTITION__"), partition(null, "2026-11-15"),
|
||||
partition(null)));
|
||||
String ddl = ddlFor(table);
|
||||
assertTrue(ddl.contains("AS SELECT TRY_CAST(r.\"id\" AS BIGINT) AS \"id\", r.\"name\" AS \"name\", p.\"dt\" AS \"dt\" "
|
||||
+ "FROM read_csv(['s3://lake/events/dt=2026-11-14/**', 's3://archive/2026/11/16/**'], header = false"), ddl);
|
||||
assertTrue(ddl.contains(", filename = '$path', hive_partitioning = false) AS r JOIN (VALUES "
|
||||
+ "('s3://lake/events/dt=2026-11-14/', '2026-11-14'), ('s3://archive/2026/11/16/', CAST(NULL AS VARCHAR))) "
|
||||
+ "AS p(\"$location\", \"dt\") ON starts_with(r.\"$path\", p.\"$location\");\n"), ddl);
|
||||
assertFalse(ddl.contains("2026-11-15") || ddl.contains("2026-11-17"), ddl);
|
||||
// One listing of the table's location answers for every partition under it.
|
||||
verify(s3, times(1)).listObjects(eq("lake"), eq("events/"), isNull(), anyInt());
|
||||
}
|
||||
|
||||
/**
|
||||
* A Parquet table's partitions are read together, columns matched by name, so a partition written before a column
|
||||
* was added reads NULL for it; a value its key's type cannot hold fails the query with Athena's
|
||||
* HIVE_INVALID_PARTITION_VALUE rather than reading its rows under a NULL key.
|
||||
*/
|
||||
@Test
|
||||
void parquetPartitionsAreReadByNameAndAnInvalidValueFailsAsAthenaDoes() {
|
||||
Table table = createTable("events", "s3://lake/parquet/", PARQUET_SERDE, null);
|
||||
table.getStorageDescriptor().setColumns(List.of(column("id", "bigint"), column("added", "string")));
|
||||
table.setPartitionKeys(List.of(column("year", "int")));
|
||||
holds("lake", "parquet/", "parquet/year=2026/part-0", "parquet/year=soon/part-0");
|
||||
when(glueService.getPartitions("audit", "events")).thenReturn(List.of(partition(null, "2026"),
|
||||
partition(null, "soon")));
|
||||
|
||||
String ddl = ddlFor(table);
|
||||
assertTrue(ddl.contains("FROM read_parquet(['s3://lake/parquet/year=2026/**', 's3://lake/parquet/year=soon/**'], "
|
||||
+ "union_by_name = true, filename = '$path', hive_partitioning = false) AS r"), ddl);
|
||||
assertTrue(ddl.contains("CASE WHEN TRY_CAST('soon' AS INTEGER) IS NULL THEN error('HIVE_INVALID_PARTITION_VALUE: "
|
||||
+ "Invalid partition value ''soon'' for INTEGER partition key: year=soon') ELSE CAST('soon' AS INTEGER) END"),
|
||||
ddl);
|
||||
}
|
||||
|
||||
/** 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/**'"));
|
||||
assertTrue(ddlFor(unpartitioned(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. */
|
||||
@@ -285,8 +343,15 @@ class GlueViewDdlBuilderTest {
|
||||
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]/**'"));
|
||||
assertTrue(ddlFor(unpartitioned(headerlessTsvTable("events", "s3://lake/events?/")))
|
||||
.contains("read_csv('s3://lake/events?/**'"));
|
||||
assertTrue(ddlFor(unpartitioned(headerlessTsvTable("events", "s3://lake/[ab]/")))
|
||||
.contains("read_csv('s3://lake/[ab]/**'"));
|
||||
}
|
||||
|
||||
private static Table unpartitioned(Table table) {
|
||||
table.setPartitionKeys(List.of());
|
||||
return table;
|
||||
}
|
||||
|
||||
/** The view of no rows types a nested or binary column as the engine reads it, not as text. */
|
||||
@@ -313,12 +378,15 @@ class GlueViewDdlBuilderTest {
|
||||
|
||||
@Test
|
||||
void headerlessDelimitedTextIsReadWithItsDelimiterColumnNamesAndTypes() {
|
||||
holds("lake", "events/", "events/dt=2026-11-16/part-0");
|
||||
when(glueService.getPartitions("audit", "events")).thenReturn(List.of(partition(null, "2026-11-16")));
|
||||
String ddl = ddlFor(headerlessTsvTable("events", "s3://lake/events/"));
|
||||
|
||||
assertTrue(ddl.contains("read_csv('s3://lake/events/**', header = false, delim = '\t', quote = '', "
|
||||
assertTrue(ddl.contains("read_csv(['s3://lake/events/dt=2026-11-16/**'], header = false, delim = '\t', quote = '', "
|
||||
+ "nullstr = '\\N', auto_detect = false, null_padding = true, strict_mode = false, "
|
||||
+ "columns = {'id': 'VARCHAR', 'name': 'VARCHAR'}, hive_types_autocast = false)"), ddl);
|
||||
assertTrue(ddl.contains("SELECT TRY_CAST(\"id\" AS BIGINT) AS \"id\", \"name\" AS \"name\", \"dt\" AS \"dt\" FROM"), ddl);
|
||||
+ "columns = {'id': 'VARCHAR', 'name': 'VARCHAR'}, filename = '$path', hive_partitioning = false)"), ddl);
|
||||
assertTrue(ddl.contains("SELECT TRY_CAST(r.\"id\" AS BIGINT) AS \"id\", r.\"name\" AS \"name\", "
|
||||
+ "p.\"dt\" AS \"dt\" FROM"), ddl);
|
||||
assertFalse(ddl.contains("read_csv_auto"), ddl);
|
||||
}
|
||||
|
||||
@@ -326,10 +394,13 @@ class GlueViewDdlBuilderTest {
|
||||
void delimitedTextPartitionKeysTakeTheirDeclaredTypesToo() {
|
||||
Table table = headerlessTsvTable("events", "s3://lake/events/");
|
||||
table.setPartitionKeys(List.of(column("year", "int")));
|
||||
holds("lake", "events/", "events/year=2026/part-0");
|
||||
when(glueService.getPartitions("audit", "events")).thenReturn(List.of(partition(null, "2026")));
|
||||
|
||||
String ddl = ddlFor(table);
|
||||
|
||||
assertTrue(ddl.contains("TRY_CAST(\"year\" AS INTEGER) AS \"year\""), ddl);
|
||||
assertTrue(ddl.contains("ELSE CAST('2026' AS INTEGER) END)"), ddl);
|
||||
assertTrue(ddl.contains("p.\"year\" AS \"year\""), ddl);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user