diff --git a/docs/services/athena.md b/docs/services/athena.md index 95177201c7..8775cf942c 100644 --- a/docs/services/athena.md +++ b/docs/services/athena.md @@ -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('')`, 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 | |---|---| diff --git a/docs/services/glue.md b/docs/services/glue.md index e11bb7f0a0..064068751f 100644 --- a/docs/services/glue.md +++ b/docs/services/glue.md @@ -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 | |---|---| diff --git a/src/main/java/io/github/hectorvent/floci/services/athena/GlueViewDdlBuilder.java b/src/main/java/io/github/hectorvent/floci/services/athena/GlueViewDdlBuilder.java index 0cf84cbeb0..21dd7da1ed 100644 --- a/src/main/java/io/github/hectorvent/floci/services/athena/GlueViewDdlBuilder.java +++ b/src/main/java/io/github/hectorvent/floci/services/athena/GlueViewDdlBuilder.java @@ -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 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 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
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
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
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); } diff --git a/src/test/java/io/github/hectorvent/floci/services/athena/GlueViewDdlBuilderTest.java b/src/test/java/io/github/hectorvent/floci/services/athena/GlueViewDdlBuilderTest.java index e9978de508..48e88ec356 100644 --- a/src/test/java/io/github/hectorvent/floci/services/athena/GlueViewDdlBuilderTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/athena/GlueViewDdlBuilderTest.java @@ -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")); + } }