diff --git a/docs/services/athena.md b/docs/services/athena.md
index 1e5ffc286e..7776a5cfb4 100644
--- a/docs/services/athena.md
+++ b/docs/services/athena.md
@@ -143,6 +143,18 @@ Not yet supported:
- A `date` or `timestamp` key with a `format` other than ISO is not parsed, so its objects are not read.
- The object path backs the template's values but is not exposed: Athena's `"$path"` pseudo-column cannot be selected.
+## Hive DDL
+
+Hive DDL runs against the Glue Data Catalog rather than the query engine, as it does on Athena, and its query reports `StatementType` `DDL`:
+
+- `CREATE EXTERNAL TABLE [IF NOT EXISTS]` creates the Glue table: its columns and `PARTITIONED BY` keys, `COMMENT`, `CLUSTERED BY ... INTO n BUCKETS`, `ROW FORMAT DELIMITED` (stored as the `LazySimpleSerDe` parameters Hive uses, `field.delim` and the rest) or `ROW FORMAT SERDE ... WITH SERDEPROPERTIES`, `STORED AS` (`TEXTFILE`, the default, `PARQUET`, `ORC`, `AVRO`, `SEQUENCEFILE`, `RCFILE`, `ION`, or `INPUTFORMAT ... OUTPUTFORMAT ...`), `LOCATION` and `TBLPROPERTIES`. Names are lower-cased and string literals take Hive's backslash escapes, so `FIELDS TERMINATED BY '\t'` stores a tab. `SORTED BY` is kept as the table's sort columns. Every format is registered, but Floci's query engine reads only Parquet, JSON and delimited text (see [Format inference](#format-inference)): an `ORC`, `AVRO`, `ION`, `RCFILE` or `SEQUENCEFILE` table serves other Glue clients, such as Spark on EMR, and Athena queries on it fail. A `CREATE TABLE` without `EXTERNAL` fails unless it creates an Iceberg table or is a `CREATE TABLE AS`, which go to the query engine.
+- `DROP TABLE [IF EXISTS]` removes a Hive table's metadata and leaves its data in S3. An Iceberg table is a managed table, so dropping it deletes the objects under its location too, as Athena does.
+- `ALTER TABLE ... ADD [IF NOT EXISTS] PARTITION (...) [LOCATION '...'] [PARTITION ...]` creates the partitions; one without a `LOCATION` is placed at `
/key=value/...`. `ALTER TABLE ... DROP [IF EXISTS] PARTITION (...)[, PARTITION ...]` deletes them. A partition specification has to name every partition key.
+- `MSCK REPAIR TABLE` lists the table's location and adds a partition for every Hive-style `key=value/...` folder path that holds an object and has none yet, with that folder, spelled as it is in S3, as the partition's location. A folder name with an invalid escape is skipped. Like Athena it only adds partitions, never removes them.
+- `SHOW PARTITIONS` returns one `partition` column, a `key=value[/key=value...]` row per partition, values escaped as Hive escapes folder names.
+
+Without `IF [NOT] EXISTS`, a table or partition that already exists, or does not, fails the query. Other `ALTER TABLE` statements are not supported.
+
## Configuration
| Property | Default | Description |
@@ -233,4 +245,6 @@ See [S3 Select](s3.md#s3-select) for details on execution modes and supported SQ
Set `FLOCI_SERVICES_ATHENA_MOCK=true` to skip DuckDB entirely for Athena. In this mode queries transition to `SUCCEEDED` immediately with an empty result set, useful for unit tests that only exercise the Athena state machine, not the query results.
+`CREATE DATABASE` and the [Hive DDL](#hive-ddl) statements still change the Glue catalog in mock mode, and `SHOW PARTITIONS` still returns its rows, since none of them needs the sidecar.
+
When mock mode is enabled the sidecar does **not** start. S3 Select will use the Java evaluator for CSV and JSON. Parquet queries will fail unless `FLOCI_SERVICES_DUCK_URL` points to an already-running floci-duck instance.
diff --git a/src/main/java/io/floci/aws/services/athena/AthenaHiveDdl.java b/src/main/java/io/floci/aws/services/athena/AthenaHiveDdl.java
new file mode 100644
index 0000000000..c1f9fa2f15
--- /dev/null
+++ b/src/main/java/io/floci/aws/services/athena/AthenaHiveDdl.java
@@ -0,0 +1,575 @@
+package io.floci.aws.services.athena;
+
+import io.floci.aws.core.common.AwsException;
+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 java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+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}. {@link #parse} answers null
+ * for every other statement, an Iceberg {@code CREATE TABLE} and {@code CREATE TABLE AS} included,
+ * so those keep going to the query engine.
+ *
+ * Names are lower-cased, as Athena stores them in Glue. String literals take Hive's backslash
+ * escapes, so {@code FIELDS TERMINATED BY '\t'} stores a tab.
+ */
+final class AthenaHiveDdl {
+
+ sealed interface Statement permits CreateTable, DropTable, AddPartitions, DropPartitions, RepairTable,
+ ShowPartitions {
+ TableRef ref();
+ }
+
+ /** A table name; {@code database} is null when the statement leaves it to the query context. */
+ record TableRef(String database, String table) {
+ }
+
+ record CreateTable(TableRef ref, boolean ifNotExists, Table table) implements Statement {
+ }
+
+ record DropTable(TableRef ref, boolean ifExists) implements Statement {
+ }
+
+ /** One partition: its key values in the order written, and its location when one is given. */
+ record PartitionSpec(Map values, String location) {
+ }
+
+ record AddPartitions(TableRef ref, boolean ifNotExists, List partitions) implements Statement {
+ }
+
+ record DropPartitions(TableRef ref, boolean ifExists, List partitions) implements Statement {
+ }
+
+ record RepairTable(TableRef ref) implements Statement {
+ }
+
+ record ShowPartitions(TableRef ref) implements Statement {
+ }
+
+ private record Format(String inputFormat, String outputFormat, String serde) {
+ }
+
+ private static final String LAZY_SIMPLE_SERDE = "org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe";
+ private static final Map FORMATS = Map.of(
+ "TEXTFILE", new Format("org.apache.hadoop.mapred.TextInputFormat",
+ "org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat", LAZY_SIMPLE_SERDE),
+ "SEQUENCEFILE", new Format("org.apache.hadoop.mapred.SequenceFileInputFormat",
+ "org.apache.hadoop.hive.ql.io.HiveSequenceFileOutputFormat", LAZY_SIMPLE_SERDE),
+ "RCFILE", new Format("org.apache.hadoop.hive.ql.io.RCFileInputFormat",
+ "org.apache.hadoop.hive.ql.io.RCFileOutputFormat",
+ "org.apache.hadoop.hive.serde2.columnar.LazyBinaryColumnarSerDe"),
+ "ORC", new Format("org.apache.hadoop.hive.ql.io.orc.OrcInputFormat",
+ "org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat", "org.apache.hadoop.hive.ql.io.orc.OrcSerde"),
+ "PARQUET", new Format("org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat",
+ "org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat",
+ "org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe"),
+ "AVRO", new Format("org.apache.hadoop.hive.ql.io.avro.AvroContainerInputFormat",
+ "org.apache.hadoop.hive.ql.io.avro.AvroContainerOutputFormat",
+ "org.apache.hadoop.hive.serde2.avro.AvroSerDe"),
+ "ION", new Format("com.amazon.ionhiveserde.formats.IonInputFormat",
+ "com.amazon.ionhiveserde.formats.IonOutputFormat", "com.amazon.ionhiveserde.IonHiveSerDe"));
+
+ /** Words that end a column type when they follow it at the top level. */
+ private static final Set TYPE_TERMINATORS = Set.of("COMMENT");
+
+ private final List tokens;
+ private int position;
+
+ private AthenaHiveDdl(List tokens) {
+ this.tokens = tokens;
+ }
+
+ /** The statement {@code sql} holds, or null when it is not one of the statements this class runs. */
+ static Statement parse(String sql) {
+ List tokens = tokenize(sql);
+ if (tokens.isEmpty()) {
+ return null;
+ }
+ return new AthenaHiveDdl(tokens).statement();
+ }
+
+ private Statement statement() {
+ if (acceptWords("CREATE", "EXTERNAL", "TABLE")) {
+ return finish(createTable());
+ }
+ if (peekWords("CREATE", "TABLE")) {
+ if (isIcebergOrCtas()) {
+ return null;
+ }
+ throw invalid("Athena creates a table without EXTERNAL only as an Iceberg table "
+ + "(TBLPROPERTIES ('table_type'='ICEBERG')); use CREATE EXTERNAL TABLE for a Hive table");
+ }
+ if (acceptWords("DROP", "TABLE")) {
+ boolean ifExists = acceptWords("IF", "EXISTS");
+ return finish(new DropTable(tableRef(), ifExists));
+ }
+ if (acceptWords("MSCK", "REPAIR", "TABLE")) {
+ return finish(new RepairTable(tableRef()));
+ }
+ if (acceptWords("SHOW", "PARTITIONS")) {
+ return finish(new ShowPartitions(tableRef()));
+ }
+ if (acceptWords("ALTER", "TABLE")) {
+ TableRef ref = tableRef();
+ if (acceptWords("ADD")) {
+ boolean ifNotExists = acceptWords("IF", "NOT", "EXISTS");
+ if (peekWords("PARTITION")) {
+ return finish(new AddPartitions(ref, ifNotExists, partitionSpecs(true)));
+ }
+ } else if (acceptWords("DROP")) {
+ boolean ifExists = acceptWords("IF", "EXISTS");
+ if (peekWords("PARTITION")) {
+ return finish(new DropPartitions(ref, ifExists, partitionSpecs(false)));
+ }
+ }
+ throw invalid("Floci runs ALTER TABLE ADD PARTITION and ALTER TABLE DROP PARTITION; "
+ + "other ALTER TABLE statements are not supported");
+ }
+ return null;
+ }
+
+ private Statement finish(Statement statement) {
+ accept(";");
+ if (position < tokens.size()) {
+ throw invalid("Unexpected '" + tokens.get(position).text() + "' in the statement");
+ }
+ return statement;
+ }
+
+ private boolean isIcebergOrCtas() {
+ for (int i = position; i < tokens.size(); i++) {
+ Token token = tokens.get(i);
+ Token following = i + 1 < tokens.size() ? tokens.get(i + 1) : null;
+ boolean query = following != null && (following.isWord("SELECT") || following.isWord("WITH")
+ || following.isWord("VALUES") || following.is("("));
+ if (token.isWord("AS") && query || token.isWord("WITH") && following != null && following.is("(")) {
+ return true;
+ }
+ if (token.kind() == Kind.STRING && "table_type".equalsIgnoreCase(token.text())
+ && i + 2 < tokens.size() && tokens.get(i + 1).is("=")
+ && "ICEBERG".equalsIgnoreCase(tokens.get(i + 2).text())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private CreateTable createTable() {
+ boolean ifNotExists = acceptWords("IF", "NOT", "EXISTS");
+ TableRef ref = tableRef();
+ Table table = new Table();
+ table.setName(ref.table());
+ table.setTableType("EXTERNAL_TABLE");
+ StorageDescriptor descriptor = new StorageDescriptor();
+ descriptor.setColumns(accept("(") ? columns() : new ArrayList<>());
+ descriptor.setCompressed(false);
+ descriptor.setNumberOfBuckets(-1);
+ descriptor.setStoredAsSubDirectories(false);
+ StorageDescriptor.SerDeInfo serde = new StorageDescriptor.SerDeInfo();
+ Map serdeParameters = new LinkedHashMap<>();
+ Map tableParameters = new LinkedHashMap<>();
+ List partitionKeys = new ArrayList<>();
+ String format = null;
+ boolean delimited = false;
+ while (position < tokens.size() && !tokens.get(position).is(";")) {
+ if (acceptWords("COMMENT")) {
+ table.setDescription(string());
+ } else if (acceptWords("PARTITIONED", "BY")) {
+ expect("(");
+ partitionKeys.addAll(columns());
+ } else if (acceptWords("CLUSTERED", "BY")) {
+ descriptor.setBucketColumns(identifierList());
+ if (acceptWords("SORTED", "BY")) {
+ descriptor.setSortColumns(sortColumns());
+ }
+ expectWords("INTO");
+ descriptor.setNumberOfBuckets(Integer.parseInt(next().text()));
+ expectWords("BUCKETS");
+ } else if (acceptWords("ROW", "FORMAT", "DELIMITED")) {
+ delimited = true;
+ delimiters(serdeParameters);
+ } else if (acceptWords("ROW", "FORMAT", "SERDE")) {
+ serde.setSerializationLibrary(string());
+ if (acceptWords("WITH", "SERDEPROPERTIES")) {
+ serdeParameters.putAll(properties());
+ }
+ } else if (acceptWords("STORED", "AS", "INPUTFORMAT")) {
+ descriptor.setInputFormat(string());
+ expectWords("OUTPUTFORMAT");
+ descriptor.setOutputFormat(string());
+ } else if (acceptWords("STORED", "AS")) {
+ format = next().text().toUpperCase(Locale.ROOT);
+ if (!FORMATS.containsKey(format)) {
+ throw invalid("Unsupported STORED AS format: " + format);
+ }
+ } else if (acceptWords("WITH", "SERDEPROPERTIES")) {
+ serdeParameters.putAll(properties());
+ } else if (acceptWords("LOCATION")) {
+ descriptor.setLocation(string());
+ } else if (acceptWords("TBLPROPERTIES")) {
+ tableParameters.putAll(properties());
+ } else {
+ throw invalid("Unexpected '" + tokens.get(position).text() + "' in CREATE EXTERNAL TABLE");
+ }
+ }
+ Format storage = FORMATS.get(format == null ? "TEXTFILE" : format);
+ if (descriptor.getInputFormat() == null) {
+ descriptor.setInputFormat(storage.inputFormat());
+ descriptor.setOutputFormat(storage.outputFormat());
+ }
+ if (serde.getSerializationLibrary() == null) {
+ serde.setSerializationLibrary(delimited ? LAZY_SIMPLE_SERDE : storage.serde());
+ }
+ if (LAZY_SIMPLE_SERDE.equals(serde.getSerializationLibrary())) {
+ serdeParameters.putIfAbsent("serialization.format", "1");
+ }
+ serde.setParameters(serdeParameters);
+ descriptor.setSerdeInfo(serde);
+ table.setStorageDescriptor(descriptor);
+ table.setPartitionKeys(partitionKeys);
+ tableParameters.put("EXTERNAL", "TRUE");
+ table.setParameters(tableParameters);
+ return new CreateTable(ref, ifNotExists, table);
+ }
+
+ /** The {@code ROW FORMAT DELIMITED} clauses, as the SerDe parameters Hive stores for them. */
+ private void delimiters(Map parameters) {
+ while (true) {
+ if (acceptWords("FIELDS", "TERMINATED", "BY")) {
+ String delimiter = string();
+ parameters.put("field.delim", delimiter);
+ parameters.put("serialization.format", delimiter);
+ if (acceptWords("ESCAPED", "BY")) {
+ parameters.put("escape.delim", string());
+ }
+ } else if (acceptWords("COLLECTION", "ITEMS", "TERMINATED", "BY")) {
+ // Hive's own spelling of the key.
+ parameters.put("colelction.delim", string());
+ } else if (acceptWords("MAP", "KEYS", "TERMINATED", "BY")) {
+ parameters.put("mapkey.delim", string());
+ } else if (acceptWords("LINES", "TERMINATED", "BY")) {
+ parameters.put("line.delim", string());
+ } else if (acceptWords("NULL", "DEFINED", "AS")) {
+ parameters.put("serialization.null.format", string());
+ } else {
+ return;
+ }
+ }
+ }
+
+ /** Column definitions up to and including the closing parenthesis. */
+ private List columns() {
+ List columns = new ArrayList<>();
+ do {
+ Column column = new Column();
+ column.setName(identifier());
+ column.setType(type());
+ if (acceptWords("COMMENT")) {
+ column.setComment(string());
+ }
+ columns.add(column);
+ } while (accept(","));
+ expect(")");
+ return columns;
+ }
+
+ /** A column type, written back lower-cased without spaces, as Glue stores it. */
+ private String type() {
+ StringBuilder type = new StringBuilder();
+ int depth = 0;
+ while (position < tokens.size()) {
+ Token token = tokens.get(position);
+ if (depth == 0 && (token.is(",") || token.is(")") || TYPE_TERMINATORS.contains(token.upper()))) {
+ break;
+ }
+ if (token.is("<") || token.is("(")) {
+ depth++;
+ } else if (token.is(">") || token.is(")")) {
+ depth--;
+ }
+ if (!type.isEmpty() && token.kind() == Kind.WORD && Character.isLetterOrDigit(type.charAt(type.length() - 1))) {
+ type.append(' ');
+ }
+ type.append(token.kind() == Kind.WORD ? token.text().toLowerCase(Locale.ROOT) : token.text());
+ position++;
+ }
+ if (type.isEmpty()) {
+ throw invalid("A column is missing its type");
+ }
+ return type.toString();
+ }
+
+ private List partitionSpecs(boolean withLocation) {
+ List specs = new ArrayList<>();
+ do {
+ expectWords("PARTITION");
+ expect("(");
+ Map values = new LinkedHashMap<>();
+ do {
+ String key = identifier();
+ expect("=");
+ Token value = next();
+ if (value.kind() != Kind.STRING && value.kind() != Kind.NUMBER) {
+ throw invalid("A partition value must be a literal, not '" + value.text() + "'");
+ }
+ values.put(key, value.text());
+ } while (accept(","));
+ expect(")");
+ String location = withLocation && acceptWords("LOCATION") ? string() : null;
+ specs.add(new PartitionSpec(values, location));
+ } while (accept(",") || peekWords("PARTITION"));
+ return specs;
+ }
+
+ private Map properties() {
+ expect("(");
+ Map properties = new LinkedHashMap<>();
+ do {
+ String key = string();
+ expect("=");
+ properties.put(key, string());
+ } while (accept(","));
+ expect(")");
+ return properties;
+ }
+
+ private List identifierList() {
+ expect("(");
+ List names = new ArrayList<>();
+ do {
+ names.add(identifier());
+ } while (accept(","));
+ expect(")");
+ return names;
+ }
+
+ /** {@code SORTED BY} columns as Glue stores them: 1 for ascending, the default, 0 for descending. */
+ private List sortColumns() {
+ expect("(");
+ List orders = new ArrayList<>();
+ do {
+ StorageDescriptor.Order order = new StorageDescriptor.Order();
+ order.setColumn(identifier());
+ order.setSortOrder(acceptWords("DESC") ? 0 : 1);
+ acceptWords("ASC");
+ orders.add(order);
+ } while (accept(","));
+ expect(")");
+ return orders;
+ }
+
+ private TableRef tableRef() {
+ String first = identifier();
+ if (accept(".")) {
+ return new TableRef(first, identifier());
+ }
+ return new TableRef(null, first);
+ }
+
+ private String identifier() {
+ Token token = next();
+ if (token.kind() != Kind.WORD && token.kind() != Kind.QUOTED) {
+ throw invalid("Expected a name but found '" + token.text() + "'");
+ }
+ return token.text().toLowerCase(Locale.ROOT);
+ }
+
+ private String string() {
+ Token token = next();
+ if (token.kind() != Kind.STRING) {
+ throw invalid("Expected a string literal but found '" + token.text() + "'");
+ }
+ return token.text();
+ }
+
+ private Token next() {
+ if (position >= tokens.size()) {
+ throw invalid("The statement ends early");
+ }
+ return tokens.get(position++);
+ }
+
+ private boolean accept(String symbol) {
+ if (position < tokens.size() && tokens.get(position).is(symbol)) {
+ position++;
+ return true;
+ }
+ return false;
+ }
+
+ private void expect(String symbol) {
+ if (!accept(symbol)) {
+ throw invalid("Expected '" + symbol + "'"
+ + (position < tokens.size() ? " but found '" + tokens.get(position).text() + "'" : " at the end"));
+ }
+ }
+
+ private boolean peekWords(String... words) {
+ if (position + words.length > tokens.size()) {
+ return false;
+ }
+ for (int i = 0; i < words.length; i++) {
+ if (!tokens.get(position + i).isWord(words[i])) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean acceptWords(String... words) {
+ if (!peekWords(words)) {
+ return false;
+ }
+ position += words.length;
+ return true;
+ }
+
+ private void expectWords(String... words) {
+ if (!acceptWords(words)) {
+ throw invalid("Expected " + String.join(" ", words)
+ + (position < tokens.size() ? " but found '" + tokens.get(position).text() + "'" : " at the end"));
+ }
+ }
+
+ private static AwsException invalid(String message) {
+ return new AwsException("InvalidRequestException", message, 400);
+ }
+
+ // ---- tokenizer ----
+
+ private enum Kind { WORD, QUOTED, STRING, NUMBER, SYMBOL }
+
+ private record Token(Kind kind, String text) {
+ boolean is(String symbol) {
+ return kind == Kind.SYMBOL && text.equals(symbol);
+ }
+
+ boolean isWord(String word) {
+ return kind == Kind.WORD && text.equalsIgnoreCase(word);
+ }
+
+ String upper() {
+ return kind == Kind.WORD ? text.toUpperCase(Locale.ROOT) : "";
+ }
+ }
+
+ private static List tokenize(String sql) {
+ List tokens = new ArrayList<>();
+ int i = 0;
+ int length = sql == null ? 0 : sql.length();
+ while (i < length) {
+ char c = sql.charAt(i);
+ if (Character.isWhitespace(c)) {
+ i++;
+ } else if (sql.startsWith("--", i)) {
+ int end = sql.indexOf('\n', i);
+ i = end < 0 ? length : end + 1;
+ } else if (sql.startsWith("/*", i)) {
+ int end = sql.indexOf("*/", i + 2);
+ i = end < 0 ? length : end + 2;
+ } else if (Character.isLetter(c) || c == '_') {
+ int start = i;
+ while (i < length && (Character.isLetterOrDigit(sql.charAt(i)) || sql.charAt(i) == '_'
+ || sql.charAt(i) == '$')) {
+ i++;
+ }
+ tokens.add(new Token(Kind.WORD, sql.substring(start, i)));
+ } else if (Character.isDigit(c)) {
+ int start = i;
+ while (i < length && (Character.isDigit(sql.charAt(i)) || sql.charAt(i) == '.')) {
+ i++;
+ }
+ tokens.add(new Token(Kind.NUMBER, sql.substring(start, i)));
+ } else if (c == '`') {
+ StringBuilder name = new StringBuilder();
+ i++;
+ while (i < length) {
+ if (sql.charAt(i) == '`') {
+ if (i + 1 < length && sql.charAt(i + 1) == '`') {
+ name.append('`');
+ i += 2;
+ continue;
+ }
+ break;
+ }
+ name.append(sql.charAt(i++));
+ }
+ i = Math.min(i + 1, length);
+ tokens.add(new Token(Kind.QUOTED, name.toString()));
+ } else if (c == '\'' || c == '"') {
+ StringBuilder value = new StringBuilder();
+ i = readString(sql, i, value);
+ tokens.add(new Token(Kind.STRING, value.toString()));
+ } else {
+ // Any other character is a symbol of its own: tokenizing never fails, so a statement this
+ // class does not run reaches the query engine with the engine's own error, not this one's.
+ tokens.add(new Token(Kind.SYMBOL, String.valueOf(c)));
+ i++;
+ }
+ }
+ return tokens;
+ }
+
+ /** Reads the Hive string literal at {@code start} into {@code value}, returning the index after it. */
+ private static int readString(String sql, int start, StringBuilder value) {
+ char quote = sql.charAt(start);
+ int i = start + 1;
+ while (i < sql.length()) {
+ char c = sql.charAt(i);
+ if (c == quote) {
+ if (i + 1 < sql.length() && sql.charAt(i + 1) == quote) {
+ value.append(quote);
+ i += 2;
+ continue;
+ }
+ return i + 1;
+ }
+ if (c == '\\' && i + 1 < sql.length()) {
+ i = readEscape(sql, i + 1, value);
+ continue;
+ }
+ value.append(c);
+ i++;
+ }
+ return i;
+ }
+
+ private static int readEscape(String sql, int i, StringBuilder value) {
+ char c = sql.charAt(i);
+ switch (c) {
+ case 't' -> value.append('\t');
+ case 'n' -> value.append('\n');
+ case 'r' -> value.append('\r');
+ case 'b' -> value.append('\b');
+ case 'f' -> value.append('\f');
+ case 'u' -> {
+ if (i + 4 < sql.length()) {
+ value.append((char) Integer.parseInt(sql.substring(i + 1, i + 5), 16));
+ return i + 5;
+ }
+ value.append(c);
+ }
+ default -> {
+ if (c >= '0' && c <= '7') {
+ int end = i;
+ while (end < sql.length() && end < i + 3 && sql.charAt(end) >= '0' && sql.charAt(end) <= '7') {
+ end++;
+ }
+ value.append((char) Integer.parseInt(sql.substring(i, end), 8));
+ return end;
+ }
+ value.append(c);
+ }
+ }
+ return i + 1;
+ }
+}
diff --git a/src/main/java/io/floci/aws/services/athena/AthenaHiveDdlExecutor.java b/src/main/java/io/floci/aws/services/athena/AthenaHiveDdlExecutor.java
new file mode 100644
index 0000000000..2898bfb91f
--- /dev/null
+++ b/src/main/java/io/floci/aws/services/athena/AthenaHiveDdlExecutor.java
@@ -0,0 +1,345 @@
+package io.floci.aws.services.athena;
+
+import io.floci.aws.core.common.AwsException;
+import io.floci.aws.services.glue.GlueService;
+import io.floci.aws.services.glue.GlueTableResolver;
+import io.floci.aws.services.glue.model.Column;
+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;
+import io.floci.aws.services.s3.model.S3Object;
+
+import java.net.URLDecoder;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * Runs an {@link AthenaHiveDdl} statement against the Glue Data Catalog, the way Athena runs it:
+ * {@code DROP TABLE} removes only a Hive table's metadata, and an Iceberg table's data with it, as
+ * Athena treats Iceberg tables as managed; {@code MSCK REPAIR TABLE}
+ * adds the Hive-style {@code key=value} partitions it finds under the table's location and never
+ * removes any; {@code IF [NOT] EXISTS} turns a duplicate or missing table or partition from an
+ * error into a no-op.
+ */
+final class AthenaHiveDdlExecutor {
+
+ private static final int LIST_PAGE_SIZE = 1000;
+ private static final String HIVE_ESCAPED_CHARACTERS = "\"#%'*/:=?\\{[]^";
+
+ private final GlueService glueService;
+ private final S3Service s3Service;
+
+ AthenaHiveDdlExecutor(GlueService glueService, S3Service s3Service) {
+ this.glueService = glueService;
+ this.s3Service = s3Service;
+ }
+
+ /**
+ * Runs {@code statement}, a table it names without a database being in {@code contextDatabase}.
+ * Returns the result rows of {@code SHOW PARTITIONS}, one {@code key=value[/key=value...]} string
+ * each, and no rows for every other statement.
+ */
+ List execute(AthenaHiveDdl.Statement statement, String contextDatabase) {
+ String database = statement.ref().database() != null ? statement.ref().database() : contextDatabase;
+ String table = statement.ref().table();
+ return switch (statement) {
+ case AthenaHiveDdl.CreateTable create -> {
+ createTable(database, create);
+ yield List.of();
+ }
+ case AthenaHiveDdl.DropTable drop -> {
+ dropTable(database, table, drop.ifExists());
+ yield List.of();
+ }
+ case AthenaHiveDdl.AddPartitions add -> {
+ addPartitions(database, existingTable(database, table), add);
+ yield List.of();
+ }
+ case AthenaHiveDdl.DropPartitions drop -> {
+ dropPartitions(database, existingTable(database, table), drop);
+ yield List.of();
+ }
+ case AthenaHiveDdl.RepairTable repair -> {
+ repair(database, existingTable(database, table));
+ yield List.of();
+ }
+ case AthenaHiveDdl.ShowPartitions show -> partitionNames(database, existingTable(database, table));
+ };
+ }
+
+ private void createTable(String database, AthenaHiveDdl.CreateTable create) {
+ create.table().setDatabaseName(database);
+ try {
+ glueService.createTable(database, create.table());
+ } catch (AwsException e) {
+ if (!create.ifNotExists() || !"AlreadyExistsException".equals(e.getErrorCode())) {
+ throw e;
+ }
+ }
+ }
+
+ private void dropTable(String database, String table, boolean ifExists) {
+ Table found = findTable(database, table);
+ if (found == null) {
+ if (ifExists) {
+ return;
+ }
+ throw tableNotFound(database, table);
+ }
+ try {
+ glueService.deleteTable(database, table);
+ } catch (AwsException e) {
+ // Another drop can remove the table between the lookup and the delete.
+ if (!ifExists || !"EntityNotFoundException".equals(e.getErrorCode())) {
+ throw e;
+ }
+ return;
+ }
+ if (GlueTableResolver.isIcebergTable(found)) {
+ // Athena treats an Iceberg table as managed: dropping it removes its data too.
+ deleteObjectsUnder(found.getStorageDescriptor() != null ? found.getStorageDescriptor().getLocation() : null);
+ }
+ }
+
+ private void deleteObjectsUnder(String location) {
+ S3Prefix prefix = S3Prefix.of(location);
+ if (prefix == null) {
+ return;
+ }
+ String continuation = null;
+ do {
+ S3Service.ListObjectsResult page = s3Service.listObjectsWithPrefixes(prefix.bucket(), prefix.prefix(), null,
+ LIST_PAGE_SIZE, continuation, null);
+ for (S3Object object : page.objects()) {
+ s3Service.deleteObject(prefix.bucket(), object.getKey());
+ }
+ continuation = page.isTruncated() ? page.nextContinuationToken() : null;
+ } while (continuation != null);
+ }
+
+ /** An {@code s3://bucket/prefix/} location split into its bucket and its key prefix, ending in a slash. */
+ private record S3Prefix(String bucket, String prefix) {
+ static S3Prefix of(String location) {
+ if (location == null || !location.startsWith("s3://")) {
+ return null;
+ }
+ String withoutScheme = location.substring("s3://".length());
+ int slash = withoutScheme.indexOf('/');
+ String bucket = slash < 0 ? withoutScheme : withoutScheme.substring(0, slash);
+ String prefix = slash < 0 ? "" : withoutScheme.substring(slash + 1);
+ return new S3Prefix(bucket, prefix.isEmpty() || prefix.endsWith("/") ? prefix : prefix + "/");
+ }
+ }
+
+ private void addPartitions(String database, Table table, AthenaHiveDdl.AddPartitions add) {
+ for (AthenaHiveDdl.PartitionSpec spec : add.partitions()) {
+ List values = orderedValues(table, spec);
+ createPartition(database, table, values,
+ spec.location() != null ? spec.location() : defaultLocation(table, values), add.ifNotExists());
+ }
+ }
+
+ private void dropPartitions(String database, Table table, AthenaHiveDdl.DropPartitions drop) {
+ for (AthenaHiveDdl.PartitionSpec spec : drop.partitions()) {
+ List values = orderedValues(table, spec);
+ try {
+ glueService.deletePartition(database, table.getName(), values);
+ } catch (AwsException e) {
+ if (!drop.ifExists() || !"EntityNotFoundException".equals(e.getErrorCode())) {
+ throw e;
+ }
+ }
+ }
+ }
+
+ /** Adds every complete {@code key=value/...} folder path under the table's location that has no partition yet. */
+ private void repair(String database, Table table) {
+ List keys = partitionKeys(table);
+ S3Prefix root = S3Prefix.of(table.getStorageDescriptor() != null ? table.getStorageDescriptor().getLocation() : null);
+ if (keys.isEmpty() || root == null) {
+ return;
+ }
+ Set> existing = glueService.getPartitions(database, table.getName()).stream()
+ .map(Partition::getValues)
+ .collect(Collectors.toCollection(HashSet::new));
+ // Each new partition's values and the folder they were found in, kept as spelled in S3.
+ Map, String> found = new LinkedHashMap<>();
+ String continuation = null;
+ do {
+ S3Service.ListObjectsResult page = s3Service.listObjectsWithPrefixes(root.bucket(), root.prefix(), null,
+ LIST_PAGE_SIZE, continuation, null);
+ for (S3Object object : page.objects()) {
+ String relative = object.getKey().substring(root.prefix().length());
+ List values = hivePartitionValues(relative, keys);
+ if (values != null && !existing.contains(values)) {
+ found.putIfAbsent(values, "s3://" + root.bucket() + "/" + root.prefix()
+ + String.join("/", Arrays.asList(relative.split("/", -1)).subList(0, keys.size())) + "/");
+ }
+ }
+ continuation = page.isTruncated() ? page.nextContinuationToken() : null;
+ } while (continuation != null);
+ found.forEach((values, location) -> createPartition(database, table, values, location, true));
+ }
+
+ private void createPartition(String database, Table table, List values, String location,
+ boolean tolerateExisting) {
+ Partition partition = new Partition();
+ partition.setValues(values);
+ partition.setStorageDescriptor(partitionDescriptor(table, location));
+ try {
+ glueService.createPartition(database, table.getName(), partition);
+ } catch (AwsException e) {
+ if (!tolerateExisting || !"AlreadyExistsException".equals(e.getErrorCode())) {
+ throw e;
+ }
+ }
+ }
+
+ /**
+ * The partition values the leading folders of {@code relativeKey} name, one {@code key=value}
+ * folder per partition key in order, or null when they do not. A key is matched without regard to
+ * case and a value is unescaped as Hive escapes folder names ({@code %2F} for {@code /}).
+ */
+ static List hivePartitionValues(String relativeKey, List keys) {
+ String[] segments = relativeKey.split("/", -1);
+ if (segments.length <= keys.size()) {
+ return null;
+ }
+ List values = new ArrayList<>();
+ for (int i = 0; i < keys.size(); i++) {
+ String segment = segments[i];
+ int equals = segment.indexOf('=');
+ if (equals <= 0 || !segment.substring(0, equals).equalsIgnoreCase(keys.get(i).getName())) {
+ return null;
+ }
+ try {
+ values.add(URLDecoder.decode(segment.substring(equals + 1).replace("+", "%2B"), StandardCharsets.UTF_8));
+ } catch (IllegalArgumentException malformedEscape) {
+ // A folder name Hive could not have written is not a partition folder.
+ return null;
+ }
+ }
+ return values;
+ }
+
+ private List partitionNames(String database, Table table) {
+ List keys = partitionKeys(table);
+ List names = new ArrayList<>();
+ for (Partition partition : glueService.getPartitions(database, table.getName())) {
+ List parts = new ArrayList<>();
+ for (int i = 0; i < keys.size() && i < partition.getValues().size(); i++) {
+ parts.add(keys.get(i).getName() + "=" + escapePathName(partition.getValues().get(i)));
+ }
+ names.add(String.join("/", parts));
+ }
+ return names;
+ }
+
+ /** The spec's values in the table's partition-key order; the spec has to name every key once. */
+ private static List orderedValues(Table table, AthenaHiveDdl.PartitionSpec spec) {
+ List keys = partitionKeys(table);
+ Map values = spec.values();
+ Set named = values.keySet().stream().map(k -> k.toLowerCase(Locale.ROOT)).collect(Collectors.toSet());
+ Set declared = keys.stream().map(k -> k.getName().toLowerCase(Locale.ROOT)).collect(Collectors.toSet());
+ if (keys.isEmpty() || !named.equals(declared) || named.size() != values.size()) {
+ throw new AwsException("InvalidRequestException", "The partition specification " + values.keySet()
+ + " does not match the partition keys of table " + table.getName() + ": " + declared, 400);
+ }
+ List ordered = new ArrayList<>();
+ for (Column key : keys) {
+ values.forEach((name, value) -> {
+ if (name.equalsIgnoreCase(key.getName())) {
+ ordered.add(value);
+ }
+ });
+ }
+ return ordered;
+ }
+
+ /** Athena's location for a partition added without one: {@code /key=value/...}. */
+ private static String defaultLocation(Table table, List values) {
+ String location = table.getStorageDescriptor() != null && table.getStorageDescriptor().getLocation() != null
+ ? table.getStorageDescriptor().getLocation() : "";
+ StringBuilder path = new StringBuilder(location.endsWith("/") ? location : location + "/");
+ List keys = partitionKeys(table);
+ for (int i = 0; i < keys.size(); i++) {
+ path.append(keys.get(i).getName()).append('=').append(escapePathName(values.get(i))).append('/');
+ }
+ return path.toString();
+ }
+
+ /**
+ * {@code value} as Hive writes it in a partition folder name and in {@code SHOW PARTITIONS}: the
+ * characters Hive's {@code FileUtils.escapePathName} escapes become {@code %XX}.
+ */
+ static String escapePathName(String value) {
+ StringBuilder escaped = new StringBuilder(value.length());
+ for (char c : value.toCharArray()) {
+ if (c < 0x20 || c == 0x7F || HIVE_ESCAPED_CHARACTERS.indexOf(c) >= 0) {
+ escaped.append('%').append(String.format(Locale.ROOT, "%02X", (int) c));
+ } else {
+ escaped.append(c);
+ }
+ }
+ return escaped.toString();
+ }
+
+ /** The table's storage descriptor with the partition's own location. */
+ private static StorageDescriptor partitionDescriptor(Table table, String location) {
+ StorageDescriptor source = table.getStorageDescriptor();
+ StorageDescriptor descriptor = new StorageDescriptor();
+ if (source != null) {
+ descriptor.setColumns(source.getColumns());
+ descriptor.setInputFormat(source.getInputFormat());
+ descriptor.setOutputFormat(source.getOutputFormat());
+ descriptor.setCompressed(source.getCompressed());
+ descriptor.setNumberOfBuckets(source.getNumberOfBuckets());
+ descriptor.setSerdeInfo(source.getSerdeInfo());
+ descriptor.setBucketColumns(source.getBucketColumns());
+ descriptor.setSortColumns(source.getSortColumns());
+ descriptor.setParameters(source.getParameters());
+ descriptor.setSkewedInfo(source.getSkewedInfo());
+ descriptor.setStoredAsSubDirectories(source.getStoredAsSubDirectories());
+ descriptor.setSchemaReference(source.getSchemaReference());
+ descriptor.setAdditionalLocations(source.getAdditionalLocations());
+ }
+ descriptor.setLocation(location);
+ return descriptor;
+ }
+
+ private static List partitionKeys(Table table) {
+ return table.getPartitionKeys() == null ? List.of() : table.getPartitionKeys();
+ }
+
+ private Table existingTable(String database, String table) {
+ Table found = findTable(database, table);
+ if (found == null) {
+ throw tableNotFound(database, table);
+ }
+ return found;
+ }
+
+ private Table findTable(String database, String table) {
+ try {
+ return glueService.getTable(database, table);
+ } catch (AwsException e) {
+ if ("EntityNotFoundException".equals(e.getErrorCode())) {
+ return null;
+ }
+ throw e;
+ }
+ }
+
+ private static AwsException tableNotFound(String database, String table) {
+ return new AwsException("InvalidRequestException", "Table not found: " + database + "." + table, 400);
+ }
+}
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 3d03d75d09..e2b29579e3 100644
--- a/src/main/java/io/floci/aws/services/athena/AthenaService.java
+++ b/src/main/java/io/floci/aws/services/athena/AthenaService.java
@@ -109,6 +109,7 @@ public class AthenaService {
private final Vertx vertx;
private final GlueViewDdlBuilder ddlBuilder;
private final RegionResolver regionResolver;
+ private final AthenaHiveDdlExecutor hiveDdlExecutor;
@Inject
public AthenaService(StorageFactory storageFactory,
@@ -134,6 +135,7 @@ public class AthenaService {
this.vertx = vertx;
this.ddlBuilder = ddlBuilder;
this.regionResolver = regionResolver;
+ this.hiveDdlExecutor = new AthenaHiveDdlExecutor(glueService, s3Service);
}
public String startQueryExecution(String query,
@@ -149,6 +151,16 @@ public class AthenaService {
}
boolean createDatabaseStatement = CREATE_DATABASE_PREFIX_PATTERN.matcher(statementText(query)).find();
+ // Hive DDL runs against the Glue catalog, not the query engine. A statement that starts like one but
+ // does not parse fails the query with the parser's reason rather than reaching DuckDB.
+ AthenaHiveDdl.Statement hiveDdl = null;
+ AwsException invalidHiveDdl = null;
+ try {
+ hiveDdl = AthenaHiveDdl.parse(query);
+ } catch (AwsException e) {
+ invalidHiveDdl = e;
+ }
+ boolean hiveDdlStatement = hiveDdl != 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.
// Statements that do not return rows must not be wrapped in a result COPY.
@@ -160,12 +172,28 @@ public class AthenaService {
: null;
QueryExecution execution = new QueryExecution(id, query, workGroup, resolvedResult, resolvedContext);
- if (createDatabaseStatement) {
+ if (createDatabaseStatement || hiveDdlStatement) {
execution.setStatementType("DDL");
}
execution.getStatus().setState(QueryExecutionState.RUNNING);
queryStore.put(id, execution);
+ if (hiveDdlStatement) {
+ try {
+ if (invalidHiveDdl != null) {
+ throw invalidHiveDdl;
+ }
+ List rows = hiveDdlExecutor.execute(hiveDdl, database);
+ if (outputLocation != null) {
+ writeSingleColumnResult(id, outputLocation, "partition", rows);
+ }
+ markSucceeded(id, execution);
+ } catch (Exception e) {
+ markFailed(id, execution, e);
+ }
+ return id;
+ }
+
if (createDatabaseStatement) {
try {
CreateDatabaseDdl createDatabaseDdl = parseCreateDatabase(query);
@@ -556,7 +584,8 @@ public class AthenaService {
throw new AwsException("InvalidRequestException", "Query has not succeeded yet", 400);
}
- if (config.services().athena().mock()
+ // DDL rows (SHOW PARTITIONS) come from the Glue catalog, not the query engine, so mock mode keeps them.
+ if (config.services().athena().mock() && !"DDL".equals(execution.getStatementType())
|| execution.getResultConfiguration() == null
|| execution.getResultConfiguration().getOutputLocation() == null) {
return new ResultSet(List.of(), new ResultSet.ResultSetMetadata(List.of()));
@@ -1120,6 +1149,18 @@ public class AthenaService {
}
}
+ /** Writes {@code rows} as a one-column result CSV, the shape the query engine writes, typed varchar. */
+ private void writeSingleColumnResult(String id, String outputLocation, String column, List rows) {
+ ensureOutputBucket(outputLocation);
+ StringBuilder csv = new StringBuilder(column).append('\n');
+ for (String row : rows) {
+ csv.append('"').append(row.replace("\"", "\"\"")).append("\"\n");
+ }
+ s3Service.putObject(extractBucket(outputLocation), extractKey(outputLocation),
+ csv.toString().getBytes(StandardCharsets.UTF_8), "text/csv", null);
+ resultColumnTypeStore.put(id, List.of("VARCHAR"));
+ }
+
private void ensureOutputBucket(String s3Path) {
String bucket = extractBucket(s3Path);
if (bucket != null) {
diff --git a/src/test/java/io/floci/aws/services/athena/AthenaHiveDdlExecutorTest.java b/src/test/java/io/floci/aws/services/athena/AthenaHiveDdlExecutorTest.java
new file mode 100644
index 0000000000..063e8becbf
--- /dev/null
+++ b/src/test/java/io/floci/aws/services/athena/AthenaHiveDdlExecutorTest.java
@@ -0,0 +1,51 @@
+package io.floci.aws.services.athena;
+
+import io.floci.aws.core.common.AwsException;
+import io.floci.aws.services.glue.GlueService;
+import io.floci.aws.services.glue.model.Column;
+import io.floci.aws.services.glue.model.Table;
+import io.floci.aws.services.s3.S3Service;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import java.util.List;
+
+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.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.when;
+
+class AthenaHiveDdlExecutorTest {
+
+ @Test
+ void dropTableIfExistsStaysANoOpWhenAnotherDropWinsTheRace() {
+ GlueService glue = Mockito.mock(GlueService.class);
+ Table table = new Table();
+ table.setName("events");
+ when(glue.getTable("lake", "events")).thenReturn(table);
+ doThrow(new AwsException("EntityNotFoundException", "Table not found", 400)).when(glue).deleteTable("lake", "events");
+ AthenaHiveDdlExecutor executor = new AthenaHiveDdlExecutor(glue, Mockito.mock(S3Service.class));
+
+ assertDoesNotThrow(() -> executor.execute(AthenaHiveDdl.parse("DROP TABLE IF EXISTS events"), "lake"));
+ AwsException e = assertThrows(AwsException.class,
+ () -> executor.execute(AthenaHiveDdl.parse("DROP TABLE events"), "lake"));
+ assertEquals("EntityNotFoundException", e.getErrorCode());
+ }
+
+ @Test
+ void aFolderWithAnInvalidEscapeIsNotAPartitionFolder() {
+ Column region = new Column();
+ region.setName("region");
+
+ assertNull(AthenaHiveDdlExecutor.hivePartitionValues("region=bad%ZZ/part-0", List.of(region)));
+ assertEquals(List.of("sa/west"), AthenaHiveDdlExecutor.hivePartitionValues("region=sa%2fwest/part-0", List.of(region)));
+ }
+
+ @Test
+ void hiveEscapesTheCharactersItReservesInFolderNames() {
+ assertEquals("sa%2Fwest%3Dx%25", AthenaHiveDdlExecutor.escapePathName("sa/west=x%"));
+ assertEquals("2026-11-14 10.00", AthenaHiveDdlExecutor.escapePathName("2026-11-14 10.00"));
+ }
+}
diff --git a/src/test/java/io/floci/aws/services/athena/AthenaHiveDdlIntegrationTest.java b/src/test/java/io/floci/aws/services/athena/AthenaHiveDdlIntegrationTest.java
new file mode 100644
index 0000000000..bbc08acc05
--- /dev/null
+++ b/src/test/java/io/floci/aws/services/athena/AthenaHiveDdlIntegrationTest.java
@@ -0,0 +1,224 @@
+package io.floci.aws.services.athena;
+
+import io.floci.aws.testing.AwsTestClients;
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.core.sync.RequestBody;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.athena.AthenaClient;
+import software.amazon.awssdk.services.athena.model.QueryExecution;
+import software.amazon.awssdk.services.athena.model.QueryExecutionState;
+import software.amazon.awssdk.services.athena.model.Row;
+import software.amazon.awssdk.services.glue.GlueClient;
+import software.amazon.awssdk.services.glue.model.EntityNotFoundException;
+import software.amazon.awssdk.services.glue.model.Partition;
+import software.amazon.awssdk.services.glue.model.Table;
+import software.amazon.awssdk.services.s3.S3Client;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.stream.Collectors;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Hive DDL submitted through Athena changes the Glue Data Catalog the way Athena does, checked
+ * through the Glue and Athena APIs with the AWS SDK.
+ */
+@QuarkusTest
+class AthenaHiveDdlIntegrationTest {
+
+ private static final AtomicLong ACCOUNTS = new AtomicLong(741680700000L);
+
+ private AthenaClient athena;
+ private GlueClient glue;
+ private S3Client s3;
+ private String bucket;
+ private String results;
+
+ @BeforeEach
+ void openClients() {
+ String account = Long.toString(ACCOUNTS.incrementAndGet());
+ athena = AwsTestClients.create(AthenaClient.builder(), account, Region.US_EAST_1);
+ glue = AwsTestClients.create(GlueClient.builder(), account, Region.US_EAST_1);
+ s3 = AwsTestClients.create(S3Client.builder().forcePathStyle(true), account, Region.US_EAST_1);
+ bucket = "hive-ddl-" + account;
+ results = "hive-ddl-results-" + account;
+ s3.createBucket(r -> r.bucket(bucket));
+ assertEquals(QueryExecutionState.SUCCEEDED, run("CREATE DATABASE lake").status().state());
+ }
+
+ @AfterEach
+ void closeClients() {
+ athena.close();
+ glue.close();
+ s3.close();
+ }
+
+ private QueryExecution run(String sql) {
+ String id = athena.startQueryExecution(r -> r.queryString(sql)
+ .queryExecutionContext(c -> c.database("lake"))
+ .resultConfiguration(c -> c.outputLocation("s3://" + results + "/"))).queryExecutionId();
+ return athena.getQueryExecution(r -> r.queryExecutionId(id)).queryExecution();
+ }
+
+ private void succeeds(String sql) {
+ QueryExecution execution = run(sql);
+ assertEquals(QueryExecutionState.SUCCEEDED, execution.status().state(), execution.status().stateChangeReason());
+ assertEquals("DDL", execution.statementTypeAsString());
+ }
+
+ private String fails(String sql) {
+ QueryExecution execution = run(sql);
+ assertEquals(QueryExecutionState.FAILED, execution.status().state(), sql);
+ return execution.status().stateChangeReason();
+ }
+
+ private void createEventsTable() {
+ succeeds("""
+ CREATE EXTERNAL TABLE events (id bigint, payload struct>)
+ PARTITIONED BY (dt string, region string)
+ ROW FORMAT DELIMITED FIELDS TERMINATED BY '\\t'
+ STORED AS TEXTFILE
+ LOCATION 's3://%s/events/'
+ TBLPROPERTIES ('classification'='csv')
+ """.formatted(bucket));
+ }
+
+ private Set partitionLocations() {
+ return glue.getPartitions(r -> r.databaseName("lake").tableName("events")).partitions().stream()
+ .map(p -> String.join("/", p.values()) + "@" + p.storageDescriptor().location())
+ .collect(Collectors.toSet());
+ }
+
+ @Test
+ void createExternalTableRegistersTheGlueTable() {
+ createEventsTable();
+
+ Table table = glue.getTable(r -> r.databaseName("lake").name("events")).table();
+ assertEquals("EXTERNAL_TABLE", table.tableType());
+ assertEquals(Map.of("classification", "csv", "EXTERNAL", "TRUE"), table.parameters());
+ assertEquals(List.of("bigint", "struct>"),
+ table.storageDescriptor().columns().stream().map(c -> c.type()).toList());
+ assertEquals(List.of("dt", "region"), table.partitionKeys().stream().map(c -> c.name()).toList());
+ assertEquals("s3://" + bucket + "/events/", table.storageDescriptor().location());
+ assertEquals("org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe",
+ table.storageDescriptor().serdeInfo().serializationLibrary());
+ assertEquals("\t", table.storageDescriptor().serdeInfo().parameters().get("field.delim"));
+
+ assertTrue(fails(String.format("CREATE EXTERNAL TABLE events (id bigint) LOCATION 's3://%s/x/'", bucket))
+ .contains("exists"));
+ succeeds(String.format("CREATE EXTERNAL TABLE IF NOT EXISTS events (id bigint) LOCATION 's3://%s/x/'", bucket));
+ assertTrue(fails("CREATE TABLE plain (a int) STORED AS PARQUET LOCATION 's3://b/plain/'").contains("EXTERNAL"));
+ }
+
+ @Test
+ void addPartitionDefaultsToTheHiveLayoutAndHonoursIfNotExists() {
+ createEventsTable();
+
+ succeeds("""
+ ALTER TABLE events ADD
+ PARTITION (dt = '2026-11-14', region = 'eu')
+ PARTITION (region = 'us', dt = '2026-11-15') LOCATION 's3://%s/custom/'
+ """.formatted(bucket));
+
+ assertEquals(Set.of("2026-11-14/eu@s3://" + bucket + "/events/dt=2026-11-14/region=eu/",
+ "2026-11-15/us@s3://" + bucket + "/custom/"), partitionLocations());
+ fails("ALTER TABLE events ADD PARTITION (dt = '2026-11-14', region = 'eu')");
+ succeeds("ALTER TABLE events ADD IF NOT EXISTS PARTITION (dt = '2026-11-14', region = 'eu')");
+ assertTrue(fails("ALTER TABLE events ADD PARTITION (dt = '2026-11-16')").contains("partition keys"));
+ }
+
+ @Test
+ void msckRepairAddsTheHiveFoldersItFindsAndShowPartitionsListsThem() {
+ createEventsTable();
+ succeeds("ALTER TABLE events ADD PARTITION (dt = '2026-11-14', region = 'eu')");
+ for (String key : List.of("events/dt=2026-11-14/region=eu/part-0.tsv", "events/dt=2026-11-16/region=ap/part-0.tsv",
+ "events/dt=2026-11-17/region=sa%2Fwest/part-0.tsv", "events/dt=2026-11-18/part-0.tsv",
+ "events/other/part-0.tsv")) {
+ s3.putObject(r -> r.bucket(bucket).key(key), RequestBody.fromString("1\t{}\n"));
+ }
+
+ succeeds("MSCK REPAIR TABLE events");
+
+ assertEquals(Set.of("2026-11-14/eu", "2026-11-16/ap", "2026-11-17/sa/west"),
+ glue.getPartitions(r -> r.databaseName("lake").tableName("events")).partitions().stream()
+ .map(p -> String.join("/", p.values())).collect(Collectors.toSet()));
+ QueryExecution show = run("SHOW PARTITIONS events");
+ assertEquals(QueryExecutionState.SUCCEEDED, show.status().state(), show.status().stateChangeReason());
+ List rows = athena.getQueryResults(r -> r.queryExecutionId(show.queryExecutionId())).resultSet().rows();
+ assertEquals("partition", rows.getFirst().data().getFirst().varCharValue());
+ assertEquals(Set.of("dt=2026-11-14/region=eu", "dt=2026-11-16/region=ap", "dt=2026-11-17/region=sa%2Fwest"),
+ rows.stream().skip(1).map(row -> row.data().getFirst().varCharValue()).collect(Collectors.toSet()));
+ }
+
+ @Test
+ void msckKeepsEachFolderAsSpelledAndSkipsOnesHiveCouldNotHaveWritten() {
+ createEventsTable();
+ for (String key : List.of("events/dt=2026-11-14/region=sa%2fwest/part-0.tsv",
+ "events/dt=2026-11-14/region=bad%ZZ/part-0.tsv")) {
+ s3.putObject(r -> r.bucket(bucket).key(key), RequestBody.fromString("1\t{}\n"));
+ }
+
+ succeeds("MSCK REPAIR TABLE events");
+
+ assertEquals(Set.of("2026-11-14/sa/west@s3://" + bucket + "/events/dt=2026-11-14/region=sa%2fwest/"),
+ partitionLocations());
+ }
+
+ @Test
+ void anAddedPartitionInheritsTheTablesSortColumns() {
+ succeeds("""
+ CREATE EXTERNAL TABLE sorted_events (id bigint) PARTITIONED BY (dt string)
+ CLUSTERED BY (id) SORTED BY (id DESC) INTO 2 BUCKETS STORED AS PARQUET LOCATION 's3://%s/sorted/'
+ """.formatted(bucket));
+
+ succeeds("ALTER TABLE sorted_events ADD PARTITION (dt = '2026-11-14')");
+
+ Partition partition = glue.getPartitions(r -> r.databaseName("lake").tableName("sorted_events")).partitions().getFirst();
+ assertEquals("id", partition.storageDescriptor().sortColumns().getFirst().column());
+ assertEquals(0, partition.storageDescriptor().sortColumns().getFirst().sortOrder());
+ }
+
+ @Test
+ void droppingAnIcebergTableDeletesItsDataToo() {
+ glue.createTable(r -> r.databaseName("lake").tableInput(t -> t.name("ice")
+ .tableType("EXTERNAL_TABLE")
+ .parameters(Map.of("table_type", "ICEBERG", "metadata_location", "s3://" + bucket + "/ice/metadata/v1.json"))
+ .storageDescriptor(sd -> sd.location("s3://" + bucket + "/ice"))));
+ for (String key : List.of("ice/metadata/v1.json", "ice/data/part-0.parquet", "iceberg-other/keep.txt")) {
+ s3.putObject(r -> r.bucket(bucket).key(key), RequestBody.fromString("x"));
+ }
+
+ succeeds("DROP TABLE ice");
+
+ assertEquals(List.of("iceberg-other/keep.txt"), s3.listObjectsV2(r -> r.bucket(bucket)).contents().stream()
+ .map(o -> o.key()).toList());
+ }
+
+ @Test
+ void dropPartitionAndDropTableRemoveMetadataOnly() {
+ createEventsTable();
+ succeeds("ALTER TABLE events ADD PARTITION (dt = '2026-11-14', region = 'eu') PARTITION (dt = '2026-11-15', region = 'us')");
+ s3.putObject(r -> r.bucket(bucket).key("events/dt=2026-11-14/region=eu/part-0.tsv"), RequestBody.fromString("1\n"));
+
+ succeeds("ALTER TABLE events DROP PARTITION (dt = '2026-11-15', region = 'us')");
+ assertEquals(List.of("2026-11-14"), glue.getPartitions(r -> r.databaseName("lake").tableName("events"))
+ .partitions().stream().map(Partition::values).map(List::getFirst).toList());
+ fails("ALTER TABLE events DROP PARTITION (dt = '2026-11-15', region = 'us')");
+ succeeds("ALTER TABLE events DROP IF EXISTS PARTITION (dt = '2026-11-15', region = 'us')");
+
+ succeeds("DROP TABLE lake.events");
+ assertThrows(EntityNotFoundException.class, () -> glue.getTable(r -> r.databaseName("lake").name("events")));
+ assertEquals(1, s3.listObjectsV2(r -> r.bucket(bucket).prefix("events/")).keyCount(),
+ "the table's data stays where it was");
+ assertTrue(fails("DROP TABLE events").contains("not found"));
+ succeeds("DROP TABLE IF EXISTS events");
+ }
+}
diff --git a/src/test/java/io/floci/aws/services/athena/AthenaHiveDdlTest.java b/src/test/java/io/floci/aws/services/athena/AthenaHiveDdlTest.java
new file mode 100644
index 0000000000..708700dbbe
--- /dev/null
+++ b/src/test/java/io/floci/aws/services/athena/AthenaHiveDdlTest.java
@@ -0,0 +1,177 @@
+package io.floci.aws.services.athena;
+
+import io.floci.aws.core.common.AwsException;
+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 org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class AthenaHiveDdlTest {
+
+ private static AthenaHiveDdl.CreateTable create(String sql) {
+ return assertInstanceOf(AthenaHiveDdl.CreateTable.class, AthenaHiveDdl.parse(sql));
+ }
+
+ @Test
+ void createExternalTableWithDelimitedTextBecomesTheGlueTableHiveStores() {
+ AthenaHiveDdl.CreateTable create = create("""
+ -- a headerless TSV table
+ CREATE EXTERNAL TABLE IF NOT EXISTS Lake.`Events` (
+ `Id` BIGINT COMMENT 'the id',
+ payload STRUCT>,
+ amount DECIMAL(10, 2)
+ )
+ COMMENT 'raw events'
+ PARTITIONED BY (dt STRING, region STRING)
+ ROW FORMAT DELIMITED FIELDS TERMINATED BY '\\t' ESCAPED BY '\\\\' LINES TERMINATED BY '\\n'
+ NULL DEFINED AS ''
+ STORED AS TEXTFILE
+ LOCATION 's3://lake/events/'
+ TBLPROPERTIES ('classification'='csv', 'skip.header.line.count'='0');
+ """);
+
+ assertEquals(new AthenaHiveDdl.TableRef("lake", "events"), create.ref());
+ assertTrue(create.ifNotExists());
+ Table table = create.table();
+ assertEquals("events", table.getName());
+ assertEquals("EXTERNAL_TABLE", table.getTableType());
+ assertEquals("raw events", table.getDescription());
+ assertEquals(Map.of("classification", "csv", "skip.header.line.count", "0", "EXTERNAL", "TRUE"),
+ table.getParameters());
+ StorageDescriptor descriptor = table.getStorageDescriptor();
+ assertEquals(List.of("id:bigint:the id", "payload:struct>:null", "amount:decimal(10,2):null"),
+ descriptor.getColumns().stream().map(c -> c.getName() + ":" + c.getType() + ":" + c.getComment()).toList());
+ assertEquals(List.of("dt", "region"), table.getPartitionKeys().stream().map(Column::getName).toList());
+ assertEquals("s3://lake/events/", descriptor.getLocation());
+ assertEquals("org.apache.hadoop.mapred.TextInputFormat", descriptor.getInputFormat());
+ assertEquals("org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat", descriptor.getOutputFormat());
+ assertEquals("org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe",
+ descriptor.getSerdeInfo().getSerializationLibrary());
+ assertEquals(Map.of("field.delim", "\t", "serialization.format", "\t", "escape.delim", "\\",
+ "line.delim", "\n", "serialization.null.format", ""), descriptor.getSerdeInfo().getParameters());
+ }
+
+ @Test
+ void clusteredAndSortedByKeepTheirColumnsAndDirections() {
+ StorageDescriptor descriptor = create("""
+ CREATE EXTERNAL TABLE t (a int, b string) CLUSTERED BY (a) SORTED BY (a DESC, b) INTO 4 BUCKETS
+ STORED AS PARQUET LOCATION 's3://b/t/'
+ """).table().getStorageDescriptor();
+
+ assertEquals(List.of("a"), descriptor.getBucketColumns());
+ assertEquals(4, descriptor.getNumberOfBuckets());
+ assertEquals(List.of("a:0", "b:1"),
+ descriptor.getSortColumns().stream().map(o -> o.getColumn() + ":" + o.getSortOrder()).toList());
+ }
+
+ @Test
+ void storedAsPicksTheFormatsInputOutputAndSerde() {
+ StorageDescriptor parquet = create("CREATE EXTERNAL TABLE t (a int) STORED AS PARQUET LOCATION 's3://b/t/'")
+ .table().getStorageDescriptor();
+
+ assertEquals("org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat", parquet.getInputFormat());
+ assertEquals("org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe",
+ parquet.getSerdeInfo().getSerializationLibrary());
+ assertEquals(Map.of(), parquet.getSerdeInfo().getParameters());
+ }
+
+ @Test
+ void anExplicitSerdeAndInputFormatAreKeptAsWritten() {
+ StorageDescriptor json = create("""
+ CREATE EXTERNAL TABLE t (a int)
+ ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe' WITH SERDEPROPERTIES ("ignore.malformed.json"="true")
+ STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat'
+ OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.IgnoreKeyTextOutputFormat'
+ LOCATION 's3://b/t/'
+ """).table().getStorageDescriptor();
+
+ assertEquals("org.openx.data.jsonserde.JsonSerDe", json.getSerdeInfo().getSerializationLibrary());
+ assertEquals(Map.of("ignore.malformed.json", "true"), json.getSerdeInfo().getParameters());
+ assertEquals("org.apache.hadoop.hive.ql.io.IgnoreKeyTextOutputFormat", json.getOutputFormat());
+ }
+
+ @Test
+ void withoutRowFormatOrStoredAsATableIsTextWithTheDefaultSerde() {
+ StorageDescriptor text = create("CREATE EXTERNAL TABLE t (a int) LOCATION 's3://b/t/'").table().getStorageDescriptor();
+
+ assertEquals("org.apache.hadoop.mapred.TextInputFormat", text.getInputFormat());
+ assertEquals(Map.of("serialization.format", "1"), text.getSerdeInfo().getParameters());
+ }
+
+ @Test
+ void createTableWithoutExternalIsLeftToIcebergAndCtasOrRefused() {
+ assertNull(AthenaHiveDdl.parse("CREATE TABLE t (a int) LOCATION 's3://b/t/' TBLPROPERTIES ('table_type'='ICEBERG')"));
+ assertNull(AthenaHiveDdl.parse("CREATE TABLE t WITH (format = 'PARQUET') AS SELECT 1 AS a"));
+ assertNull(AthenaHiveDdl.parse("CREATE TABLE t AS SELECT 1 AS a"));
+ AwsException hive = assertThrows(AwsException.class,
+ () -> AthenaHiveDdl.parse("CREATE TABLE t (a int) STORED AS PARQUET LOCATION 's3://b/t/'"));
+ assertTrue(hive.getMessage().contains("EXTERNAL"), hive.getMessage());
+ }
+
+ @Test
+ void dropRepairAndShowNameTheirTable() {
+ AthenaHiveDdl.DropTable drop = assertInstanceOf(AthenaHiveDdl.DropTable.class,
+ AthenaHiveDdl.parse("DROP TABLE IF EXISTS lake.events;"));
+ assertTrue(drop.ifExists());
+ assertEquals(new AthenaHiveDdl.TableRef("lake", "events"), drop.ref());
+ assertFalse(assertInstanceOf(AthenaHiveDdl.DropTable.class, AthenaHiveDdl.parse("drop table t")).ifExists());
+ assertEquals(new AthenaHiveDdl.TableRef(null, "events"),
+ AthenaHiveDdl.parse("MSCK REPAIR TABLE `Events`").ref());
+ assertInstanceOf(AthenaHiveDdl.ShowPartitions.class, AthenaHiveDdl.parse("SHOW PARTITIONS lake.events"));
+ }
+
+ @Test
+ void alterTableAddAndDropPartitionsKeepEachSpecAndLocation() {
+ AthenaHiveDdl.AddPartitions add = assertInstanceOf(AthenaHiveDdl.AddPartitions.class, AthenaHiveDdl.parse("""
+ ALTER TABLE events ADD IF NOT EXISTS
+ PARTITION (dt = '2026-11-14', region = 'eu')
+ PARTITION (dt = '2026-11-15', region = 'us') LOCATION 's3://lake/custom/'
+ """));
+ assertTrue(add.ifNotExists());
+ assertEquals(List.of(new AthenaHiveDdl.PartitionSpec(Map.of("dt", "2026-11-14", "region", "eu"), null),
+ new AthenaHiveDdl.PartitionSpec(Map.of("dt", "2026-11-15", "region", "us"), "s3://lake/custom/")),
+ add.partitions());
+
+ AthenaHiveDdl.DropPartitions drop = assertInstanceOf(AthenaHiveDdl.DropPartitions.class,
+ AthenaHiveDdl.parse("ALTER TABLE events DROP PARTITION (year = 2026), PARTITION (year = 2025)"));
+ assertFalse(drop.ifExists());
+ assertEquals(List.of(Map.of("year", "2026"), Map.of("year", "2025")),
+ drop.partitions().stream().map(AthenaHiveDdl.PartitionSpec::values).toList());
+ }
+
+ @Test
+ void otherAlterTableStatementsAreRefusedClearly() {
+ AwsException e = assertThrows(AwsException.class,
+ () -> AthenaHiveDdl.parse("ALTER TABLE events ADD COLUMNS (b string)"));
+
+ assertTrue(e.getMessage().contains("ADD PARTITION"), e.getMessage());
+ }
+
+ @Test
+ void queriesAndOtherStatementsAreNotHiveDdl() {
+ assertNull(AthenaHiveDdl.parse("SELECT a || b, 'x' FROM t WHERE c ~ 'y'"));
+ assertNull(AthenaHiveDdl.parse("SHOW TABLES IN lake"));
+ assertNull(AthenaHiveDdl.parse("CREATE DATABASE lake"));
+ assertNull(AthenaHiveDdl.parse("DROP DATABASE lake"));
+ assertNull(AthenaHiveDdl.parse("INSERT INTO t VALUES (1)"));
+ assertNull(AthenaHiveDdl.parse(""));
+ }
+
+ @Test
+ void aMalformedHiveStatementSaysWhatIsWrong() {
+ AwsException e = assertThrows(AwsException.class,
+ () -> AthenaHiveDdl.parse("CREATE EXTERNAL TABLE t (a int LOCATION 's3://b/'"));
+
+ assertEquals("InvalidRequestException", e.getErrorCode());
+ }
+}