Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(athena): glue catalog integration and s3 result persistence (#524)
Max Kavaliou92b832b8929d
diff --git a/ministack/services/athena.py b/ministack/services/athena.pyindex cd9d84c6..3ba16170 100644--- a/ministack/services/athena.py+++ b/ministack/services/athena.py@@ -12,14 +12,19 @@ Supports: StartQueryExecution, GetQueryExecution, GetQueryResults,GetTableMetadata, ListTableMetadata,TagResource, UntagResource, ListTagsForResource."""-+import asyncioimport copy+import csv+import ioimport jsonimport loggingimport osimport reimport threadingimport time+import xml.etree.ElementTree as ET+from datetime import date+from urllib.parse import urlparsefrom ministack.core.persistence import PERSIST_STATE, load_statefrom ministack.core.responses import (@@ -36,6 +41,7 @@ logger = logging.getLogger("athena")REGION = os.environ.get("MINISTACK_REGION", "us-east-1")S3_DATA_DIR = os.environ.get("S3_DATA_DIR", "/tmp/ministack-data/s3")ATHENA_ENGINE = os.environ.get("ATHENA_ENGINE", "auto") # "auto" | "duckdb" | "mock"+ATHENA_DATA_DIR = S3_DATA_DIRdef get_athena_engine():@@ -270,15 +276,12 @@ def _start_query_execution(data):}_executions[query_id] = execution- thread = threading.Thread(- target=_execute_query, args=(query_id, query, db), daemon=True- )- thread.start()+ asyncio.create_task(_execute_query(query_id, query, db))return json_response({"QueryExecutionId": query_id})-def _execute_query(query_id, query, database):+async def _execute_query(query_id, query, database):execution = _executions.get(query_id)if not execution:return@@ -290,7 +293,7 @@ def _execute_query(query_id, query, database):engine = get_athena_engine()if engine == "duckdb":- results = _run_duckdb(query, database)+ results = await _run_duckdb(query, database)else:results = _mock_query_results(query)@@ -307,6 +310,8 @@ def _execute_query(query_id, query, database):execution["Statistics"]["DataScannedInBytes"] = sum(len(str(row)) for row in results.get("rows", []))++ await _save_query_results(query_id)except Exception as e:logger.error("Athena query %s failed: %s", query_id, e)execution["Status"]["State"] = "FAILED"@@ -316,11 +321,11 @@ def _execute_query(query_id, query, database):execution["Status"]["CompletionDateTime"] = int(time.time())-def _run_duckdb(query, database):+async def _run_duckdb(query, database):import duckdb-conn = duckdb.connect(":memory:")- rewritten = _rewrite_s3_paths(query)++ rewritten = await _rewrite_data_paths(query, database)try:result = conn.execute(rewritten)@@ -348,6 +353,43 @@ def _run_duckdb(query, database):raise e+async def _rewrite_data_paths(query, database):+ from ministack.services import glue as glue_svc++ pattern = r'(?:FROM|JOIN)\s+([a-zA-Z0-9_".\-/]+(?:\(.*?\))?)'+ tables_to_resolve = re.findall(pattern, query, re.IGNORECASE)++ for full_name in tables_to_resolve:+ if "/" in full_name or "(" in full_name:+ continue++ parts = full_name.split(".")+ db_name, table_name = (parts[0], parts[1]) if len(parts) > 1 else (database or "default", parts[0])++ body = json.dumps({"DatabaseName": db_name, "Name": table_name}).encode("utf-8")+ headers = {"x-amz-target": "AWSGlue.GetTable"}+ status, _, response_body = await glue_svc.handle_request("POST", "/", headers, body, {})++ if status == 200:+ table_data = json.loads(response_body).get("Table", {})+ sd = table_data.get('StorageDescriptor', {})+ s3_location = sd.get("Location")++ if s3_location:+ 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_path = f"{ATHENA_DATA_DIR}/{account_id}/{stripped}"+ duck_path = f"{local_path}/**/*.{classification}"++ query = re.sub(rf"{re.escape(full_name)}", f"'{duck_path}'", query)++ query = _rewrite_s3_paths(query)+ return query++def _rewrite_s3_paths(query):"""Replace s3://bucket/key references with local file paths.Handles: quoted strings, read_csv/read_parquet/read_json function args,@@ -364,9 +406,10 @@ def _rewrite_s3_paths(query):elif stripped.startswith("s3a://"):stripped = stripped[6:]parts = stripped.split("/", 1)+ account_id = get_account_id()bucket = parts[0]key = parts[1] if len(parts) > 1 else ""- local_path = os.path.join(S3_DATA_DIR, bucket, key)+ local_path = os.path.join(ATHENA_DATA_DIR, account_id, bucket, key)return f"{prefix}{local_path}{suffix}"result = re.sub(@@ -383,6 +426,54 @@ def _rewrite_s3_paths(query):return result+async def _save_query_results(query_id):+ from ministack.services import s3 as s3_svc+ execution = _executions.get(query_id)+ results = execution.get('_results', [])++ output = io.StringIO()+ writer = csv.writer(output)+ writer.writerows(results['rows'])+ csv_content = output.getvalue().encode("utf-8")++ col_types = execution.get('_column_types', [])+ metadata_text = ",".join(results['columns']) + "\n" + ",".join(col_types)+ metadata_content = metadata_text.encode("utf-8")++ output_location = execution["ResultConfiguration"]["OutputLocation"]+ p = urlparse(output_location)+ local_path = f"{p.netloc}{p.path}".rstrip("/")++ async def upload(path, data):+ account_id = get_account_id()+ aws_region = get_region()+ dt = date.today().strftime("%Y%m%d")++ credential = f"{account_id}/{dt}/{aws_region}/s3/aws4_request"++ headers = {+ "content-type": "application/octet-stream",+ "content-length": str(len(data)),+ "x-amz-account-id": account_id,+ "Authorization": f"AWS4-HMAC-SHA256 Credential={credential}"+ }+ status, _, body = await s3_svc.handle_request("PUT", path, headers, data, {})+ if status != 200:+ try:+ root = ET.fromstring(body)+ code = root.findtext("Code", "UnknownError")+ message = root.findtext("Message", "An unexpected S3 error occurred")+ except Exception:+ code, message = "InternalError", "Failed to parse S3 error response"+ execution["Status"]["State"] = "FAILED"+ execution["Status"]["StateChangeReason"] = f"An error occurred while writing to S3. {code}: {message}"+ return False+ return True++ if await upload(local_path, csv_content):+ await upload(f"{local_path}.metadata", metadata_content)++def _mock_query_results(query):query_upper = query.strip().upper()if query_upper.startswith("SELECT"):diff --git a/tests/test_athena.py b/tests/test_athena.pyindex d7480907..c5fceaf6 100644--- a/tests/test_athena.py+++ b/tests/test_athena.py@@ -48,7 +48,7 @@ def test_athena_query_execution_v2(athena):resp = athena.start_query_execution(QueryString="SELECT 42 AS answer, 'world' AS hello",QueryExecutionContext={"Database": "default"},- ResultConfiguration={"OutputLocation": "s3://athena-out/"},+ ResultConfiguration={"OutputLocation": "s3://athena-results/"},)qid = resp["QueryExecutionId"]state = None@@ -228,7 +228,7 @@ def test_athena_stop_query(athena):"""StopQueryExecution cancels a running query."""resp = athena.start_query_execution(QueryString="SELECT 1",- ResultConfiguration={"OutputLocation": "s3://qa-athena-results/"},+ ResultConfiguration={"OutputLocation": "s3://athena-results/"},)qid = resp["QueryExecutionId"]athena.stop_query_execution(QueryExecutionId=qid)@@ -301,3 +301,93 @@ def test_athena_engine_mock_via_config(athena):method="POST",)urllib.request.urlopen(req2, timeout=5)+++def test_athena_mixed_glue_and_s3_uri(athena, glue, monkeypatch, tmp_path):+ bucket_name = "athena-results"+ db_name = "test_db_athena_glue_s3"++ from ministack.services import s3 as s3mod+ monkeypatch.setattr(s3mod, "DATA_DIR", str(tmp_path))+ monkeypatch.setattr(s3mod, "S3_PERSIST", True)++ import json as _json+ import urllib.request++ 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(+ bucket_name,+ "tables/users/data.csv",+ b"id,name\n1,alice\n2,bob"+ )++ s3mod._persist_object(+ bucket_name,+ "raw/age_info.csv",+ b"id,age\n1,25\n2,30"+ )++ s3mod._persist_object(+ bucket_name,+ "raw/height_info.csv",+ b"id,height\n1,170\n2,180"+ )++ glue.create_database(DatabaseInput={'Name': db_name})+ glue.create_table(+ DatabaseName=db_name,+ TableInput={+ 'Name': 'users_table',+ 'StorageDescriptor': {+ 'Location': f's3://{bucket_name}/tables/users/',+ 'InputFormat': 'org.apache.hadoop.mapred.TextInputFormat',+ },+ 'Parameters': {'classification': 'csv'}+ }+ )++ query = f"""+ SELECT u.name, a.age, h.height+ FROM {db_name}.users_table u+ JOIN read_csv('s3://{bucket_name}/raw/age_info.csv') a ON u.id = a.id+ JOIN 's3://{bucket_name}/raw/height_info.csv' h ON u.id = h.id+ ORDER BY u.id+ """++ output_loc = f"s3://{bucket_name}/results/"++ resp = athena.start_query_execution(+ QueryString=query,+ QueryExecutionContext={'Database': db_name},+ ResultConfiguration={'OutputLocation': output_loc}+ )+ query_id = resp['QueryExecutionId']++ for _ in range(10):+ status = athena.get_query_execution(QueryExecutionId=query_id)+ state = status['QueryExecution']['Status']['State']+ if state in ['SUCCEEDED', 'FAILED', 'CANCELLED']:+ break+ time.sleep(0.2)++ assert state == "SUCCEEDED", f"Query ended in state: {state}"+ results = athena.get_query_results(QueryExecutionId=query_id)++ rows = results["ResultSet"]["Rows"]+ assert len(rows) >= 2+ assert rows[1]["Data"][0]["VarCharValue"] == "alice"+ assert rows[1]["Data"][1]["VarCharValue"] == "25"+ assert rows[1]["Data"][2]["VarCharValue"] == "170"++[email protected](scope="module", autouse=True)+def _create_s3_results_bucket(s3):+ s3.create_bucket(Bucket="athena-results")