mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(athena): read Iceberg-format Glue tables via iceberg_scan (#3738)
* feat(athena): read Iceberg-format Glue tables via iceberg_scan Glue tables written by pyiceberg's GlueCatalog (Parameters.table_type= ICEBERG) never populate StorageDescriptor.InputFormat/SerializationLibrary, so GlueViewDdlBuilder's format-sniffing heuristic always fell through to read_csv_auto and failed parsing the table's binary Parquet data files. Detect Iceberg tables via Parameters.table_type and build the view from iceberg_scan(Parameters.metadata_location) instead, following the table's real manifest list rather than globbing every Parquet file physically present under its location -- which also fixes silently wrong results for any table with more than one snapshot (updates, deletes, repeated appends), not just the CSV-parse failure on a single-snapshot table. The iceberg extension is installed/loaded once, only when the DDL batch actually contains an Iceberg table. A table flagged ICEBERG but missing metadata_location falls back to the existing format-sniffed heuristic. Verified against a live build: pyiceberg write -> Athena SELECT returns correct rows for both a single-snapshot and a two-snapshot table; full athena + glue test suites (352 tests) pass with no regressions. Fixes #3737 This change was implemented by Claude (Anthropic's AI coding assistant), working on behalf of @maurice1979 who filed the linked issue. * docs(athena): fix formatting and clarify Iceberg handling explanation Corrected formatting and clarified the explanation regarding Iceberg tables and their handling in DuckDB. Signed-off-by: Jordi Vidal de LLobatera <is.maurice@protonmail.com> * docs(glue): cross-reference Iceberg handling from glue.md; fix em dash docs/services/glue.md still described only the InputFormat/SerdeInfo format-sniffing heuristic for choosing a DuckDB read function, without mentioning that Iceberg-format tables (Parameters.table_type=ICEBERG) bypass it entirely via iceberg_scan, per the change in the previous commit. Added a short cross-reference to Athena's format-inference docs so glue.md doesn't describe stale, pre-fix behavior. Also removed an em dash from GlueViewDdlBuilder's new Javadoc, per this repo's own AGENTS.md style rule (no em dashes; colons, commas, or periods instead). The matching instance in docs/services/athena.md was already fixed via the Copilot autofix suggestion. Both findings came from the Copilot pull request review on #3738. This change was implemented by Claude (Anthropic's AI coding assistant), working on behalf of @maurice1979. --------- Signed-off-by: Jordi Vidal de LLobatera <is.maurice@protonmail.com>
This commit is contained in:
1 parent
dfbb0ee756
commit
9740b32b51
4 files changed
+136
-10
No files matched your search
@@ -42,7 +42,9 @@ Floci emulates Amazon Athena with **real SQL execution** powered by a [floci-duc
|
||||
|
||||
## Format inference
|
||||
|
||||
The DuckDB read function is chosen from the Glue table's `StorageDescriptor`:
|
||||
**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('')`.
|
||||
|
||||
For every other table, the DuckDB read function is chosen from the Glue table's `StorageDescriptor`:
|
||||
|
||||
| Condition | Read function |
|
||||
|---|---|
|
||||
|
||||
@@ -135,7 +135,9 @@ The Glue Data Catalog is automatically used by **Athena** to resolve table names
|
||||
|
||||
Tables can reference a Schema Registry schema version through `StorageDescriptor.SchemaReference`. On `GetTable` and `GetTables`, Floci resolves the schema definition into Glue columns when possible.
|
||||
|
||||
The DuckDB read function is selected based on the table's `StorageDescriptor.InputFormat` and `StorageDescriptor.SerdeInfo.SerializationLibrary`:
|
||||
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` against `Parameters.metadata_location` instead, following the table's real manifest list rather than its `StorageDescriptor`. See [Athena's format inference](athena.md#format-inference) for the full explanation.
|
||||
|
||||
For every other table, the DuckDB read function is selected based on the table's `StorageDescriptor.InputFormat` and `StorageDescriptor.SerdeInfo.SerializationLibrary`:
|
||||
|
||||
| Condition | DuckDB function |
|
||||
|---|---|
|
||||
|
||||
@@ -19,6 +19,21 @@ public class GlueViewDdlBuilder {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(GlueViewDdlBuilder.class);
|
||||
|
||||
/**
|
||||
* Iceberg tables are read through the {@code iceberg} extension rather than one of the
|
||||
* Hive-format-sniffed {@code read_*} functions, so it is installed and loaded once, up
|
||||
* front, only when the batch actually contains an Iceberg table.
|
||||
*/
|
||||
private static final String ICEBERG_EXTENSION_SETUP = "INSTALL iceberg; LOAD iceberg;\n";
|
||||
|
||||
/** Glue table property AWS/pyiceberg set to mark a table as Iceberg-format. */
|
||||
private static final String PARAM_TABLE_TYPE = "table_type";
|
||||
|
||||
/** Glue table property holding the path to the table's current Iceberg metadata JSON. */
|
||||
private static final String PARAM_METADATA_LOCATION = "metadata_location";
|
||||
|
||||
private static final String ICEBERG_TABLE_TYPE = "ICEBERG";
|
||||
|
||||
private final GlueService glueService;
|
||||
|
||||
@Inject
|
||||
@@ -28,6 +43,7 @@ public class GlueViewDdlBuilder {
|
||||
|
||||
public String build(String contextDatabase) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
boolean usesIceberg = false;
|
||||
boolean contextDbHandled = false;
|
||||
List<Database> databases = glueService.getDatabases();
|
||||
if (databases != null) {
|
||||
@@ -42,9 +58,9 @@ public class GlueViewDdlBuilder {
|
||||
sb.append("CREATE SCHEMA IF NOT EXISTS ").append(quote(schema)).append(";\n");
|
||||
try {
|
||||
List<Table> tables = glueService.getTables(schema);
|
||||
appendViews(sb, schema, tables, true);
|
||||
usesIceberg |= appendViews(sb, schema, tables, true);
|
||||
if (schema.equals(contextDatabase)) {
|
||||
appendViews(sb, schema, tables, false);
|
||||
usesIceberg |= appendViews(sb, schema, tables, false);
|
||||
contextDbHandled = true;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
@@ -56,19 +72,25 @@ public class GlueViewDdlBuilder {
|
||||
if (!contextDbHandled && contextDatabase != null && !contextDatabase.isBlank()) {
|
||||
try {
|
||||
List<Table> tables = glueService.getTables(contextDatabase);
|
||||
appendViews(sb, contextDatabase, tables, false);
|
||||
usesIceberg |= appendViews(sb, contextDatabase, tables, false);
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Could not fetch tables for context database {0}: {1}", contextDatabase, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
if (usesIceberg) {
|
||||
sb.insert(0, ICEBERG_EXTENSION_SETUP);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void appendViews(StringBuilder sb, String schemaOrNull, List<Table> tables, boolean qualified) {
|
||||
/** @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) {
|
||||
if (tables == null) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
boolean usesIceberg = false;
|
||||
for (Table t : tables) {
|
||||
try {
|
||||
if (t == null) {
|
||||
@@ -86,22 +108,30 @@ public class GlueViewDdlBuilder {
|
||||
String normalizedLocation = location.endsWith("/")
|
||||
? location.substring(0, location.length() - 1)
|
||||
: location;
|
||||
String readFn = inferReadFunction(t);
|
||||
String readPath = PartitionProjection.readPath(t, normalizedLocation);
|
||||
String target = qualified
|
||||
? quote(schemaOrNull) + "." + quote(t.getName())
|
||||
: quote(t.getName());
|
||||
String fromClause;
|
||||
if (isIcebergTable(t) && icebergMetadataLocation(t) != null && !icebergMetadataLocation(t).isBlank()) {
|
||||
fromClause = icebergReadExpression(icebergMetadataLocation(t));
|
||||
usesIceberg = true;
|
||||
} else {
|
||||
String readFn = inferReadFunction(t);
|
||||
String readPath = PartitionProjection.readPath(t, normalizedLocation);
|
||||
fromClause = readExpression(readFn, readPath);
|
||||
}
|
||||
sb.append("CREATE OR REPLACE VIEW ")
|
||||
.append(target)
|
||||
.append(" AS SELECT ")
|
||||
.append(buildProjection(t))
|
||||
.append(" FROM ")
|
||||
.append(readExpression(readFn, readPath))
|
||||
.append(fromClause)
|
||||
.append(";\n");
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("skip Glue table {0}.{1}: {2}", schemaOrNull, t != null ? t.getName() : "unknown", e.getMessage());
|
||||
}
|
||||
}
|
||||
return usesIceberg;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -183,6 +213,29 @@ public class GlueViewDdlBuilder {
|
||||
return readFn + "('" + glob + "')";
|
||||
}
|
||||
|
||||
/**
|
||||
* Iceberg tables are not read via a Hive {@code InputFormat}/{@code SerializationLibrary}
|
||||
* pair at all: pyiceberg and the AWS Glue-Iceberg integration leave those unset, so
|
||||
* {@link #inferReadFunction} would otherwise fall through to {@code read_csv_auto} and fail
|
||||
* on the table's binary Parquet data files, or a forced {@code read_parquet} would silently
|
||||
* glob every data file ever written under the table's location, including ones no longer
|
||||
* referenced by the current snapshot. Following the catalog's own {@code metadata_location}
|
||||
* into {@code iceberg_scan} instead resolves the table through its real manifest list.
|
||||
*/
|
||||
static boolean isIcebergTable(Table table) {
|
||||
return table != null
|
||||
&& table.getParameters() != null
|
||||
&& ICEBERG_TABLE_TYPE.equalsIgnoreCase(table.getParameters().get(PARAM_TABLE_TYPE));
|
||||
}
|
||||
|
||||
static String icebergMetadataLocation(Table table) {
|
||||
return table.getParameters().get(PARAM_METADATA_LOCATION);
|
||||
}
|
||||
|
||||
static String icebergReadExpression(String metadataLocation) {
|
||||
return "iceberg_scan('" + metadataLocation.replace("'", "''") + "')";
|
||||
}
|
||||
|
||||
static boolean containsIgnoreCase(String str, String sub) {
|
||||
return str != null && str.toLowerCase(Locale.ROOT).contains(sub);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
@@ -315,5 +316,73 @@ class GlueViewDdlBuilderTest {
|
||||
assertTrue(ddl.contains("CREATE OR REPLACE VIEW \"orders\""));
|
||||
Mockito.verify(glueService, Mockito.times(1)).getTables("shop");
|
||||
}
|
||||
|
||||
private Table icebergTable(String name, String location, String metadataLocation) {
|
||||
Table table = createTable(name, location, null, null);
|
||||
table.setParameters(metadataLocation == null
|
||||
? Map.of("table_type", "ICEBERG")
|
||||
: Map.of("table_type", "ICEBERG", "metadata_location", metadataLocation));
|
||||
return table;
|
||||
}
|
||||
|
||||
/**
|
||||
* pyiceberg's GlueCatalog (and AWS's own Glue-Iceberg integration) never populate
|
||||
* InputFormat/SerializationLibrary, so an Iceberg table must be detected from
|
||||
* Parameters.table_type rather than format-sniffed like every other table kind.
|
||||
*/
|
||||
@Test
|
||||
void testIcebergTableUsesIcebergScanOnMetadataLocation() {
|
||||
Table table = icebergTable("orders", "s3://bucket/warehouse/orders",
|
||||
"s3://bucket/warehouse/orders/metadata/00001-abc.metadata.json");
|
||||
String ddl = ddlFor(table);
|
||||
|
||||
assertTrue(ddl.contains(
|
||||
"CREATE OR REPLACE VIEW \"audit\".\"orders\" AS SELECT * FROM "
|
||||
+ "iceberg_scan('s3://bucket/warehouse/orders/metadata/00001-abc.metadata.json');\n"),
|
||||
ddl);
|
||||
}
|
||||
|
||||
/** The iceberg extension is expensive to install, so it's only requested when actually needed. */
|
||||
@Test
|
||||
void testIcebergExtensionSetupOnlyEmittedWhenTableIsIceberg() {
|
||||
Table icebergTable = icebergTable("orders", "s3://bucket/orders",
|
||||
"s3://bucket/orders/metadata/00000.metadata.json");
|
||||
String ddlWithIceberg = ddlFor(icebergTable);
|
||||
assertTrue(ddlWithIceberg.startsWith("INSTALL iceberg; LOAD iceberg;\n"), ddlWithIceberg);
|
||||
|
||||
Table plainTable = createTable("orders", "s3://bucket/orders", null, null);
|
||||
String ddlWithoutIceberg = ddlFor(plainTable);
|
||||
assertFalse(ddlWithoutIceberg.contains("iceberg"), ddlWithoutIceberg);
|
||||
}
|
||||
|
||||
/** A malformed Iceberg table (flagged as Iceberg but missing metadata_location) falls back
|
||||
* to format inference rather than emitting an unusable iceberg_scan('') call. */
|
||||
@Test
|
||||
void testIcebergTableWithoutMetadataLocationFallsBackToFormatInference() {
|
||||
Table table = icebergTable("orders", "s3://bucket/orders", null);
|
||||
String ddl = ddlFor(table);
|
||||
|
||||
assertTrue(ddl.contains("FROM read_csv_auto('s3://bucket/orders/**');\n"), ddl);
|
||||
assertFalse(ddl.contains("iceberg_scan"), ddl);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsIcebergTableDetection() {
|
||||
assertFalse(GlueViewDdlBuilder.isIcebergTable(null));
|
||||
assertFalse(GlueViewDdlBuilder.isIcebergTable(createTable("t", "s3://b/t", null, null)));
|
||||
|
||||
Table table = createTable("t", "s3://b/t", null, null);
|
||||
table.setParameters(Map.of("table_type", "iceberg"));
|
||||
assertTrue(GlueViewDdlBuilder.isIcebergTable(table), "table_type comparison should be case-insensitive");
|
||||
|
||||
table.setParameters(Map.of("table_type", "EXTERNAL_TABLE"));
|
||||
assertFalse(GlueViewDdlBuilder.isIcebergTable(table));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIcebergReadExpressionEscapesSingleQuotes() {
|
||||
assertEquals("iceberg_scan('s3://bucket/it''s-a-table/metadata/x.json')",
|
||||
GlueViewDdlBuilder.icebergReadExpression("s3://bucket/it's-a-table/metadata/x.json"));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user