diff --git a/docs/services/athena.md b/docs/services/athena.md index 35204438be..4a86d462d5 100644 --- a/docs/services/athena.md +++ b/docs/services/athena.md @@ -178,6 +178,16 @@ Athena manages Iceberg tables through AWS Glue's Iceberg REST catalog, which Flo `CREATE TABLE AS` with `table_type = 'ICEBERG'` and `OPTIMIZE` are not supported yet. +### S3 Tables catalogs + +A table bucket integrated with the Glue Data Catalog (see [Glue's catalogs and Amazon S3 Tables](glue.md#catalogs-and-amazon-s3-tables)) is the catalog `s3tablescatalog/`, with its namespaces as databases. With that catalog in the query's `QueryExecutionContext` (`{"Catalog": "s3tablescatalog/", "Database": ""}`), or named in the query (`"s3tablescatalog/"..`): + +- DDL statements run in the context catalog, naming a table `[namespace.]table` as Athena's do. `CREATE DATABASE` creates a namespace, and `CREATE TABLE ... TBLPROPERTIES ('table_type'='iceberg')` an Iceberg table in the bucket; it names no `LOCATION`, since S3 Tables decides where the table lives. +- `SELECT`, `INSERT INTO`, `UPDATE`, `DELETE FROM` and `MERGE INTO` run in the query engine, which attaches each S3 Tables catalog the query names under that name, through Glue's Iceberg REST endpoint with a token for the calling account. A context catalog's namespace resolves names given without one. With no `Database`, the context database is Athena's `default`, so only the names the query qualifies resolve, unless the bucket has a `default` namespace. A write naming `awsdatacatalog..
` writes the default catalog's Iceberg table. +- `DROP TABLE`, in the context catalog, deletes the table, data and all. + +As on Athena, `OPTIMIZE` and `VACUUM` are refused (S3 manages compaction and snapshots), and so are Hive DDL statements. `CREATE TABLE AS` into an S3 Tables catalog is not supported yet. + ## Configuration | Property | Default | Description | diff --git a/src/main/java/io/floci/aws/services/athena/AthenaHiveDdl.java b/src/main/java/io/floci/aws/services/athena/AthenaHiveDdl.java index d5b7b17b32..67aad0ec84 100644 --- a/src/main/java/io/floci/aws/services/athena/AthenaHiveDdl.java +++ b/src/main/java/io/floci/aws/services/athena/AthenaHiveDdl.java @@ -17,7 +17,8 @@ import java.util.Set; * Parses the Hive DDL statements Athena runs against the Glue Data Catalog rather than against * data: {@code CREATE EXTERNAL TABLE}, {@code DROP TABLE}, {@code ALTER TABLE ... ADD|DROP * PARTITION}, {@code MSCK REPAIR TABLE} and {@code SHOW PARTITIONS}, and the Iceberg {@code CREATE TABLE ... - * TBLPROPERTIES ('table_type'='ICEBERG')} and {@code VACUUM}, which Floci runs against Glue's Iceberg catalog. + * TBLPROPERTIES ('table_type'='ICEBERG')}, {@code VACUUM} and {@code OPTIMIZE}, which Floci runs against Glue's Iceberg + * catalog. A table is named {@code t} or {@code db.t}, its catalog being the query's context catalog. * {@link #parse} answers null for every other statement, {@code CREATE TABLE AS} included, so those keep going to * the query engine. * @@ -27,7 +28,7 @@ import java.util.Set; final class AthenaHiveDdl { sealed interface Statement permits CreateTable, DropTable, AddPartitions, DropPartitions, RepairTable, - ShowPartitions, CreateIcebergTable, Vacuum { + ShowPartitions, CreateIcebergTable, Vacuum, Optimize { TableRef ref(); } @@ -67,6 +68,10 @@ final class AthenaHiveDdl { record Vacuum(TableRef ref) implements Statement { } + /** {@code OPTIMIZE ... REWRITE DATA USING BIN_PACK}: compacts an Iceberg table's data files. */ + record Optimize(TableRef ref) implements Statement { + } + private record Format(String inputFormat, String outputFormat, String serde) { } @@ -130,6 +135,12 @@ final class AthenaHiveDdl { if (acceptWords("VACUUM")) { return finish(new Vacuum(tableRef())); } + if (acceptWords("OPTIMIZE")) { + // Its REWRITE DATA USING BIN_PACK clause and filter are not read: no table this runs on compacts. + Optimize optimize = new Optimize(tableRef()); + position = tokens.size(); + return optimize; + } if (acceptWords("MSCK", "REPAIR", "TABLE")) { return finish(new RepairTable(tableRef())); } diff --git a/src/main/java/io/floci/aws/services/athena/AthenaHiveDdlExecutor.java b/src/main/java/io/floci/aws/services/athena/AthenaHiveDdlExecutor.java index 9c2bc64906..06facdf9bf 100644 --- a/src/main/java/io/floci/aws/services/athena/AthenaHiveDdlExecutor.java +++ b/src/main/java/io/floci/aws/services/athena/AthenaHiveDdlExecutor.java @@ -49,8 +49,35 @@ final class AthenaHiveDdlExecutor { * each, and no rows for every other statement. */ List execute(AthenaHiveDdl.Statement statement, String contextDatabase) { + return execute(statement, AthenaService.DEFAULT_CATALOG, contextDatabase); + } + + /** + * Runs {@code statement} in the context catalog {@code contextCatalog}. In an S3 Tables catalog + * ({@code s3tablescatalog/}), which holds Iceberg tables only, a {@code CREATE TABLE} creates one in the + * table bucket and {@code DROP TABLE} deletes it; Hive DDL, {@code OPTIMIZE} and {@code VACUUM} are refused, as on + * Athena. + */ + List execute(AthenaHiveDdl.Statement statement, String contextCatalog, String contextDatabase) { String database = statement.ref().database() != null ? statement.ref().database() : contextDatabase; String table = statement.ref().table(); + String bucket = AthenaIcebergStatements.s3TablesBucket(contextCatalog); + if (bucket != null) { + return switch (statement) { + case AthenaHiveDdl.CreateIcebergTable create -> { + icebergStatements.createTable(AthenaIcebergStatements.restCatalog(bucket), database, create); + yield List.of(); + } + case AthenaHiveDdl.DropTable drop -> { + icebergStatements.dropS3Table(bucket, database, table, drop.ifExists()); + yield List.of(); + } + case AthenaHiveDdl.Vacuum vacuum -> throw maintainedByS3(); + case AthenaHiveDdl.Optimize optimize -> throw maintainedByS3(); + default -> throw new AwsException("InvalidRequestException", "Catalog " + contextCatalog + + " holds Iceberg tables only; this statement is not supported in it", 400); + }; + } return switch (statement) { case AthenaHiveDdl.CreateTable create -> { createTable(database, create); @@ -79,9 +106,20 @@ final class AthenaHiveDdlExecutor { } case AthenaHiveDdl.Vacuum vacuum -> throw new IllegalStateException("VACUUM runs on the query engine, not against the catalog alone"); + case AthenaHiveDdl.Optimize optimize -> + throw new AwsException("InvalidRequestException", "OPTIMIZE is not supported yet", 400); }; } + /** + * Athena's refusal of {@code OPTIMIZE} and {@code VACUUM} on S3 Tables, whose compaction and snapshots S3 + * manages. + */ + private static AwsException maintainedByS3() { + return new AwsException("InvalidRequestException", + "OPTIMIZE and VACUUM are not supported on S3 Tables: S3 manages their compaction and snapshots", 400); + } + private void createTable(String database, AthenaHiveDdl.CreateTable create) { create.table().setDatabaseName(database); try { diff --git a/src/main/java/io/floci/aws/services/athena/AthenaIcebergStatements.java b/src/main/java/io/floci/aws/services/athena/AthenaIcebergStatements.java index 69dd6180d2..01ac8814eb 100644 --- a/src/main/java/io/floci/aws/services/athena/AthenaIcebergStatements.java +++ b/src/main/java/io/floci/aws/services/athena/AthenaIcebergStatements.java @@ -26,6 +26,7 @@ import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; @@ -68,6 +69,8 @@ public class AthenaIcebergStatements { private static final Pattern DML = Pattern.compile("^(?:INSERT\\s+INTO|MERGE\\s+INTO|DELETE\\s+FROM|UPDATE)\\s+", Pattern.CASE_INSENSITIVE); private static final Pattern S3_URI = Pattern.compile("^s3[an]?://([^/]+)/(.*)$"); + private static final String S3_TABLES_CATALOG_NAME = "s3tablescatalog"; + private static final Pattern S3_TABLES_CATALOG = Pattern.compile("(?i)^s3tablescatalog/([a-z0-9][a-z0-9-]*)$"); private final GlueIcebergCatalog catalog; private final GlueService glue; @@ -103,10 +106,23 @@ public class AthenaIcebergStatements { // ─── CREATE TABLE ───────────────────────────────────────────────────────────── - /** Creates the Iceberg table {@code create} describes in {@code database}, with no data. */ + /** Creates the Iceberg table {@code create} describes in {@code database} of the default catalog, with no data. */ void createTable(String database, AthenaHiveDdl.CreateIcebergTable create) { + createTable(DEFAULT_CATALOG, database, create); + } + + /** + * Creates the Iceberg table {@code create} describes in {@code database} of {@code restCatalog}, the catalog as + * Glue's Iceberg REST endpoint names it: the default catalog, or a table bucket of the federated S3 Tables catalog + * ({@code s3tablescatalog:}), where S3 Tables decides the table's location. + */ + void createTable(String restCatalog, String database, AthenaHiveDdl.CreateIcebergTable create) { + if (!DEFAULT_CATALOG.equals(restCatalog) && create.location() != null) { + throw invalid("S3 Tables manage their own storage locations: a CREATE TABLE in an S3 Tables catalog names " + + "no LOCATION"); + } String table = create.ref().table(); - if (create.ifNotExists() && findTable(database, table) != null) { + if (DEFAULT_CATALOG.equals(restCatalog) && create.ifNotExists() && findTable(database, table) != null) { return; } Map properties = new HashMap<>(); @@ -131,7 +147,7 @@ public class AthenaIcebergStatements { throw invalid(e.getMessage()); } try { - catalog.createTable(DEFAULT_CATALOG, database, request); + catalog.createTable(restCatalog, database, request); } catch (IcebergRestException e) { if (create.ifNotExists() && "AlreadyExistsException".equals(e.type())) { return; @@ -154,6 +170,121 @@ public class AthenaIcebergStatements { } } + // ─── S3 Tables catalogs ─────────────────────────────────────────────────────── + + /** + * The table bucket an Athena catalog name ({@code s3tablescatalog/}) names, or null for any other catalog: + * Athena queries a table bucket integrated with the Glue Data Catalog under that name. + */ + static String s3TablesBucket(String catalogName) { + if (catalogName == null) { + return null; + } + Matcher matcher = S3_TABLES_CATALOG.matcher(catalogName); + return matcher.matches() ? matcher.group(1).toLowerCase(Locale.ROOT) : null; + } + + /** The catalog Glue's Iceberg REST endpoint answers for a table bucket of the caller's federated S3 Tables catalog. */ + static String restCatalog(String bucket) { + return S3_TABLES_CATALOG_NAME + ":" + bucket; + } + + /** {@code CREATE DATABASE} in an S3 Tables catalog: a namespace of its table bucket. */ + void createNamespace(String bucket, String name, boolean ifNotExists) { + try { + catalog.createNamespace(restCatalog(bucket), mapper.createObjectNode().set("namespace", + mapper.createArrayNode().add(name))); + } catch (IcebergRestException e) { + if (ifNotExists && "AlreadyExistsException".equals(e.type())) { + return; + } + throw invalid(e.getMessage()); + } + } + + /** {@code DROP TABLE} in an S3 Tables catalog: S3 Tables deletes the table, data and all. */ + void dropS3Table(String bucket, String namespace, String table, boolean ifExists) { + try { + catalog.dropTable(restCatalog(bucket), namespace, table); + } catch (IcebergRestException e) { + if (ifExists && ("NoSuchTableException".equals(e.type()) || "NoSuchNamespaceException".equals(e.type()))) { + return; + } + throw invalid(e.getMessage()); + } + } + + /** + * The query engine's attachments of the S3 Tables catalogs a query reads or writes: its context catalog, when that + * is one, and every {@code "s3tablescatalog/"} it names. Each is attached under its own name, through Glue's + * Iceberg REST endpoint with the warehouse {@code :s3tablescatalog/}, so the query runs as written; + * with a context catalog whose namespace exists, the search path resolves unqualified names in it. The token goes + * once the query ends. + */ + record S3TablesAttachment(String attachSql, String searchPathSql, String token) { + } + + /** The attachments {@code query} needs, or null when it names no S3 Tables catalog. */ + S3TablesAttachment s3TablesAttachment(String query, String contextCatalog, String contextDatabase) { + Set buckets = new LinkedHashSet<>(); + String contextBucket = s3TablesBucket(contextCatalog); + if (contextBucket != null) { + buckets.add(contextBucket); + } + // A catalog only a comment or a string literal holds is no reference. + for (List name : GlueViewDdlBuilder.references(query)) { + String bucket = name.size() > 1 ? s3TablesBucket(name.getFirst()) : null; + if (bucket != null) { + buckets.add(bucket); + } + } + if (buckets.isEmpty()) { + return null; + } + String accountId = regionResolver.getAccountId(); + String token = tokens.mint(accountId, regionResolver.getRegion(), TOKEN_LIFETIME); + StringBuilder attachSql = new StringBuilder("INSTALL iceberg; LOAD iceberg;\n"); + for (String bucket : buckets) { + attachSql.append(attach(accountId + ":" + S3_TABLES_CATALOG_NAME + "/" + bucket, + GlueViewDdlBuilder.quote(S3_TABLES_CATALOG_NAME + "/" + bucket), token)); + } + String searchPath = contextBucket == null || !hasNamespace(contextBucket, contextDatabase) ? "" + : "SET search_path = " + literal(GlueViewDdlBuilder.quote(S3_TABLES_CATALOG_NAME + "/" + contextBucket) + + "." + GlueViewDdlBuilder.quote(contextDatabase) + ",memory.main") + ";\n"; + return new S3TablesAttachment(attachSql.toString(), searchPath, token); + } + + /** + * Whether the table bucket has the namespace: the engine refuses a search path naming one it does not, and a query + * whose context database is the {@code default} Athena gives one naming none still runs on the names it qualifies. + */ + private boolean hasNamespace(String bucket, String namespace) { + try { + catalog.loadNamespace(restCatalog(bucket), namespace); + return true; + } catch (IcebergRestException e) { + if ("NoSuchNamespaceException".equals(e.type())) { + return false; + } + throw e; + } + } + + /** + * The query engine's attachment of Glue's Iceberg REST endpoint, as {@code alias}, for the catalog + * {@code warehouse} names, with a catalog token, its S3 reads and writes going through the engine's own credentials. + */ + private String attach(String warehouse, String alias, String token) { + return "ATTACH " + literal(warehouse) + " AS " + alias + " (TYPE iceberg, ENDPOINT " + + literal(containerEndpoint.baseUrl() + "/iceberg") + ", AUTHORIZATION_TYPE 'oauth2', TOKEN " + + literal(token) + ", ACCESS_DELEGATION_MODE 'none');\n"; + } + + /** Gives up the catalog token of an S3 Tables attachment once its query has ended. */ + void finished(S3TablesAttachment attachment) { + tokens.revoke(attachment.token()); + } + // ─── INSERT / UPDATE / DELETE / MERGE ───────────────────────────────────────── /** @@ -166,12 +297,20 @@ public class AthenaIcebergStatements { /** * {@code query} rewritten to write its Iceberg target through the attached catalog, or null when it is not an - * {@code INSERT INTO}, {@code UPDATE}, {@code DELETE FROM} or {@code MERGE INTO} of an Iceberg table; a target - * named without a database is in {@code contextDatabase}. + * {@code INSERT INTO}, {@code UPDATE}, {@code DELETE FROM} or {@code MERGE INTO} of an Iceberg table of the + * default catalog; a target named without a database is in {@code contextDatabase}. */ IcebergWrite write(String query, String contextDatabase) { + return write(query, AthenaService.DEFAULT_CATALOG, contextDatabase); + } + + /** + * As {@link #write(String, String)}, in the context catalog {@code contextCatalog}: in an S3 Tables catalog, only a + * target naming the default catalog ({@code awsdatacatalog.db.t}) is one, a name giving none being the context's. + */ + IcebergWrite write(String query, String contextCatalog, String contextDatabase) { Target target = target(query); - if (target == null) { + if (target == null || s3TablesBucket(contextCatalog) != null && !target.catalogNamed()) { return null; } String database = target.database() != null ? target.database() : contextDatabase; @@ -184,9 +323,7 @@ public class AthenaIcebergStatements { Lock lock = tableLock(database, target.table()).readLock(); lock.lock(); String token = tokens.mint(accountId, regionResolver.getRegion(), TOKEN_LIFETIME); - String setup = "INSTALL iceberg; LOAD iceberg;\nATTACH " + literal(accountId) + " AS " + CATALOG_ALIAS - + " (TYPE iceberg, ENDPOINT " + literal(containerEndpoint.baseUrl() + "/iceberg") - + ", AUTHORIZATION_TYPE 'oauth2', TOKEN " + literal(token) + ", ACCESS_DELEGATION_MODE 'none');\n"; + String setup = "INSTALL iceberg; LOAD iceberg;\n" + attach(accountId, CATALOG_ALIAS, token); String rewritten = query.substring(0, target.start()) + CATALOG_ALIAS + "." + GlueViewDdlBuilder.quote(database) + "." + GlueViewDdlBuilder.quote(target.table()) + query.substring(target.end()); @@ -212,8 +349,8 @@ public class AthenaIcebergStatements { + database + "/" + table, key -> new ReentrantReadWriteLock()); } - /** The table a statement writes, and where its name sits in the statement. */ - record Target(String database, String table, int start, int end) { + /** The table a statement writes, whether its name gives its catalog, and where its name sits in the statement. */ + record Target(String database, String table, boolean catalogNamed, int start, int end) { } /** @@ -249,10 +386,10 @@ public class AthenaIcebergStatements { } } return switch (parts.size()) { - case 1 -> new Target(null, parts.get(0), nameStart, nameEnd); - case 2 -> new Target(parts.get(0), parts.get(1), nameStart, nameEnd); + case 1 -> new Target(null, parts.get(0), false, nameStart, nameEnd); + case 2 -> new Target(parts.get(0), parts.get(1), false, nameStart, nameEnd); case 3 -> DEFAULT_DATA_CATALOG.equals(parts.get(0)) - ? new Target(parts.get(1), parts.get(2), nameStart, nameEnd) : null; + ? new Target(parts.get(1), parts.get(2), true, nameStart, nameEnd) : null; default -> null; }; } diff --git a/src/main/java/io/floci/aws/services/athena/AthenaService.java b/src/main/java/io/floci/aws/services/athena/AthenaService.java index b77fdcaec4..7832d956d9 100644 --- a/src/main/java/io/floci/aws/services/athena/AthenaService.java +++ b/src/main/java/io/floci/aws/services/athena/AthenaService.java @@ -163,8 +163,11 @@ public class AthenaService { } catch (AwsException e) { invalidHiveDdl = e; } - // VACUUM reads the table's manifests, so it runs on the query engine like a query. - AthenaHiveDdl.Vacuum vacuum = hiveDdl instanceof AthenaHiveDdl.Vacuum statement ? statement : null; + String s3TablesBucket = AthenaIcebergStatements.s3TablesBucket(resolvedContext.getCatalog()); + // VACUUM reads the table's manifests, so it runs on the query engine like a query; in an S3 Tables catalog + // the executor refuses it at once. + AthenaHiveDdl.Vacuum vacuum = hiveDdl instanceof AthenaHiveDdl.Vacuum statement && s3TablesBucket == null + ? statement : null; boolean hiveDdlStatement = (hiveDdl != null && vacuum == null) || invalidHiveDdl != null; // AWS reports the result CSV object itself as the OutputLocation, not a // directory prefix — the same key is written and returned to the client. @@ -188,7 +191,7 @@ public class AthenaService { if (invalidHiveDdl != null) { throw invalidHiveDdl; } - List rows = hiveDdlExecutor.execute(hiveDdl, database); + List rows = hiveDdlExecutor.execute(hiveDdl, resolvedContext.getCatalog(), database); if (outputLocation != null) { writeSingleColumnResult(id, outputLocation, "partition", rows); } @@ -205,7 +208,13 @@ public class AthenaService { if (createDatabaseDdl == null) { throw new AwsException("InvalidRequestException", "Invalid CREATE DATABASE statement", 400); } - createGlueDatabase(createDatabaseDdl); + if (s3TablesBucket != null) { + // In an S3 Tables catalog a database is a namespace of the table bucket. + icebergStatements.createNamespace(s3TablesBucket, createDatabaseDdl.name(), + createDatabaseDdl.ifNotExists()); + } else { + createGlueDatabase(createDatabaseDdl); + } markSucceeded(id, execution); } catch (Exception e) { markFailed(id, execution, e); @@ -237,11 +246,17 @@ public class AthenaService { List
projectionTables = tablesForProjectionCheck(database); PartitionProjection.assertLocationTemplatesComplete(query, projectionTables); PartitionProjection.assertInjectedColumnsFiltered(query, projectionTables); - // A write to an Iceberg table goes through the engine's attachment of Glue's Iceberg catalog. - AthenaIcebergStatements.IcebergWrite icebergWrite = icebergStatements.write(query, database); + // S3 Tables catalogs the query names are attached under their own names; a write to an Iceberg + // table of the default catalog goes through the engine's attachment of Glue's Iceberg catalog. + AthenaIcebergStatements.S3TablesAttachment s3Tables = icebergStatements.s3TablesAttachment(query, + resolvedContext.getCatalog(), database); + AthenaIcebergStatements.IcebergWrite icebergWrite = null; try { - String setupDdl = (icebergWrite != null ? icebergWrite.setupSql() : "") - + TrinoSqlCompatibility.FUNCTION_MACROS + ddlBuilder.build(database, query); + icebergWrite = icebergStatements.write(query, resolvedContext.getCatalog(), database); + String setupDdl = (s3Tables != null ? s3Tables.attachSql() : "") + + (icebergWrite != null ? icebergWrite.setupSql() : "") + + TrinoSqlCompatibility.FUNCTION_MACROS + ddlBuilder.build(database, query) + + (s3Tables != null ? s3Tables.searchPathSql() : ""); String duckQuery = TrinoSqlCompatibility.translate( icebergWrite != null ? icebergWrite.query() : query); if (outputLocation != null) { @@ -255,6 +270,9 @@ public class AthenaService { if (icebergWrite != null) { icebergStatements.finished(icebergWrite); } + if (s3Tables != null) { + icebergStatements.finished(s3Tables); + } } return null; }) diff --git a/src/main/java/io/floci/aws/services/glue/iceberg/GlueIcebergCatalog.java b/src/main/java/io/floci/aws/services/glue/iceberg/GlueIcebergCatalog.java index 9162d9de44..e2fd6ebba5 100644 --- a/src/main/java/io/floci/aws/services/glue/iceberg/GlueIcebergCatalog.java +++ b/src/main/java/io/floci/aws/services/glue/iceberg/GlueIcebergCatalog.java @@ -127,7 +127,7 @@ public class GlueIcebergCatalog { return result; } - ObjectNode createNamespace(String catalog, JsonNode request) { + public ObjectNode createNamespace(String catalog, JsonNode request) { IcebergCatalogStore store = store(catalog); JsonNode levels = request.path("namespace"); if (!levels.isArray() || levels.size() != 1) { @@ -141,7 +141,7 @@ public class GlueIcebergCatalog { return result; } - ObjectNode loadNamespace(String catalog, String namespace) { + public ObjectNode loadNamespace(String catalog, String namespace) { IcebergCatalogStore store = store(catalog); String name = namespace(namespace); Map properties = store.namespaceProperties(name); @@ -333,7 +333,7 @@ public class GlueIcebergCatalog { * table's storage alone whether or not the client asked for a purge; an S3 Tables table's warehouse, its data and * metadata, goes with it, as S3 Tables' DeleteTable deletes it. */ - void dropTable(String catalog, String namespace, String name) { + public void dropTable(String catalog, String namespace, String name) { IcebergCatalogStore store = store(catalog); String ns = namespace(namespace); store.namespaceProperties(ns); diff --git a/src/test/java/io/floci/aws/services/athena/AthenaHiveDdlExecutorTest.java b/src/test/java/io/floci/aws/services/athena/AthenaHiveDdlExecutorTest.java index 3597dab9c7..3b0fcfd323 100644 --- a/src/test/java/io/floci/aws/services/athena/AthenaHiveDdlExecutorTest.java +++ b/src/test/java/io/floci/aws/services/athena/AthenaHiveDdlExecutorTest.java @@ -14,7 +14,9 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class AthenaHiveDdlExecutorTest { @@ -35,6 +37,27 @@ class AthenaHiveDdlExecutorTest { assertEquals("EntityNotFoundException", e.getErrorCode()); } + /** + * In an S3 Tables context catalog, DROP TABLE deletes the bucket's table and OPTIMIZE is refused as VACUUM is; in + * the default catalog, OPTIMIZE is not supported yet. + */ + @Test + void optimizeIsRefusedInAnS3TablesCatalogAndNotSupportedYetInTheDefaultOne() { + AthenaIcebergStatements iceberg = Mockito.mock(AthenaIcebergStatements.class); + AthenaHiveDdlExecutor executor = new AthenaHiveDdlExecutor(Mockito.mock(GlueService.class), + Mockito.mock(S3Service.class), iceberg); + + executor.execute(AthenaHiveDdl.parse("DROP TABLE orders"), "s3tablescatalog/lake", "sales"); + verify(iceberg).dropS3Table("lake", "sales", "orders", false); + AwsException optimize = assertThrows(AwsException.class, () -> executor.execute( + AthenaHiveDdl.parse("OPTIMIZE orders REWRITE DATA USING BIN_PACK"), "s3tablescatalog/lake", "sales")); + assertTrue(optimize.getMessage().contains("not supported on S3 Tables"), optimize.getMessage()); + + AwsException unsupported = assertThrows(AwsException.class, () -> executor.execute( + AthenaHiveDdl.parse("OPTIMIZE lake.events REWRITE DATA USING BIN_PACK"), "default")); + assertEquals("OPTIMIZE is not supported yet", unsupported.getMessage()); + } + @Test void aFolderWithAnInvalidEscapeIsNotAPartitionFolder() { Column region = new Column(); diff --git a/src/test/java/io/floci/aws/services/athena/AthenaHiveDdlTest.java b/src/test/java/io/floci/aws/services/athena/AthenaHiveDdlTest.java index c759d35baa..68c02b6f5c 100644 --- a/src/test/java/io/floci/aws/services/athena/AthenaHiveDdlTest.java +++ b/src/test/java/io/floci/aws/services/athena/AthenaHiveDdlTest.java @@ -164,6 +164,14 @@ class AthenaHiveDdlTest { AthenaHiveDdl.parse("vacuum `_events`")).ref()); } + @Test + void optimizeNamesItsTableWhateverItsClauses() { + assertEquals(new AthenaHiveDdl.TableRef("lake", "events"), assertInstanceOf(AthenaHiveDdl.Optimize.class, + AthenaHiveDdl.parse("OPTIMIZE lake.events REWRITE DATA USING BIN_PACK WHERE id > 5")).ref()); + assertEquals(new AthenaHiveDdl.TableRef(null, "events"), assertInstanceOf(AthenaHiveDdl.Optimize.class, + AthenaHiveDdl.parse("optimize events rewrite data using bin_pack;")).ref()); + } + @Test void dropRepairAndShowNameTheirTable() { AthenaHiveDdl.DropTable drop = assertInstanceOf(AthenaHiveDdl.DropTable.class, diff --git a/src/test/java/io/floci/aws/services/athena/AthenaIcebergSidecarIntegrationTest.java b/src/test/java/io/floci/aws/services/athena/AthenaIcebergSidecarIntegrationTest.java index 1c34bb4e7a..87ed1421dd 100644 --- a/src/test/java/io/floci/aws/services/athena/AthenaIcebergSidecarIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/athena/AthenaIcebergSidecarIntegrationTest.java @@ -1,6 +1,7 @@ package io.floci.aws.services.athena; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.RequestScopes; import io.floci.aws.core.storage.StorageFactory; @@ -9,11 +10,16 @@ import io.floci.aws.services.athena.model.QueryExecutionContext; import io.floci.aws.services.athena.model.QueryExecutionState; import io.floci.aws.services.athena.model.ResultConfiguration; import io.floci.aws.services.floci.duck.FlociDuckClient; +import io.floci.aws.services.glue.GlueCatalogService; import io.floci.aws.services.glue.GlueService; import io.floci.aws.services.glue.iceberg.GlueIcebergCatalog; import io.floci.aws.services.glue.model.Database; import io.floci.aws.services.glue.model.Table; import io.floci.aws.services.s3.S3Service; +import io.floci.aws.services.s3tables.S3TablesService; +import io.floci.aws.services.s3tables.model.Namespace; +import io.floci.aws.services.s3tables.model.S3Table; +import io.floci.aws.services.s3tables.model.TableBucket; import io.floci.aws.testing.SidecarContainersProfile; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.TestProfile; @@ -24,6 +30,7 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.List; @@ -76,6 +83,12 @@ class AthenaIcebergSidecarIntegrationTest { @Inject GlueIcebergCatalog catalog; + @Inject + S3TablesService s3Tables; + + @Inject + GlueCatalogService catalogs; + private AthenaService athena; private String bucket; private String database; @@ -174,28 +187,109 @@ class AthenaIcebergSidecarIntegrationTest { rows("SELECT id FROM events ORDER BY id")); } + @Test + void anS3TablesCatalogIsCreatedWrittenAndReadInItsOwnNameAndAsTheContext() throws Exception { + String tableBucket = "athena-s3t-" + System.nanoTime(); + String catalogName = "s3tablescatalog/" + tableBucket; + TableBucket created = RequestScopes.callAs(ACCOUNT, REGION, () -> { + TableBucket made = s3Tables.createTableBucket(tableBucket, null, null, Map.of(), REGION); + try { + catalogs.createCatalog("s3tablescatalog", new ObjectMapper().readTree( + "{\"FederatedCatalog\":{\"Identifier\":\"" + made.getArn() + + "\",\"ConnectionName\":\"aws:s3tables\"}}"), Map.of(), REGION); + } catch (IOException e) { + throw new IllegalStateException(e); + } + return made; + }); + try { + run(catalogName, null, "CREATE DATABASE sales"); + run(catalogName, "sales", "CREATE TABLE orders (id bigint, name string) " + + "TBLPROPERTIES ('table_type'='iceberg')"); + run(catalogName, "sales", "INSERT INTO orders VALUES (1, 'a'), (2, 'b')"); + run(null, database, "INSERT INTO \"" + catalogName + "\".sales.orders VALUES (3, 'c')"); + run(catalogName, "sales", "DELETE FROM orders WHERE id = 1"); + + assertEquals(List.of(row("id", "2", "name", "b"), row("id", "3", "name", "c")), + s3TablesRows(catalogName, "sales", "SELECT id, name FROM orders ORDER BY id")); + assertTrue(RequestScopes.callAs(ACCOUNT, REGION, () -> s3Tables.getTable(created.getArn(), "sales", + "orders", REGION)).getMetadataLocation().contains("/metadata/")); + // With no Database, Athena's context database is "default", which the bucket does not have. + run(catalogName, null, "SELECT count(*) FROM \"" + catalogName + "\".sales.orders"); + for (String maintenance : List.of("VACUUM orders", "OPTIMIZE orders REWRITE DATA USING BIN_PACK")) { + QueryExecution refused = execute(catalogName, "sales", maintenance); + assertEquals(QueryExecutionState.FAILED, refused.getStatus().getState(), maintenance); + assertTrue(refused.getStatus().getStateChangeReason().contains("not supported on S3 Tables"), + refused.getStatus().getStateChangeReason()); + } + + run(catalogName, "sales", "DROP TABLE orders"); + assertTrue(RequestScopes.callAs(ACCOUNT, REGION, + () -> s3Tables.listTables(created.getArn(), "sales", null, REGION)).isEmpty()); + } finally { + RequestScopes.runAs(ACCOUNT, REGION, () -> { + catalogs.deleteCatalog("s3tablescatalog", REGION); + for (Namespace namespace : s3Tables.listNamespaces(created.getArn(), null, REGION)) { + for (S3Table table : s3Tables.listTables(created.getArn(), namespace.getName(), null, REGION)) { + s3Tables.deleteTable(created.getArn(), namespace.getName(), table.getName(), REGION); + } + s3Tables.deleteNamespace(created.getArn(), namespace.getName(), REGION); + } + s3Tables.deleteTableBucket(created.getArn(), REGION); + }); + } + } + private void run(String sql) { - QueryExecutionContext context = new QueryExecutionContext(); - context.setDatabase(database); - String id = RequestScopes.callAs(ACCOUNT, REGION, () -> athena.startQueryExecution(sql, "primary", context, - new ResultConfiguration("s3://" + bucket + "/results/"))); - QueryExecution execution = await().atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofMillis(100)) - .until(() -> RequestScopes.callAs(ACCOUNT, REGION, () -> athena.getQueryExecution(id)), - found -> found.getStatus().getState() != QueryExecutionState.RUNNING - && found.getStatus().getState() != QueryExecutionState.QUEUED); + run(null, database, sql); + } + + /** Runs {@code sql} in the context catalog and database, failing the test unless it succeeds. */ + private void run(String catalogName, String contextDatabase, String sql) { + QueryExecution execution = execute(catalogName, contextDatabase, sql); if (execution.getStatus().getState() != QueryExecutionState.SUCCEEDED) { fail(sql + " -> " + execution.getStatus().getState() + ": " + execution.getStatus().getStateChangeReason()); } } + private QueryExecution execute(String catalogName, String contextDatabase, String sql) { + QueryExecutionContext context = new QueryExecutionContext(); + context.setCatalog(catalogName); + context.setDatabase(contextDatabase); + String id = RequestScopes.callAs(ACCOUNT, REGION, () -> athena.startQueryExecution(sql, "primary", context, + new ResultConfiguration("s3://" + bucket + "/results/"))); + return await().atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofMillis(100)) + .until(() -> RequestScopes.callAs(ACCOUNT, REGION, () -> athena.getQueryExecution(id)), + found -> found.getStatus().getState() != QueryExecutionState.RUNNING + && found.getStatus().getState() != QueryExecutionState.QUEUED); + } + + /** The rows of {@code sql} read in an S3 Tables context catalog, through the attachment Athena gives a query. */ + private List> s3TablesRows(String catalogName, String contextDatabase, String sql) { + return rowsOf(RequestScopes.callAs(ACCOUNT, REGION, () -> { + AthenaIcebergStatements.S3TablesAttachment attachment = icebergStatements.s3TablesAttachment(sql, + catalogName, contextDatabase); + try { + return duck.query(TrinoSqlCompatibility.translate(sql), attachment.attachSql() + + TrinoSqlCompatibility.FUNCTION_MACROS + attachment.searchPathSql(), ACCOUNT); + } finally { + icebergStatements.finished(attachment); + } + })); + } + private List> rows(String sql) { - return RequestScopes.callAs(ACCOUNT, REGION, () -> duck.query(TrinoSqlCompatibility.translate(sql), - TrinoSqlCompatibility.FUNCTION_MACROS + ddlBuilder.build(database, sql), ACCOUNT)).stream() - .map(found -> { - Map row = new TreeMap<>(); - found.forEach((column, value) -> row.put(column, String.valueOf(value))); - return row; - }).toList(); + return rowsOf(RequestScopes.callAs(ACCOUNT, REGION, () -> duck.query(TrinoSqlCompatibility.translate(sql), + TrinoSqlCompatibility.FUNCTION_MACROS + ddlBuilder.build(database, sql), ACCOUNT))); + } + + /** The engine's rows, each column's value as its text, columns in name order. */ + private static List> rowsOf(List> found) { + return found.stream().map(columns -> { + Map row = new TreeMap<>(); + columns.forEach((column, value) -> row.put(column, String.valueOf(value))); + return row; + }).toList(); } private static Map row(String... columnsAndValues) { diff --git a/src/test/java/io/floci/aws/services/athena/AthenaIcebergStatementsTest.java b/src/test/java/io/floci/aws/services/athena/AthenaIcebergStatementsTest.java index c7399a3a92..39244091fc 100644 --- a/src/test/java/io/floci/aws/services/athena/AthenaIcebergStatementsTest.java +++ b/src/test/java/io/floci/aws/services/athena/AthenaIcebergStatementsTest.java @@ -10,11 +10,13 @@ import io.floci.aws.services.floci.duck.FlociDuckClient; import io.floci.aws.services.glue.GlueService; import io.floci.aws.services.glue.iceberg.GlueIcebergCatalog; import io.floci.aws.services.glue.iceberg.GlueIcebergTokens; +import io.floci.aws.services.glue.iceberg.IcebergRestException; import io.floci.aws.services.glue.model.Column; 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 io.floci.aws.testing.InlineMocks; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -95,12 +97,13 @@ class AthenaIcebergStatementsTest { assertEquals("ev\"ents", target.table()); assertEquals("Lake . \"Ev\"\"ents\"", insert.substring(target.start(), target.end())); - assertEquals(new AthenaIcebergStatements.Target(null, "events", 12, 18), + assertEquals(new AthenaIcebergStatements.Target(null, "events", false, 12, 18), AthenaIcebergStatements.target("DELETE FROM events WHERE id = 1")); AthenaIcebergStatements.Target merge = AthenaIcebergStatements.target( "MERGE INTO awsdatacatalog.lake.events AS t USING src s ON t.id = s.id WHEN MATCHED THEN DELETE"); assertEquals("lake", merge.database()); assertEquals("events", merge.table()); + assertTrue(merge.catalogNamed()); assertEquals("events", AthenaIcebergStatements.target("UPDATE events SET a = 1").table()); assertNull(AthenaIcebergStatements.target("UPDATE other_catalog.lake.events SET a = 1")); @@ -126,6 +129,24 @@ class AthenaIcebergStatementsTest { verify(tokens).revoke("tok'en"); } + /** + * In an S3 Tables context catalog, a write naming the default catalog goes through Glue's attachment, and one + * naming no catalog is the context's, which the S3 Tables attachment serves. + */ + @Test + void inAnS3TablesContextOnlyAWriteNamingTheDefaultCatalogGoesThroughGlue() { + glueTable("lake", "events", true); + when(tokens.mint(eq("111122223333"), eq("eu-west-1"), any())).thenReturn("tok"); + + assertNull(statements.write("INSERT INTO events VALUES (1)", "s3tablescatalog/bucket", "lake")); + assertNull(statements.write("INSERT INTO lake.events VALUES (1)", "s3tablescatalog/bucket", "sales")); + verify(tokens, never()).mint(anyString(), anyString(), any()); + AthenaIcebergStatements.IcebergWrite write = statements.write( + "INSERT INTO awsdatacatalog.lake.events SELECT * FROM orders", "s3tablescatalog/bucket", "sales"); + assertEquals("INSERT INTO glue_iceberg.\"lake\".\"events\" SELECT * FROM orders", write.query()); + statements.finished(write); + } + @Test void aWriteToAHiveTableOrAMissingOneIsLeftAlone() { glueTable("lake", "hive_events", false); @@ -137,6 +158,47 @@ class AthenaIcebergStatementsTest { verify(tokens, never()).mint(anyString(), anyString(), any()); } + @Test + void anS3TablesCatalogIsAttachedUnderItsOwnNameAndIsTheSearchPathAsTheContext() { + when(tokens.mint(eq("111122223333"), eq("eu-west-1"), any())).thenReturn("tok"); + assertEquals("lake", AthenaIcebergStatements.s3TablesBucket("S3TablesCatalog/lake")); + assertNull(AthenaIcebergStatements.s3TablesBucket("AwsDataCatalog")); + assertNull(statements.s3TablesAttachment("SELECT 1", "AwsDataCatalog", "default")); + + AthenaIcebergStatements.S3TablesAttachment attachment = statements.s3TablesAttachment( + "INSERT INTO \"s3tablescatalog/other\".ns.t SELECT * FROM orders", "s3tablescatalog/lake", "sales"); + + assertEquals("INSTALL iceberg; LOAD iceberg;\n" + + "ATTACH '111122223333:s3tablescatalog/lake' AS \"s3tablescatalog/lake\" (TYPE iceberg, ENDPOINT " + + "'http://floci:4566/iceberg', AUTHORIZATION_TYPE 'oauth2', TOKEN 'tok', ACCESS_DELEGATION_MODE 'none');\n" + + "ATTACH '111122223333:s3tablescatalog/other' AS \"s3tablescatalog/other\" (TYPE iceberg, ENDPOINT " + + "'http://floci:4566/iceberg', AUTHORIZATION_TYPE 'oauth2', TOKEN 'tok', ACCESS_DELEGATION_MODE 'none');\n", + attachment.attachSql()); + assertEquals("SET search_path = '\"s3tablescatalog/lake\".\"sales\",memory.main';\n", attachment.searchPathSql()); + statements.finished(attachment); + verify(tokens).revoke("tok"); + } + + /** + * A catalog only a comment or a string literal names is not attached, and a context namespace the bucket does + * not have (Athena's {@code default} for a query naming none) is not the search path, which the engine would + * refuse. + */ + @Test + void anS3TablesCatalogNamedOnlyInACommentOrLiteralIsNotAttachedNorAMissingNamespaceSearched() { + when(tokens.mint(eq("111122223333"), eq("eu-west-1"), any())).thenReturn("tok"); + assertNull(statements.s3TablesAttachment("SELECT '\"s3tablescatalog/a\".ns.t' -- \"s3tablescatalog/b\".ns.t\n" + + "/* \"s3tablescatalog/c\".ns.t */ FROM dual", "AwsDataCatalog", "default")); + + IcebergRestException missing = InlineMocks.inlineMock(IcebergRestException.class); + when(missing.type()).thenReturn("NoSuchNamespaceException"); + when(catalog.loadNamespace("s3tablescatalog:lake", "default")).thenThrow(missing); + AthenaIcebergStatements.S3TablesAttachment attachment = statements.s3TablesAttachment( + "SELECT * FROM \"s3tablescatalog/lake\".sales.orders", "s3tablescatalog/lake", "default"); + assertTrue(attachment.attachSql().contains("AS \"s3tablescatalog/lake\""), attachment.attachSql()); + assertEquals("", attachment.searchPathSql()); + } + // ─── CREATE TABLE ───────────────────────────────────────────────────────────── private static AthenaHiveDdl.CreateIcebergTable create(boolean ifNotExists, Map properties) {