Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

feat(athena): support DDL, database ops, and Trino-style table references (#1897)

Seongjin Cho6052913e4402
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 82c7e6f2..6e2fac09 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Added
+
+- **Athena — databases, DDL, and Trino-style table references** — `ListDatabases` and `GetDatabase` read the Glue Data Catalog; `CREATE EXTERNAL TABLE` and `DROP TABLE` apply to it, creating the Glue table Athena would (formats, SerDe, TBLPROPERTIES); `CREATE TABLE` without `EXTERNAL` is rejected as Athena rejects it, and Iceberg tables are not supported; a query may name a table as `"awsdatacatalog"."db"."t"` or `db.t`.
+
## [1.5.20] — 2026-10-01
### Added
diff --git a/ministack/services/athena.py b/ministack/services/athena.py
index 41a13b3b..56f7aeb2 100644
--- a/ministack/services/athena.py
+++ b/ministack/services/athena.py
@@ -17,6 +17,7 @@ Supports: StartQueryExecution, GetQueryExecution, GetQueryResults,
import asyncio
import copy
import csv
+import glob
import io
import json
import logging
@@ -24,6 +25,7 @@ import os
import re
import time
import xml.etree.ElementTree as ET
+from dataclasses import dataclass, field
from urllib.parse import urlparse
from ministack.core.arn import ArnParseError, parse_arn
@@ -73,7 +75,13 @@ def _ensure_default_workgroup():
"Description": "Primary workgroup",
"CreationTime": int(time.time()),
"Configuration": {
- "ResultConfiguration": {"OutputLocation": "s3://athena-results/"}
+ "ResultConfiguration": {"OutputLocation": "s3://athena-results/"},
+ # AUTO is the default selection; the effective version is what Athena resolved it to.
+ # https://docs.aws.amazon.com/athena/latest/APIReference/API_EngineVersion.html
+ "EngineVersion": {
+ "SelectedEngineVersion": "AUTO",
+ "EffectiveEngineVersion": "Athena engine version 3",
+ },
},
}
@@ -313,7 +321,9 @@ async def handle_request(method, path, headers, body, query_params):
"GetPreparedStatement": _get_prepared_statement,
"DeletePreparedStatement": _delete_prepared_statement,
"ListPreparedStatements": _list_prepared_statements,
- # Table Metadata
+ # Databases and Table Metadata (Glue Data Catalog)
+ "GetDatabase": _get_database,
+ "ListDatabases": _list_databases,
"GetTableMetadata": _get_table_metadata,
"ListTableMetadata": _list_table_metadata,
# Tags
@@ -330,6 +340,501 @@ async def handle_request(method, path, headers, body, query_params):
return handler(data)
+# ---- SQL scanning ----
+#
+# Statements are read token by token, so a literal, a comment or a quoted name
+# is never structure: the "," in 'a, b' or the ")" in -- note) ends nothing.
+
+_NAME_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
+_NUMBER_RE = re.compile(r"[0-9]+")
+
+
+def _sql_tokens(sql):
+ """``(kind, text, start, end)`` per token, skipping whitespace and comments.
+
+ Kinds: ``name`` (bare, lower-cased), ``qname`` (``"x"`` or Hive's ``\\`x\\```, unquoted),
+ ``str`` (``'x'`` as written), ``number``, ``punct`` (one character).
+ """
+ i, n = 0, len(sql)
+ while i < n:
+ ch = sql[i]
+ if ch.isspace():
+ i += 1
+ elif sql.startswith("--", i):
+ j = sql.find("\n", i)
+ i = n if j < 0 else j + 1
+ elif sql.startswith("/*", i):
+ j = sql.find("*/", i + 2)
+ i = n if j < 0 else j + 2
+ elif ch in "'\"`":
+ j = i + 1
+ while j < n and not (sql[j] == ch and sql[j + 1:j + 2] != ch):
+ j += 2 if sql[j] == ch else 1
+ end = min(j + 1, n)
+ if ch == "'":
+ yield "str", sql[i:end], i, end
+ else:
+ yield "qname", sql[i + 1:j].replace(ch * 2, ch), i, end
+ i = end
+ elif m := _NAME_RE.match(sql, i):
+ yield "name", m.group(0).lower(), i, m.end()
+ i = m.end()
+ elif m := _NUMBER_RE.match(sql, i):
+ yield "number", m.group(0), i, m.end()
+ i = m.end()
+ else:
+ yield "punct", ch, i, i + 1
+ i += 1
+
+
+class _Cursor:
+ def __init__(self, text):
+ self.text = text
+ self.tokens = list(_sql_tokens(text))
+ self.i = 0
+
+ def reset(self):
+ self.i = 0
+
+ def at_end(self):
+ return self.i >= len(self.tokens)
+
+ def peek(self):
+ return self.tokens[self.i] if self.i < len(self.tokens) else (None, None, None, None)
+
+ def advance(self):
+ self.i += 1
+
+ def keywords(self, *words):
+ """Consume the bare-name keyword run ``words`` if it is next; else leave the cursor."""
+ for offset, word in enumerate(words):
+ if self.i + offset >= len(self.tokens) or self.tokens[self.i + offset][:2] != ("name", word):
+ return False
+ self.i += len(words)
+ return True
+
+ def punct(self, char):
+ if self.peek()[:2] == ("punct", char):
+ self.advance()
+ return True
+ return False
+
+ def skip_group(self):
+ """After ``punct("(")``: consume through the matching ``)``."""
+ depth = 1
+ while not self.at_end() and depth > 0:
+ if self.punct("("):
+ depth += 1
+ elif self.punct(")"):
+ depth -= 1
+ else:
+ self.advance()
+
+ def name(self):
+ kind, text = self.peek()[:2]
+ if kind == "name":
+ self.advance()
+ return text
+ return None
+
+ def identifier(self):
+ """A bare (lower-cased) or quoted (verbatim) identifier."""
+ kind, text = self.peek()[:2]
+ if kind in ("name", "qname"):
+ self.advance()
+ return text
+ return None
+
+ def number(self):
+ kind, text = self.peek()[:2]
+ if kind == "number":
+ self.advance()
+ return int(text)
+ return None
+
+ def string(self):
+ """A ``'...'`` literal's value: ``''`` is a quote, and Hive's ``\\t``, ``\\n`` and ``\\\\`` are unescaped."""
+ kind, text = self.peek()[:2]
+ if kind != "str" or len(text) < 2 or not text.endswith("'"):
+ return None
+ self.advance()
+ value = text[1:-1].replace("''", "'")
+ return re.sub(r"\\(.)", lambda m: {"t": "\t", "n": "\n"}.get(m.group(1), m.group(1)), value)
+
+ def dotted_name(self, max_parts):
+ """The dotted name that is next, right-aligned in a ``max_parts`` tuple: with 3,
+ ``t`` → ``(None, None, "t")`` and ``a.b.c`` → ``("a", "b", "c")``. None when no name is
+ next, a ``.`` has nothing after it, or the name has more than ``max_parts`` parts."""
+ parts = []
+ while True:
+ part = self.identifier()
+ if part is None:
+ return None
+ parts.append(part)
+ if not self.punct("."):
+ break
+ if len(parts) > max_parts:
+ return None
+ return (None,) * (max_parts - len(parts)) + tuple(parts)
+
+
+@dataclass(frozen=True)
+class TableReference:
+ """One ``FROM``/``JOIN`` target and where its text sits in the query."""
+
+ database: str | None # None when the reference names only the table
+ table: str
+ start: int
+ end: int
+ aliased: bool
+
+
+# After a table reference, these keywords start the next clause; anything else is an alias.
+_CLAUSE_KEYWORDS = frozenset(
+ "where on join inner left right full cross natural using group order limit offset having "
+ "union except intersect window qualify fetch with".split()
+)
+
+
+def _table_references(query):
+ """The ``FROM``/``JOIN`` targets of ``query``, in order, with CTE names left out.
+
+ ``SELECT u.id FROM "awsdatacatalog"."acme"."users" u JOIN orders ON ...`` yields
+ ``TableReference("acme", "users", 17, 48, aliased=True)`` and
+ ``TableReference(None, "orders", 56, 62, aliased=False)``: a catalog qualifier is dropped,
+ since Glue is the only catalog here, and a ``WITH users AS (...)`` name shadows a table.
+ """
+ cursor = _Cursor(query)
+ ctes = _cte_names(cursor)
+ cursor.reset()
+ references = []
+ while not cursor.at_end():
+ if not (cursor.keywords("from") or cursor.keywords("join")):
+ cursor.advance()
+ continue
+ start = cursor.peek()[2]
+ name = cursor.dotted_name(3)
+ if name is None:
+ continue
+ _, database, table = name # the catalog qualifier is dropped: Glue is the only catalog here
+ if database is None and table in ctes:
+ continue
+ end = cursor.tokens[cursor.i - 1][3]
+ next_kind, next_text = cursor.peek()[:2]
+ aliased = next_kind == "qname" or (next_kind == "name" and next_text not in _CLAUSE_KEYWORDS)
+ references.append(TableReference(database, table, start, end, aliased))
+ return references
+
+
+def _cte_names(cursor):
+ """Names bound by a top-level ``WITH name AS (...)``."""
+ names = set()
+ if not cursor.keywords("with"):
+ return names
+ while True:
+ name = cursor.identifier()
+ if name is None or not cursor.keywords("as") or not cursor.punct("("):
+ return names
+ names.add(name)
+ cursor.skip_group()
+ if not cursor.punct(","):
+ return names
+
+
+# ---- Table DDL ----
+
+_TEXT_INPUT_FORMAT = "org.apache.hadoop.mapred.TextInputFormat"
+_LAZY_SIMPLE_SERDE = "org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe"
+# STORED AS <format> → (InputFormat, OutputFormat, SerDe), as Athena writes them to Glue.
+_STORED_AS = {
+ "textfile": (_TEXT_INPUT_FORMAT, "org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat", _LAZY_SIMPLE_SERDE),
+ "parquet": (
+ "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",
+ ),
+ "orc": (
+ "org.apache.hadoop.hive.ql.io.orc.OrcInputFormat",
+ "org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat",
+ "org.apache.hadoop.hive.ql.io.orc.OrcSerde",
+ ),
+ "avro": (
+ "org.apache.hadoop.hive.ql.io.avro.AvroContainerInputFormat",
+ "org.apache.hadoop.hive.ql.io.avro.AvroContainerOutputFormat",
+ "org.apache.hadoop.hive.serde2.avro.AvroSerDe",
+ ),
+}
+# A ROW FORMAT SERDE table with no STORED AS is text written through IgnoreKeyTextOutputFormat.
+_SERDE_TEXT_OUTPUT_FORMAT = "org.apache.hadoop.hive.ql.io.IgnoreKeyTextOutputFormat"
+# ROW FORMAT DELIMITED <clause> TERMINATED BY / DEFINED AS 'c' → SerDe parameter.
+_DELIMITED = {
+ ("fields", "terminated", "by"): "field.delim",
+ ("escaped", "by"): "escape.delim",
+ ("collection", "items", "terminated", "by"): "collection.delim",
+ ("map", "keys", "terminated", "by"): "mapkey.delim",
+ ("lines", "terminated", "by"): "line.delim",
+ ("null", "defined", "as"): "serialization.null.format",
+}
+
+
+@dataclass(frozen=True)
+class CreateTable:
+ database: str | None # None when the statement names only the table
+ table: str
+ external: bool
+ columns: list = field(default_factory=list) # Glue column dicts: Name, Type, optional Comment
+ partition_keys: list = field(default_factory=list)
+ comment: str | None = None
+ location: str | None = None
+ input_format: str = _TEXT_INPUT_FORMAT
+ output_format: str = _STORED_AS["textfile"][1]
+ serde: str = _LAZY_SIMPLE_SERDE
+ serde_parameters: dict = field(default_factory=lambda: {"serialization.format": "1"})
+ table_properties: dict = field(default_factory=dict)
+ bucket_columns: list = field(default_factory=list)
+ number_of_buckets: int = -1
+ if_not_exists: bool = False
+
+ @property
+ def iceberg(self):
+ return self.table_properties.get("table_type", "").lower() == "iceberg"
+
+
+@dataclass(frozen=True)
+class DropTable:
+ database: str | None
+ table: str
+ if_exists: bool = False
+
+
+def _parse_ddl(query):
+ """The ``CreateTable`` or ``DropTable`` a statement is, or None.
+
+ None also covers a CREATE this does not model (CTAS, ``SORTED BY``, an unknown ``STORED AS``)
+ and anything followed by a second statement, so those reach the query engine as written.
+ """
+ cursor = _Cursor(query)
+ if cursor.tokens and cursor.tokens[-1][:2] == ("punct", ";"):
+ cursor.tokens.pop()
+ if any(token[:2] == ("punct", ";") for token in cursor.tokens):
+ return None
+ if cursor.keywords("drop", "table"):
+ if_exists = cursor.keywords("if", "exists")
+ name = cursor.dotted_name(2)
+ if name is None or not cursor.at_end():
+ return None
+ return DropTable(*name, if_exists=if_exists)
+ if not cursor.keywords("create"):
+ return None
+ external = cursor.keywords("external")
+ if not cursor.keywords("table"):
+ return None
+ if_not_exists = cursor.keywords("if", "not", "exists")
+ name = cursor.dotted_name(2)
+ columns = _column_list(cursor) if name else []
+ if not columns:
+ return None
+ clauses = {}
+ stored_as = row_format_serde = None
+ serde_parameters = {"serialization.format": "1"}
+ while not cursor.at_end():
+ if cursor.keywords("comment"):
+ clauses["comment"] = cursor.string()
+ elif cursor.keywords("partitioned", "by"):
+ clauses["partition_keys"] = _column_list(cursor) or None
+ elif cursor.keywords("clustered", "by"):
+ bucket_columns = _name_list(cursor)
+ buckets = cursor.number() if bucket_columns and cursor.keywords("into") else None
+ if buckets is None or not cursor.keywords("buckets"):
+ return None
+ clauses["bucket_columns"], clauses["number_of_buckets"] = bucket_columns, buckets
+ elif cursor.keywords("row", "format", "delimited"):
+ delimited = _delimited(cursor)
+ if delimited is None:
+ return None
+ serde_parameters.update(delimited)
+ elif cursor.keywords("row", "format", "serde"):
+ row_format_serde = cursor.string()
+ if row_format_serde is None:
+ return None
+ if cursor.keywords("with", "serdeproperties"):
+ properties = _property_list(cursor)
+ if properties is None:
+ return None
+ serde_parameters.update(properties)
+ elif cursor.keywords("with", "serdeproperties"):
+ properties = _property_list(cursor)
+ if properties is None:
+ return None
+ serde_parameters.update(properties)
+ elif cursor.keywords("stored", "as", "inputformat"):
+ input_format = cursor.string()
+ output_format = cursor.string() if cursor.keywords("outputformat") else None
+ if input_format is None or output_format is None:
+ return None
+ stored_as = (input_format, output_format, None)
+ elif cursor.keywords("stored", "as"):
+ stored_as = _STORED_AS.get(cursor.name() or "")
+ if stored_as is None:
+ return None
+ elif cursor.keywords("location"):
+ clauses["location"] = cursor.string()
+ elif cursor.keywords("tblproperties"):
+ clauses["table_properties"] = _property_list(cursor)
+ else:
+ return None
+ if any(value is None for value in clauses.values()):
+ return None
+ if stored_as is None:
+ input_format, output_format, serde = _STORED_AS["textfile"]
+ if row_format_serde:
+ output_format = _SERDE_TEXT_OUTPUT_FORMAT
+ else:
+ input_format, output_format, serde = stored_as
+ return CreateTable(
+ *name, external=external, columns=columns, input_format=input_format, output_format=output_format,
+ serde=row_format_serde or serde or _LAZY_SIMPLE_SERDE, serde_parameters=serde_parameters,
+ if_not_exists=if_not_exists, **clauses,
+ )
+
+
+def _column_list(cursor):
+ """``( name type [COMMENT 'text'] , … )`` → Glue column dicts; [] when malformed."""
+ if not cursor.punct("("):
+ return []
+ columns = []
+ while True:
+ name = cursor.identifier()
+ if name is None:
+ return []
+ type_start = type_end = None
+ comment = None
+ depth = 0
+ while not cursor.at_end():
+ kind, text, start, end = cursor.peek()
+ if depth == 0 and kind == "punct" and text in ",)":
+ break
+ if depth == 0 and kind == "name" and text == "comment":
+ cursor.advance()
+ comment = cursor.string()
+ if comment is None:
+ return []
+ continue
+ if kind == "punct" and text in "(<":
+ depth += 1
+ elif kind == "punct" and text in ")>":
+ depth -= 1
+ if type_start is None:
+ type_start = start
+ type_end = end
+ cursor.advance()
+ if type_start is None:
+ return []
+ column = {"Name": name, "Type": cursor.text[type_start:type_end].lower()}
+ if comment is not None:
+ column["Comment"] = comment
+ columns.append(column)
+ if cursor.punct(","):
+ continue
+ if cursor.punct(")"):
+ return columns
+ return []
+
+
+def _name_list(cursor):
+ """``( a , b )`` → ``["a", "b"]``; [] when malformed."""
+ if not cursor.punct("("):
+ return []
+ names = []
+ while (name := cursor.identifier()) is not None:
+ names.append(name)
+ if cursor.punct(")"):
+ return names
+ if not cursor.punct(","):
+ return []
+ return []
+
+
+def _property_list(cursor):
+ """``( 'k' = 'v' , … )`` → dict; None when malformed."""
+ if not cursor.punct("("):
+ return None
+ properties = {}
+ while True:
+ key = cursor.string()
+ value = cursor.string() if key is not None and cursor.punct("=") else None
+ if value is None:
+ return None
+ properties[key] = value
+ if cursor.punct(")"):
+ return properties
+ if not cursor.punct(","):
+ return None
+
+
+def _delimited(cursor):
+ """The SerDe parameters a ``ROW FORMAT DELIMITED`` clause sets; None when malformed.
+
+ ``FIELDS TERMINATED BY ','`` → ``{"field.delim": ",", "serialization.format": ","}``.
+ """
+ parameters = {}
+ while True:
+ for words, parameter in _DELIMITED.items():
+ if cursor.keywords(*words):
+ value = cursor.string()
+ if value is None:
+ return None
+ parameters[parameter] = value
+ break
+ else:
+ break
+ if "field.delim" in parameters:
+ parameters["serialization.format"] = parameters["field.delim"]
+ return parameters
+
+
+def _create_table_input(ddl):
+ """The Glue ``TableInput`` Athena writes for ``ddl``: TBLPROPERTIES and the table COMMENT
+ become Parameters, STORED AS / ROW FORMAT become the formats and SerDe."""
+ parameters = {"EXTERNAL": "TRUE", "transient_lastDdlTime": str(int(time.time())), **ddl.table_properties}
+ if ddl.comment is not None:
+ parameters["comment"] = ddl.comment
+ storage = {
+ "Columns": ddl.columns,
+ "InputFormat": ddl.input_format,
+ "OutputFormat": ddl.output_format,
+ "Compressed": False,
+ "NumberOfBuckets": ddl.number_of_buckets,
+ "SerdeInfo": {"SerializationLibrary": ddl.serde, "Parameters": ddl.serde_parameters},
+ "BucketColumns": ddl.bucket_columns,
+ "SortColumns": [],
+ "Parameters": {},
+ "SkewedInfo": {"SkewedColumnNames": [], "SkewedColumnValues": [], "SkewedColumnValueLocationMaps": {}},
+ "StoredAsSubDirectories": False,
+ }
+ if ddl.location:
+ storage["Location"] = ddl.location.rstrip("/")
+ return {
+ "Name": ddl.table,
+ "Owner": "hadoop",
+ "TableType": "EXTERNAL_TABLE",
+ "Parameters": parameters,
+ "StorageDescriptor": storage,
+ "PartitionKeys": ddl.partition_keys,
+ }
+
+
+def _data_format(table_data):
+ """The file format DuckDB reads a table as: its ``classification`` property when set, else the
+ one its InputFormat or SerDe names (``MapredParquetInputFormat`` → ``parquet``), else ``csv``."""
+ classification = (table_data.get("Parameters") or {}).get("classification")
+ if classification:
+ return classification
+ storage = table_data.get("StorageDescriptor") or {}
+ classes = f"{storage.get('InputFormat', '')} {(storage.get('SerdeInfo') or {}).get('SerializationLibrary', '')}".lower()
+ return next((fmt for fmt in ("parquet", "orc", "avro", "json") if fmt in classes), "csv")
+
+
# ---- Query Execution ----
@@ -344,6 +849,14 @@ def _start_query_execution(data):
).get("OutputLocation", "s3://athena-results/")
db = data.get("QueryExecutionContext", {}).get("Database", "default")
catalog = data.get("QueryExecutionContext", {}).get("Catalog", "AwsDataCatalog")
+ # Athena rejects any malformed statement here; with no Trino parser, only this DDL rule is
+ # checked at submission and other errors fail the execution instead.
+ ddl = _parse_ddl(query)
+ if isinstance(ddl, CreateTable) and not ddl.external and not ddl.iceberg:
+ return error_response_json(
+ "InvalidRequestException", "External keyword required for table type HIVE", 400,
+ extra={"AthenaErrorCode": "MALFORMED_QUERY"},
+ )
execution = {
"QueryExecutionId": query_id,
@@ -377,12 +890,12 @@ def _start_query_execution(data):
}
_executions[query_id] = execution
- asyncio.create_task(_execute_query(query_id, query, db))
+ asyncio.create_task(_execute_query(query_id, query, db, ddl))
return json_response({"QueryExecutionId": query_id})
-async def _execute_query(query_id, query, database):
+async def _execute_query(query_id, query, database, ddl):
execution = _executions.get(query_id)
if not execution:
return
@@ -393,7 +906,9 @@ async def _execute_query(query_id, query, database):
try:
engine = get_athena_engine()
- if engine == "duckdb":
+ if ddl is not None:
+ results = _run_ddl(ddl, database)
+ elif engine == "duckdb":
results = await _run_duckdb(query, database)
else:
results = _mock_query_results(query)
@@ -464,45 +979,98 @@ async def _run_duckdb(query, database):
async def _rewrite_data_paths(query, database):
- from ministack.services import glue as glue_svc
+ """Replace each Glue table reference with the DuckDB relation that reads its local S3 data.
+
+ With Glue table ``acme.users`` at ``s3://acme-data/users/`` holding CSV::
+
+ SELECT u.id FROM "awsdatacatalog"."acme"."users" u WHERE u.id > 1
+ SELECT users.id FROM users WHERE users.id > 1
- # Skip identifiers that look like function calls (read_csv('s3://...'))
- # or already contain a path separator. Restrict to bare table references
- # — optional database qualifier, then table name — letters/digits/dots/
- # underscores/hyphens. Quoted identifiers (e.g. "my-db"."my-table") are
- # left to a future pass.
- pattern = r'(?:FROM|JOIN)\s+([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)?)\b'
- tables_to_resolve = re.findall(pattern, query, re.IGNORECASE)
+ become::
- for full_name in tables_to_resolve:
- parts = full_name.split(".")
- db_name, table_name = (parts[0], parts[1]) if len(parts) > 1 else (database or "default", parts[0])
+ SELECT u.id FROM '<data dir>/<account>/acme-data/users/**/*.csv' u WHERE u.id > 1
+ SELECT users.id FROM '<data dir>/<account>/acme-data/users/**/*.csv' AS "users" WHERE users.id > 1
+
+ The second gains an alias so ``users.id`` still resolves once the name is a path. A table
+ not in Glue is left as written for DuckDB to reject.
+ """
+ from ministack.services import glue as glue_svc
+
+ account_id = get_account_id()
+ edits = []
+ for ref in _table_references(query):
+ db_name = ref.database or database or "default"
# Read directly from glue's internal store rather than going through
# the HTTP handler. The store is account-scoped via AccountScopedDict
# and reads the current request's contextvar, so multi-tenancy is
# preserved without crafting synthetic Authorization headers.
- table_data = glue_svc._tables.get(f"{db_name}/{table_name}")
+ table_data = glue_svc._tables.get(f"{db_name}/{ref.table}")
if not table_data:
continue
-
- sd = table_data.get("StorageDescriptor", {})
- s3_location = sd.get("Location")
+ s3_location = (table_data.get("StorageDescriptor") or {}).get("Location")
if not s3_location:
continue
- account_id = get_account_id()
p = urlparse(s3_location)
stripped = f"{p.netloc}{p.path}".rstrip("/")
- classification = table_data.get("Parameters", {}).get("classification", "csv")
+ local_dir = f"{ATHENA_DATA_DIR}/{account_id}/{stripped}"
+ if glob.glob(f"{local_dir}/**/*", recursive=True):
+ relation = f"'{local_dir}/**/*.{_data_format(table_data)}'" # DuckDB reads the files, or reports why not
+ else:
+ relation = _empty_relation(table_data)
+ alias = "" if ref.aliased else f' AS "{ref.table}"'
+ edits.append((ref.start, ref.end, relation + alias))
+
+ for span_start, span_end, replacement in reversed(edits):
+ query = query[:span_start] + replacement + query[span_end:]
+ return _rewrite_s3_paths(query)
- local_path = f"{ATHENA_DATA_DIR}/{account_id}/{stripped}"
- duck_path = f"{local_path}/**/*.{classification}"
- query = re.sub(rf"\b{re.escape(full_name)}\b", f"'{duck_path}'", query)
+_DUCKDB_TYPE_BY_ATHENA = {
+ "boolean": "BOOLEAN", "tinyint": "TINYINT", "smallint": "SMALLINT", "int": "INTEGER", "integer": "INTEGER",
+ "bigint": "BIGINT", "float": "FLOAT", "real": "FLOAT", "double": "DOUBLE", "date": "DATE",
+ "timestamp": "TIMESTAMP", "binary": "BLOB", "varbinary": "BLOB",
+}
- query = _rewrite_s3_paths(query)
- return query
+
+def _empty_relation(table_data):
+ """Zero rows with the table's Glue columns and partition keys; complex types read as VARCHAR."""
+ columns = ((table_data.get("StorageDescriptor") or {}).get("Columns") or []) + (table_data.get("PartitionKeys") or [])
+ if not columns:
+ return "(SELECT 1 WHERE FALSE)"
+ projected = []
+ for column in columns:
+ base = str(column.get("Type", "string")).lower().split("(")[0].strip()
+ duck_type = "DECIMAL" if base == "decimal" else _DUCKDB_TYPE_BY_ATHENA.get(base, "VARCHAR")
+ name = str(column.get("Name", "")).replace('"', '""')
+ projected.append(f'CAST(NULL AS {duck_type}) AS "{name}"')
+ return f"(SELECT {', '.join(projected)} WHERE FALSE)"
+
+
+def _run_ddl(ddl, database):
+ from ministack.services import glue as glue_svc
+
+ db_name = ddl.database or database or "default"
+ if isinstance(ddl, DropTable):
+ if f"{db_name}/{ddl.table}" not in glue_svc._tables:
+ if ddl.if_exists:
+ return {"columns": [], "rows": [], "column_types": []}
+ raise ValueError(f"Table '{db_name}.{ddl.table}' does not exist")
+ glue_svc._delete_table({"DatabaseName": db_name, "Name": ddl.table})
+ return {"columns": [], "rows": [], "column_types": []}
+ if ddl.iceberg:
+ raise ValueError("NOT_SUPPORTED: Iceberg tables are not supported")
+ if db_name not in glue_svc._databases:
+ raise ValueError(f"Schema '{db_name}' does not exist")
+ if f"{db_name}/{ddl.table}" in glue_svc._tables:
+ if ddl.if_not_exists:
+ return {"columns": [], "rows": [], "column_types": []}
+ raise ValueError(f"Table '{db_name}.{ddl.table}' already exists")
+ status, _, body = glue_svc._create_table({"DatabaseName": db_name, "TableInput": _create_table_input(ddl)})
+ if status >= 300:
+ raise ValueError(json.loads(body).get("message", "Glue CreateTable failed"))
+ return {"columns": [], "rows": [], "column_types": []}
def _rewrite_s3_paths(query):
@@ -627,13 +1195,11 @@ def _mock_query_results(query):
def _detect_statement_type(query):
- q = query.strip().upper()
- if q.startswith("SELECT") or q.startswith("WITH"):
+ first = next((text for kind, text, _, _ in _sql_tokens(query) if kind != "punct" or text != "("), "")
+ if first in ("select", "with", "insert", "delete", "update", "merge"):
return "DML"
- if q.startswith(("CREATE", "DROP", "ALTER")):
+ if first in ("create", "drop", "alter"):
return "DDL"
- if q.startswith(("INSERT", "DELETE", "UPDATE", "MERGE")):
- return "DML"
return "UTILITY"
@@ -684,7 +1250,9 @@ def _get_query_results(data):
page_rows = rows[start_idx : start_idx + max_results]
result_rows = []
- result_rows.append({"Data": [{"VarCharValue": col} for col in columns]})
+ # Only a DML result's first page carries Athena's header row of column names.
+ if execution.get("StatementType") == "DML" and start_idx == 0:
+ result_rows.append({"Data": [{"VarCharValue": col} for col in columns]})
for row in page_rows:
result_rows.append(
{"Data": [{"VarCharValue": str(v) if v is not None else ""} for v in row]}
@@ -1074,7 +1642,34 @@ def _list_prepared_statements(data):
return json_response({"PreparedStatements": stmts})
-# ---- Table Metadata (stubs) ----
+# ---- Databases and Table Metadata (Glue Data Catalog) ----
+
+
+def _athena_database(db):
+ return {"Name": db["Name"], "Description": db.get("Description", ""), "Parameters": db.get("Parameters") or {}}
+
+
+def _get_database(data):
+ from ministack.services import glue as glue_svc
+ if data.get("CatalogName", "AwsDataCatalog") not in _data_catalogs:
+ return error_response_json("MetadataException", f"Catalog {data.get('CatalogName')} not found", 400)
+ db = glue_svc._databases.get(data.get("DatabaseName", ""))
+ if not db:
+ return error_response_json("MetadataException", f"Database {data.get('DatabaseName')} not found", 400)
+ return json_response({"Database": _athena_database(db)})
+
+
+def _list_databases(data):
+ from ministack.services import glue as glue_svc
+ if data.get("CatalogName", "AwsDataCatalog") not in _data_catalogs:
+ return error_response_json("MetadataException", f"Catalog {data.get('CatalogName')} not found", 400)
+ databases = [_athena_database(db) for db in glue_svc._databases.values()]
+ start = int(data.get("NextToken") or 0)
+ end = start + int(data.get("MaxResults") or 50)
+ response = {"DatabaseList": databases[start:end]}
+ if end < len(databases):
+ response["NextToken"] = str(end)
+ return json_response(response)
def _glue_col(c):
diff --git a/tests/conftest.py b/tests/conftest.py
index 2705beb3..8c56a354 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -112,6 +112,10 @@ _SERIAL_TESTS = {
"tests/test_rds.py::test_rds_pg_two_replicating_readers_provision_source_once",
"tests/test_athena.py::test_athena_engine_mock_via_config",
"tests/test_athena.py::test_athena_mixed_glue_and_s3_uri",
+ "tests/test_athena.py::test_athena_resolves_quoted_and_catalog_qualified_tables",
+ "tests/test_athena.py::test_athena_header_row_only_on_first_page",
+ "tests/test_athena.py::test_athena_create_and_drop_table_apply_to_glue",
+ "tests/test_athena.py::test_athena_reads_a_parquet_table_created_without_classification",
"tests/test_ec2.py::test_ec2_create_default_vpc",
"tests/test_eks.py::test_eks_cfn_cluster",
"tests/test_eks.py::test_eks_create_describe_delete_cluster",
diff --git a/tests/test_athena.py b/tests/test_athena.py
index fd88c6d1..6ab4ceae 100644
--- a/tests/test_athena.py
+++ b/tests/test_athena.py
@@ -858,3 +858,361 @@ def test_athena_mixed_glue_and_s3_uri(athena, glue, monkeypatch, tmp_path):
@pytest.fixture(scope="module", autouse=True)
def _create_s3_results_bucket(s3):
s3.create_bucket(Bucket="athena-results")
+
+
+def test_athena_list_and_get_databases_from_glue(athena, glue):
+ """ListDatabases / GetDatabase read the Glue Data Catalog, so a catalog client that
+ walks databases before tables sees what Glue holds."""
+ glue.create_database(DatabaseInput={"Name": "ath_db_list", "Description": "listed"})
+ names = [d["Name"] for d in athena.list_databases(CatalogName="AwsDataCatalog")["DatabaseList"]]
+ assert "ath_db_list" in names
+ got = athena.get_database(CatalogName="AwsDataCatalog", DatabaseName="ath_db_list")["Database"]
+ assert got["Name"] == "ath_db_list" and got["Description"] == "listed"
+ with pytest.raises(ClientError) as err:
+ athena.get_database(CatalogName="AwsDataCatalog", DatabaseName="ath_db_missing")
+ assert err.value.response["Error"]["Code"] == "MetadataException"
+ with pytest.raises(ClientError):
+ athena.list_databases(CatalogName="no_such_catalog")
+ page = athena.list_databases(CatalogName="AwsDataCatalog", MaxResults=1)
+ assert len(page["DatabaseList"]) == 1 and "NextToken" in page
+
+
+def test_athena_workgroup_reports_engine_version(athena):
+ version = athena.get_work_group(WorkGroup="primary")["WorkGroup"]["Configuration"]["EngineVersion"]
+ assert version["EffectiveEngineVersion"] == "Athena engine version 3"
+
+
+def _run_to_completion(athena, query, database):
+ query_id = athena.start_query_execution(
+ QueryString=query, QueryExecutionContext={"Database": database},
+ )["QueryExecutionId"]
+ for _ in range(20):
+ execution = athena.get_query_execution(QueryExecutionId=query_id)["QueryExecution"]
+ if execution["Status"]["State"] in ("SUCCEEDED", "FAILED", "CANCELLED"):
+ break
+ time.sleep(0.2)
+ return query_id, execution
+
+
+def _seed_users(monkeypatch, tmp_path, glue, db_name):
+ from ministack.services import s3 as s3mod
+ monkeypatch.setattr(s3mod, "DATA_DIR", str(tmp_path))
+ monkeypatch.setattr(s3mod, "S3_PERSIST", True)
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+ req = urllib.request.Request(
+ f"{endpoint}/_ministack/config",
+ data=json.dumps({"athena.ATHENA_DATA_DIR": str(tmp_path)}).encode(),
+ headers={"Content-Type": "application/json"}, method="POST",
+ )
+ urllib.request.urlopen(req, timeout=5)
+ s3mod._persist_object("athena-results", f"{db_name}/users/data.csv", b"id,email\n1,[email protected]\n2,[email protected]")
+ glue.create_database(DatabaseInput={"Name": db_name})
+ glue.create_table(DatabaseName=db_name, TableInput={
+ "Name": "users",
+ "StorageDescriptor": {
+ "Columns": [{"Name": "id", "Type": "bigint"}, {"Name": "email", "Type": "string"}],
+ "Location": f"s3://athena-results/{db_name}/users/",
+ },
+ "Parameters": {"classification": "csv"},
+ })
+
+
+def test_athena_resolves_quoted_and_catalog_qualified_tables(athena, glue, monkeypatch, tmp_path):
+ """Trino clients emit "catalog"."db"."table" AS "alias"; the reference resolves to the
+ table's data and a reference without an alias keeps resolving qualified columns."""
+ db_name = "ath_quoted_db"
+ _seed_users(monkeypatch, tmp_path, glue, db_name)
+ query = (f'SELECT "users"."id" AS "id", "users"."email" AS "email" '
+ f'FROM "awsdatacatalog"."{db_name}"."users" AS "users" ORDER BY "users"."id"')
+ query_id, execution = _run_to_completion(athena, query, db_name)
+ assert execution["Status"]["State"] == "SUCCEEDED", execution["Status"]
+ rows = athena.get_query_results(QueryExecutionId=query_id)["ResultSet"]["Rows"]
+ assert [d["VarCharValue"] for d in rows[0]["Data"]] == ["id", "email"]
+ assert [d["VarCharValue"] for d in rows[1]["Data"]] == ["1", "[email protected]"]
+
+ query_id, execution = _run_to_completion(athena, "SELECT users.email FROM users WHERE users.id = 2", db_name)
+ assert execution["Status"]["State"] == "SUCCEEDED", execution["Status"]
+ rows = athena.get_query_results(QueryExecutionId=query_id)["ResultSet"]["Rows"]
+ assert [d["VarCharValue"] for d in rows[1]["Data"]] == ["[email protected]"]
+
+ # A CTE named like the Glue table shadows it, and a leading comment does not hide the header row.
+ query = "-- note\nWITH users AS (SELECT 99 AS id) SELECT users.id FROM users"
+ query_id, execution = _run_to_completion(athena, query, db_name)
+ assert execution["Status"]["State"] == "SUCCEEDED", execution["Status"]
+ assert execution["StatementType"] == "DML"
+ rows = athena.get_query_results(QueryExecutionId=query_id)["ResultSet"]["Rows"]
+ assert [[d["VarCharValue"] for d in r["Data"]] for r in rows] == [["id"], ["99"]]
+
+
+def test_athena_header_row_only_on_first_page(athena, glue, monkeypatch, tmp_path):
+ db_name = "ath_paged_db"
+ _seed_users(monkeypatch, tmp_path, glue, db_name)
+ query_id, execution = _run_to_completion(athena, "SELECT id FROM users ORDER BY id", db_name)
+ assert execution["Status"]["State"] == "SUCCEEDED", execution["Status"]
+ first = athena.get_query_results(QueryExecutionId=query_id, MaxResults=1)
+ assert [r["Data"][0]["VarCharValue"] for r in first["ResultSet"]["Rows"]] == ["id", "1"]
+ second = athena.get_query_results(QueryExecutionId=query_id, MaxResults=1, NextToken=first["NextToken"])
+ assert [r["Data"][0]["VarCharValue"] for r in second["ResultSet"]["Rows"]] == ["2"]
+
+
+def test_athena_create_and_drop_table_apply_to_glue(athena, glue, monkeypatch, tmp_path):
+ """CREATE EXTERNAL TABLE registers the table in Glue (so metadata calls see it), an empty
+ location reads as zero rows, and DROP TABLE removes it."""
+ db_name = "ath_ddl_db"
+ _seed_users(monkeypatch, tmp_path, glue, db_name)
+ ddl = "CREATE EXTERNAL TABLE events (id INT, note STRING COMMENT 'free text') LOCATION 's3://athena-results/ath_ddl_db/events/'"
+ _, execution = _run_to_completion(athena, ddl, db_name)
+ assert execution["Status"]["State"] == "SUCCEEDED", execution["Status"]
+ assert execution["StatementType"] == "DDL"
+ md = athena.get_table_metadata(CatalogName="AwsDataCatalog", DatabaseName=db_name, TableName="events")["TableMetadata"]
+ assert [(c["Name"], c["Type"]) for c in md["Columns"]] == [("id", "int"), ("note", "string")]
+ assert md["Columns"][1]["Comment"] == "free text"
+
+ query_id, execution = _run_to_completion(athena, "SELECT id, note FROM events", db_name)
+ assert execution["Status"]["State"] == "SUCCEEDED", execution["Status"]
+ result = athena.get_query_results(QueryExecutionId=query_id)["ResultSet"]
+ assert [c["Name"] for c in result["ResultSetMetadata"]["ColumnInfo"]] == ["id", "note"]
+ assert len(result["Rows"]) == 1 # header only
+
+ _, execution = _run_to_completion(athena, "DROP TABLE events", db_name)
+ assert execution["Status"]["State"] == "SUCCEEDED", execution["Status"]
+ listed = athena.list_table_metadata(CatalogName="AwsDataCatalog", DatabaseName=db_name)["TableMetadataList"]
+ assert [t["Name"] for t in listed] == ["users"]
+ with pytest.raises(ClientError):
+ glue.get_table(DatabaseName=db_name, Name="events")
+ _, execution = _run_to_completion(athena, "DROP TABLE events", db_name)
+ assert execution["Status"]["State"] == "FAILED"
+
+
+def test_athena_create_table_requires_external(athena, glue):
+ """Athena rejects a Hive CREATE TABLE without EXTERNAL at submission, not as a failed execution."""
+ glue.create_database(DatabaseInput={"Name": "ath_managed_db"})
+ with pytest.raises(ClientError) as err:
+ athena.start_query_execution(
+ QueryString="CREATE TABLE t (a int) LOCATION 's3://athena-results/t/'",
+ QueryExecutionContext={"Database": "ath_managed_db"},
+ )
+ assert err.value.response["Error"]["Code"] == "InvalidRequestException"
+ assert err.value.response["Error"]["Message"] == "External keyword required for table type HIVE"
+ assert err.value.response["AthenaErrorCode"] == "MALFORMED_QUERY"
+ with pytest.raises(ClientError):
+ glue.get_table(DatabaseName="ath_managed_db", Name="t")
+
+
+def test_athena_create_iceberg_table_is_not_supported(athena, glue):
+ glue.create_database(DatabaseInput={"Name": "ath_iceberg_db"})
+ _, execution = _run_to_completion(
+ athena,
+ "CREATE TABLE t (a int) LOCATION 's3://athena-results/ice/' TBLPROPERTIES ('table_type'='ICEBERG')",
+ "ath_iceberg_db",
+ )
+ assert execution["Status"]["State"] == "FAILED"
+ assert "NOT_SUPPORTED" in execution["Status"]["StateChangeReason"]
+
+
+def test_athena_create_table_writes_the_glue_table_athena_does(athena, glue):
+ glue.create_database(DatabaseInput={"Name": "ath_shape_db"})
+ ddl = (
+ "CREATE EXTERNAL TABLE p (a int COMMENT 'ca', b string) COMMENT 'table comment' "
+ "PARTITIONED BY (dt string) STORED AS PARQUET LOCATION 's3://athena-results/parquet/' "
+ "TBLPROPERTIES ('classification'='parquet', 'x'='y')"
+ )
+ _, execution = _run_to_completion(athena, ddl, "ath_shape_db")
+ assert execution["Status"]["State"] == "SUCCEEDED", execution["Status"]
+ table = glue.get_table(DatabaseName="ath_shape_db", Name="p")["Table"]
+ assert table["Owner"] == "hadoop" and table["TableType"] == "EXTERNAL_TABLE"
+ assert "Description" not in table or not table["Description"]
+ parameters = table["Parameters"]
+ assert parameters.pop("transient_lastDdlTime").isdigit()
+ assert parameters == {"EXTERNAL": "TRUE", "classification": "parquet", "x": "y", "comment": "table comment"}
+ assert table["PartitionKeys"] == [{"Name": "dt", "Type": "string"}]
+ storage = table["StorageDescriptor"]
+ assert storage["Columns"] == [{"Name": "a", "Type": "int", "Comment": "ca"}, {"Name": "b", "Type": "string"}]
+ assert storage["Location"] == "s3://athena-results/parquet"
+ assert storage["InputFormat"] == "org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat"
+ assert storage["OutputFormat"] == "org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat"
+ assert storage["SerdeInfo"] == {
+ "SerializationLibrary": "org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe",
+ "Parameters": {"serialization.format": "1"},
+ }
+ assert storage["NumberOfBuckets"] == -1 and storage["Compressed"] is False
+
+ _, execution = _run_to_completion(
+ athena,
+ "CREATE EXTERNAL TABLE d (a int, b string) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' "
+ "LOCATION 's3://athena-results/delim/'",
+ "ath_shape_db",
+ )
+ assert execution["Status"]["State"] == "SUCCEEDED", execution["Status"]
+ storage = glue.get_table(DatabaseName="ath_shape_db", Name="d")["Table"]["StorageDescriptor"]
+ assert storage["InputFormat"] == "org.apache.hadoop.mapred.TextInputFormat"
+ assert storage["OutputFormat"] == "org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat"
+ assert storage["SerdeInfo"] == {
+ "SerializationLibrary": "org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe",
+ "Parameters": {"serialization.format": ",", "field.delim": ","},
+ }
+
+
+def test_athena_reads_a_parquet_table_created_without_classification(
+ athena, glue, s3, persisted_parquet_store, tmp_path,
+):
+ """A table's format comes from its InputFormat when no classification property names it."""
+ suffix = _uuid_mod.uuid4().hex[:10]
+ bucket, database = f"athena-ddl-parquet-{suffix}", f"ddl_parquet_{suffix}"
+ s3.create_bucket(Bucket=bucket)
+ glue.create_database(DatabaseInput={"Name": database})
+ parquet = tmp_path / "items.parquet"
+ with duckdb.connect() as connection:
+ connection.execute("COPY (SELECT * FROM (VALUES (1), (2)) v(id)) TO '%s' (FORMAT PARQUET)" % parquet)
+ persisted_parquet_store._persist_object(bucket, "data/items.parquet", parquet.read_bytes())
+ _, execution = _run_to_completion(
+ athena, f"CREATE EXTERNAL TABLE items (id int) STORED AS PARQUET LOCATION 's3://{bucket}/data/'", database,
+ )
+ assert execution["Status"]["State"] == "SUCCEEDED", execution["Status"]
+ assert "classification" not in glue.get_table(DatabaseName=database, Name="items")["Table"]["Parameters"]
+ query_id, execution = _run_to_completion(athena, "SELECT id FROM items ORDER BY id", database)
+ assert execution["Status"]["State"] == "SUCCEEDED", execution["Status"]
+ rows = athena.get_query_results(QueryExecutionId=query_id)["ResultSet"]["Rows"]
+ assert [row["Data"][0]["VarCharValue"] for row in rows] == ["id", "1", "2"]
+
+
+# ---- DDL and table-reference parsing (in-process, no server) ----
+
+
+def test_parse_create_external_table_with_location_and_comment():
+ from ministack.services.athena import CreateTable, _parse_ddl
+
+ ddl = _parse_ddl(
+ "CREATE EXTERNAL TABLE events (id INT, note STRING COMMENT 'free text') "
+ "LOCATION 's3://bucket/db/events/'"
+ )
+ assert ddl == CreateTable(
+ None, "events", external=True,
+ columns=[{"Name": "id", "Type": "int"}, {"Name": "note", "Type": "string", "Comment": "free text"}],
+ location="s3://bucket/db/events/",
+ )
+
+
+def test_parse_create_table_if_not_exists_qualified_and_quoted():
+ from ministack.services.athena import _parse_ddl
+
+ ddl = _parse_ddl('CREATE TABLE IF NOT EXISTS `my db`."Users" ("Id" bigint)')
+ assert ddl.if_not_exists is True and ddl.external is False
+ assert (ddl.database, ddl.table) == ("my db", "Users")
+ assert ddl.columns == [{"Name": "Id", "Type": "bigint"}]
+
+
[email protected]("clause, input_format, output_format, serde", [
+ ("", "org.apache.hadoop.mapred.TextInputFormat", "org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat",
+ "org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe"),
+ ("STORED AS orc", "org.apache.hadoop.hive.ql.io.orc.OrcInputFormat", "org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat",
+ "org.apache.hadoop.hive.ql.io.orc.OrcSerde"),
+ ("STORED AS INPUTFORMAT 'in.Format' OUTPUTFORMAT 'out.Format'", "in.Format", "out.Format",
+ "org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe"),
+ ("ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'", "org.apache.hadoop.mapred.TextInputFormat",
+ "org.apache.hadoop.hive.ql.io.IgnoreKeyTextOutputFormat", "org.openx.data.jsonserde.JsonSerDe"),
+])
+def test_parse_storage_clauses_map_to_athena_formats(clause, input_format, output_format, serde):
+ from ministack.services.athena import _parse_ddl
+
+ ddl = _parse_ddl(f"CREATE EXTERNAL TABLE t (a int) {clause} LOCATION 's3://b/t/'")
+ assert (ddl.input_format, ddl.output_format, ddl.serde) == (input_format, output_format, serde)
+
+
+def test_parse_serde_properties_delimiters_and_buckets():
+ from ministack.services.athena import _parse_ddl
+
+ ddl = _parse_ddl(
+ "CREATE EXTERNAL TABLE t (a int) CLUSTERED BY (a) INTO 4 BUCKETS "
+ "ROW FORMAT DELIMITED FIELDS TERMINATED BY '\\t' LINES TERMINATED BY '\\n' "
+ "TBLPROPERTIES ('skip.header.line.count'='1')"
+ )
+ assert ddl.serde_parameters == {"serialization.format": "\t", "field.delim": "\t", "line.delim": "\n"}
+ assert (ddl.bucket_columns, ddl.number_of_buckets) == (["a"], 4)
+ assert ddl.table_properties == {"skip.header.line.count": "1"}
+ ddl = _parse_ddl(
+ "CREATE EXTERNAL TABLE t (a int) ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe' "
+ "WITH SERDEPROPERTIES ('ignore.malformed.json'='true')"
+ )
+ assert ddl.serde_parameters == {"serialization.format": "1", "ignore.malformed.json": "true"}
+
+
+def test_parse_iceberg_table_properties():
+ from ministack.services.athena import _parse_ddl
+
+ assert _parse_ddl("CREATE TABLE t (a int) TBLPROPERTIES ('table_type'='ICEBERG')").iceberg is True
+ assert _parse_ddl("CREATE EXTERNAL TABLE t (a int)").iceberg is False
+
+
+ "SELECT 1",
+ "CREATE TABLE t ()", # no columns
+ "CREATE TABLE t (id)", # column without a type
+ "CREATE TABLE t (id int", # unclosed
+ "CREATE TABLE t AS SELECT 1", # CTAS
+ "CREATE TABLE t (a int); DROP TABLE victim", # two statements
+ "CREATE TABLE t (a int) STORED AS SEQUENCEFILE", # format not modeled
+ "CREATE TABLE t (a int) CLUSTERED BY (a) SORTED BY (a) INTO 2 BUCKETS",
+ "CREATE TABLE t (a int) LOCATION 's3://b/t/' SOMETHING ELSE",
+ "CREATE DATABASE db",
+ "ALTER TABLE t ADD COLUMNS (x int)",
+ "DROP TABLE",
+ "DROP TABLE a b",
+ "DROP TABLE a; DROP TABLE b",
+])
+def test_parse_unmodeled_statements_return_none(query):
+ from ministack.services.athena import _parse_ddl
+
+ assert _parse_ddl(query) is None
+
+
+def test_parse_column_types_nested_and_precise():
+ from ministack.services.athena import _parse_ddl
+
+ ddl = _parse_ddl(
+ "CREATE TABLE t (id int, tags array<string>, geo struct<lat:double,lng:double>, "
+ "m map<string,int>, amount DECIMAL(10, 2))"
+ )
+ assert [c["Type"] for c in ddl.columns] == [
+ "int", "array<string>", "struct<lat:double,lng:double>", "map<string,int>", "decimal(10, 2)",
+ ]
+
+
+def test_parse_literals_and_comments_are_not_structure():
+ from ministack.services.athena import _parse_ddl
+
+ ddl = _parse_ddl(
+ "create external table t (a int COMMENT 'has, a comma and a )', b string) -- trailing (comment\n"
+ "LOCATION 's3://b/it''s/'"
+ )
+ assert [c["Name"] for c in ddl.columns] == ["a", "b"]
+ assert ddl.columns[0]["Comment"] == "has, a comma and a )"
+ assert ddl.location == "s3://b/it's/"
+
+
+def test_parse_drop_table():
+ from ministack.services.athena import DropTable, _parse_ddl
+
+ assert _parse_ddl("DROP TABLE events") == DropTable(None, "events")
+ assert _parse_ddl("drop table if exists db.events;") == DropTable("db", "events", if_exists=True)
+
+
+def test_table_references_qualified_quoted_and_aliased():
+ from ministack.services.athena import TableReference, _table_references
+
+ query = 'SELECT u.id FROM "awsdatacatalog"."acme"."users" u JOIN orders ON u.id = orders.uid'
+ refs = _table_references(query)
+ assert refs == [
+ TableReference("acme", "users", query.index('"awsdatacatalog"'), query.index(" u JOIN"), aliased=True),
+ TableReference(None, "orders", query.index("orders ON"), query.index(" ON u.id"), aliased=False),
+ ]
+
+
+def test_table_references_skip_ctes_and_keep_clause_keywords_unaliased():
+ from ministack.services.athena import _table_references
+
+ refs = _table_references("WITH users AS (SELECT 1 AS id) SELECT * FROM users JOIN acme.events WHERE 1 = 1")
+ assert [(r.database, r.table, r.aliased) for r in refs] == [("acme", "events", False)]
+ assert _table_references("SELECT 1") == []
+ assert _table_references("SELECT 1 FROM a.b.c.d") == []
+ assert [r.aliased for r in _table_references('SELECT * FROM t AS "x" LIMIT 1')] == [True]