feat(athena): query and write S3 Tables catalogs (s3tablescatalog/<bucket>) (#8549)

This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-16 00:59:49 -04:00
1 parent 0b6077d374
commit 35b03c6bf6
10 files changed
+444 -43

No files matched your search

@@ -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()));
}
@@ -49,8 +49,35 @@ final class AthenaHiveDdlExecutor {
* each, and no rows for every other statement.
*/
List<String> 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/<bucket>}), 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<String> 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 {
@@ -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:<bucket>}), 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<String, String> 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/<bucket>}) 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/<bucket>"} it names. Each is attached under its own name, through Glue's
* Iceberg REST endpoint with the warehouse {@code <account>:s3tablescatalog/<bucket>}, 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<String> 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<String> 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;
};
}
@@ -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<String> rows = hiveDdlExecutor.execute(hiveDdl, database);
List<String> 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<Table> 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;
})
@@ -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<String, String> 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);