intentdataflow 0.3.10__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- intentdataflow-0.3.10.dist-info/METADATA +191 -0
- intentdataflow-0.3.10.dist-info/RECORD +83 -0
- intentdataflow-0.3.10.dist-info/WHEEL +5 -0
- intentdataflow-0.3.10.dist-info/entry_points.txt +2 -0
- intentdataflow-0.3.10.dist-info/licenses/LICENSE +202 -0
- intentdataflow-0.3.10.dist-info/licenses/NOTICE +4 -0
- intentdataflow-0.3.10.dist-info/top_level.txt +1 -0
- intentflow/__init__.py +2 -0
- intentflow/auth.py +30 -0
- intentflow/business_rules.py +77 -0
- intentflow/catalogs.py +100 -0
- intentflow/change_review.py +331 -0
- intentflow/checks/__init__.py +92 -0
- intentflow/checks/airflow3.py +174 -0
- intentflow/checks/business.py +27 -0
- intentflow/checks/catalog.py +43 -0
- intentflow/checks/cluster.py +81 -0
- intentflow/checks/contracts.py +79 -0
- intentflow/checks/cost.py +35 -0
- intentflow/checks/dbt_quality.py +90 -0
- intentflow/checks/dbt_run.py +83 -0
- intentflow/checks/deep.py +180 -0
- intentflow/checks/dq.py +53 -0
- intentflow/checks/elementary.py +50 -0
- intentflow/checks/external.py +91 -0
- intentflow/checks/lakehouse.py +46 -0
- intentflow/checks/lint.py +81 -0
- intentflow/checks/orchestration.py +148 -0
- intentflow/checks/probes.py +66 -0
- intentflow/checks/runtime_history.py +94 -0
- intentflow/checks/schema_drift.py +92 -0
- intentflow/checks/sql_quality.py +274 -0
- intentflow/checks/streaming.py +62 -0
- intentflow/cli.py +914 -0
- intentflow/contracts.py +107 -0
- intentflow/datadiff.py +172 -0
- intentflow/dbt_loader.py +194 -0
- intentflow/dbt_results.py +55 -0
- intentflow/dq_results.py +108 -0
- intentflow/extensions.py +51 -0
- intentflow/external.py +381 -0
- intentflow/http_utils.py +89 -0
- intentflow/i18n.py +76 -0
- intentflow/incidents.py +83 -0
- intentflow/integrations.py +139 -0
- intentflow/lakehouse.py +62 -0
- intentflow/lineage.py +336 -0
- intentflow/lineage_api.py +244 -0
- intentflow/lineage_oracle.py +374 -0
- intentflow/locale/pt.json +1300 -0
- intentflow/model.py +43 -0
- intentflow/monitoring.py +197 -0
- intentflow/notify.py +154 -0
- intentflow/ol_emit.py +93 -0
- intentflow/openlineage.py +168 -0
- intentflow/orchestrators/__init__.py +53 -0
- intentflow/orchestrators/airflow.py +69 -0
- intentflow/orchestrators/aws.py +93 -0
- intentflow/orchestrators/dagster.py +48 -0
- intentflow/orchestrators/dbtcloud.py +68 -0
- intentflow/orchestrators/extra.py +135 -0
- intentflow/orchestrators/ingestion.py +112 -0
- intentflow/orchestrators/kestra.py +27 -0
- intentflow/orchestrators/more.py +135 -0
- intentflow/orchestrators/prefect.py +53 -0
- intentflow/orchestrators/spark.py +118 -0
- intentflow/otel.py +53 -0
- intentflow/overview.py +123 -0
- intentflow/preflight.py +363 -0
- intentflow/promexport.py +39 -0
- intentflow/pyflow.py +554 -0
- intentflow/risks.py +178 -0
- intentflow/runner.py +264 -0
- intentflow/secrets_box.py +84 -0
- intentflow/sqlmesh_loader.py +134 -0
- intentflow/store.py +1006 -0
- intentflow/streaming.py +115 -0
- intentflow/totp.py +38 -0
- intentflow/warehouses/__init__.py +190 -0
- intentflow/warehouses/cloud.py +160 -0
- intentflow/warehouses/more.py +342 -0
- intentflow/web.html +878 -0
- intentflow/web.py +726 -0
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
"""Trino, ClickHouse and Redshift (read-only, the driver is imported only when used).
|
|
2
|
+
|
|
3
|
+
Trino : TRINO_HOST, [TRINO_PORT=8080, TRINO_USER=intentflow, TRINO_CATALOG, TRINO_SCHEMA, TRINO_PASSWORD → https]
|
|
4
|
+
ClickHouse : CLICKHOUSE_HOST, [CLICKHOUSE_PORT=8123, CLICKHOUSE_USER=default, CLICKHOUSE_PASSWORD, CLICKHOUSE_DATABASE, CLICKHOUSE_SECURE]
|
|
5
|
+
Redshift : REDSHIFT_URL (postgresql://…, Postgres protocol)
|
|
6
|
+
Verification: Trino and ClickHouse in real containers; Redshift only with a fake connection (there is no emulator).
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from ..i18n import tr
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
|
|
16
|
+
from . import PostgresWarehouse, Warehouse
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _num(x):
|
|
20
|
+
try:
|
|
21
|
+
v = float(x)
|
|
22
|
+
return v if v == v else None # NaN → None
|
|
23
|
+
except (TypeError, ValueError):
|
|
24
|
+
return None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class TrinoWarehouse(Warehouse):
|
|
28
|
+
dialect, name = "trino", "trino"
|
|
29
|
+
def _bucket(self, text):
|
|
30
|
+
return f"abs(mod(from_big_endian_64(xxhash64(to_utf8({text}))), 10000))"
|
|
31
|
+
|
|
32
|
+
MEM_ERRORS = ("EXCEEDED_LOCAL_MEMORY_LIMIT", "EXCEEDED_GLOBAL_MEMORY_LIMIT", "EXCEEDED_SPILL_LIMIT", "CLUSTER_OUT_OF_MEMORY")
|
|
33
|
+
|
|
34
|
+
def __init__(self, connection=None):
|
|
35
|
+
if connection is None:
|
|
36
|
+
import trino # type: ignore
|
|
37
|
+
host = os.environ.get("TRINO_HOST")
|
|
38
|
+
if not host:
|
|
39
|
+
raise RuntimeError(tr("variable {name} is not set", name="TRINO_HOST"))
|
|
40
|
+
pw = os.environ.get("TRINO_PASSWORD")
|
|
41
|
+
kw = dict(host=host, port=int(os.environ.get("TRINO_PORT", "8080")), user=os.environ.get("TRINO_USER", "intentflow"),
|
|
42
|
+
catalog=os.environ.get("TRINO_CATALOG"), schema=os.environ.get("TRINO_SCHEMA"))
|
|
43
|
+
if pw:
|
|
44
|
+
kw.update(http_scheme="https", auth=trino.auth.BasicAuthentication(kw["user"], pw))
|
|
45
|
+
connection = trino.dbapi.connect(**kw)
|
|
46
|
+
self.con = connection
|
|
47
|
+
|
|
48
|
+
def rows(self, sql):
|
|
49
|
+
cur = self.con.cursor()
|
|
50
|
+
cur.execute(sql)
|
|
51
|
+
return [tuple(r) for r in cur.fetchall()]
|
|
52
|
+
|
|
53
|
+
def describe(self, rel):
|
|
54
|
+
return [(r[0], str(r[1])) for r in self.rows(f"describe {rel}")]
|
|
55
|
+
|
|
56
|
+
def plan(self, sql):
|
|
57
|
+
raw = self.rows("EXPLAIN (TYPE DISTRIBUTED, FORMAT JSON) " + sql)[0][0]
|
|
58
|
+
frags = json.loads(raw) if isinstance(raw, str) else raw
|
|
59
|
+
ops, rows, cost = [], [], []
|
|
60
|
+
|
|
61
|
+
def walk(n):
|
|
62
|
+
ops.append(n.get("name", ""))
|
|
63
|
+
for e in n.get("estimates") or []:
|
|
64
|
+
if _num(e.get("outputRowCount")) is not None:
|
|
65
|
+
rows.append(int(_num(e["outputRowCount"])))
|
|
66
|
+
if _num(e.get("cpuCost")):
|
|
67
|
+
cost.append(_num(e["cpuCost"]))
|
|
68
|
+
for c in n.get("children", []):
|
|
69
|
+
walk(c)
|
|
70
|
+
for f in (frags.values() if isinstance(frags, dict) and "name" not in frags else [frags]):
|
|
71
|
+
walk(f)
|
|
72
|
+
return {"operators": ops, "max_rows": max(rows) if rows else None, "cost": max(cost) if cost else None}
|
|
73
|
+
|
|
74
|
+
def memory_failures(self, hours: int = 24) -> list[dict]:
|
|
75
|
+
"""Queries that died from the memory limit (Trino does not expose spill bytes in `runtime.queries`)."""
|
|
76
|
+
inl = ", ".join(f"'{e}'" for e in self.MEM_ERRORS)
|
|
77
|
+
try:
|
|
78
|
+
r = self.rows(f"select query_id, substr(query, 1, 200), error_code from system.runtime.queries "
|
|
79
|
+
f"where error_code in ({inl}) and \"end\" > current_timestamp - interval '{int(hours)}' hour order by \"end\" desc limit 50")
|
|
80
|
+
except Exception:
|
|
81
|
+
return []
|
|
82
|
+
return [{"source": "trino", "scope": qid, "detail": f"{code}: {txt}"} for qid, txt, code in r]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class RedshiftWarehouse(PostgresWarehouse):
|
|
86
|
+
"""Postgres protocol, but without EXPLAIN JSON: the plan comes from the text (`cost=a..b rows=N`)."""
|
|
87
|
+
dialect, name = "redshift", "redshift"
|
|
88
|
+
|
|
89
|
+
def _bucket(self, text):
|
|
90
|
+
return f"abs(mod(fnv_hash({text}), 10000))"
|
|
91
|
+
|
|
92
|
+
SPILL_SQL = ("select query, sum(bytes) from svl_query_summary where is_diskbased = 't' and starttime > dateadd(hour, -{hours}, getdate()) "
|
|
93
|
+
"group by query order by 2 desc limit 50")
|
|
94
|
+
|
|
95
|
+
def __init__(self, url_env: str = "REDSHIFT_URL", connection=None):
|
|
96
|
+
if connection is not None:
|
|
97
|
+
self.con = connection
|
|
98
|
+
else:
|
|
99
|
+
super().__init__(url_env)
|
|
100
|
+
|
|
101
|
+
def plan(self, sql):
|
|
102
|
+
txt = "\n".join(str(r[0]) for r in self.rows("EXPLAIN " + sql))
|
|
103
|
+
ops = [m.group(1).strip() for m in re.finditer(r"^\s*(?:->\s*)?(XN [\w ]+?)\s+\(cost", txt, re.M)]
|
|
104
|
+
rows = [int(m) for m in re.findall(r"rows=(\d+)", txt)]
|
|
105
|
+
cost = [float(m) for m in re.findall(r"cost=[\d.]+\.\.([\d.]+)", txt)]
|
|
106
|
+
return {"operators": ops, "max_rows": max(rows) if rows else None, "cost": max(cost) if cost else None}
|
|
107
|
+
|
|
108
|
+
def describe(self, rel):
|
|
109
|
+
with self.con.cursor() as c:
|
|
110
|
+
c.execute(f"select * from {rel} where 1=0")
|
|
111
|
+
return [(d.name, str(d.type_code)) for d in c.description]
|
|
112
|
+
|
|
113
|
+
def spill_report(self, hours=24):
|
|
114
|
+
try:
|
|
115
|
+
r = self.rows(self.SPILL_SQL.format(hours=int(hours)))
|
|
116
|
+
except Exception:
|
|
117
|
+
return []
|
|
118
|
+
return [{"source": "redshift", "scope": str(q), "spilled_bytes": int(b or 0), "detail": "svl_query_summary is_diskbased"} for q, b in r]
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class ClickHouseWarehouse(Warehouse):
|
|
122
|
+
dialect, name = "clickhouse", "clickhouse"
|
|
123
|
+
def _bucket(self, text):
|
|
124
|
+
return f"(cityHash64({text}) % 10000)"
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def __init__(self, client=None):
|
|
128
|
+
if client is None:
|
|
129
|
+
import clickhouse_connect # type: ignore
|
|
130
|
+
host = os.environ.get("CLICKHOUSE_HOST")
|
|
131
|
+
if not host:
|
|
132
|
+
raise RuntimeError(tr("variable {name} is not set", name="CLICKHOUSE_HOST"))
|
|
133
|
+
secure = os.environ.get("CLICKHOUSE_SECURE", "").lower() in ("1", "true", "yes")
|
|
134
|
+
client = clickhouse_connect.get_client(
|
|
135
|
+
host=host, port=int(os.environ.get("CLICKHOUSE_PORT", "8443" if secure else "8123")), username=os.environ.get("CLICKHOUSE_USER", "default"),
|
|
136
|
+
password=os.environ.get("CLICKHOUSE_PASSWORD", ""), database=os.environ.get("CLICKHOUSE_DATABASE", "default"), secure=secure,
|
|
137
|
+
settings={"readonly": 2, "join_use_nulls": 1}) # readonly=2: no writes, but settings can be adjusted; join_use_nulls: a correct anti-join
|
|
138
|
+
self.con = client
|
|
139
|
+
|
|
140
|
+
def rows(self, sql):
|
|
141
|
+
return [tuple(r) for r in self.con.query(sql).result_rows]
|
|
142
|
+
|
|
143
|
+
def differs(self, a, b): # 24.x: IS [NOT] DISTINCT FROM only exists in JOIN ON
|
|
144
|
+
return f"ifNull({a} != {b}, isNull({a}) != isNull({b}))"
|
|
145
|
+
|
|
146
|
+
def describe(self, rel):
|
|
147
|
+
return [(r[0], str(r[1])) for r in self.rows(f"describe table {rel}")]
|
|
148
|
+
|
|
149
|
+
def plan(self, sql):
|
|
150
|
+
ops: list[str] = []
|
|
151
|
+
|
|
152
|
+
def walk(n):
|
|
153
|
+
ops.append(n.get("Node Type", ""))
|
|
154
|
+
for c in n.get("Plans", []):
|
|
155
|
+
walk(c)
|
|
156
|
+
raw = self.rows("EXPLAIN json = 1 " + sql)[0][0]
|
|
157
|
+
for item in (json.loads(raw) if isinstance(raw, str) else raw):
|
|
158
|
+
walk(item.get("Plan", {}))
|
|
159
|
+
rows = None
|
|
160
|
+
try: # EXPLAIN ESTIMATE: (database, table, parts, rows, marks)
|
|
161
|
+
rows = sum(int(r[3]) for r in self.rows("EXPLAIN ESTIMATE " + sql)) or None
|
|
162
|
+
except Exception:
|
|
163
|
+
pass
|
|
164
|
+
return {"operators": ops, "max_rows": rows, "cost": None}
|
|
165
|
+
|
|
166
|
+
def spill_report(self, hours=24):
|
|
167
|
+
try:
|
|
168
|
+
r = self.rows(
|
|
169
|
+
"select query_id, substring(query, 1, 200), "
|
|
170
|
+
"ProfileEvents['ExternalProcessingCompressedBytesTotal'] + ProfileEvents['ExternalSortCompressedBytes'] + ProfileEvents['ExternalAggregationCompressedBytes'] as b "
|
|
171
|
+
f"from system.query_log where type = 'QueryFinish' and event_time > now() - interval {int(hours)} hour and b > 0 order by b desc limit 50")
|
|
172
|
+
except Exception:
|
|
173
|
+
return []
|
|
174
|
+
return [{"source": "clickhouse", "scope": qid, "spilled_bytes": int(b), "detail": txt} for qid, txt, b in r]
|
|
175
|
+
|
|
176
|
+
def memory_failures(self, hours=24):
|
|
177
|
+
try: # 241 = MEMORY_LIMIT_EXCEEDED
|
|
178
|
+
r = self.rows("select query_id, substring(query, 1, 200) from system.query_log "
|
|
179
|
+
f"where type = 'ExceptionWhileProcessing' and exception_code = 241 and event_time > now() - interval {int(hours)} hour limit 50")
|
|
180
|
+
except Exception:
|
|
181
|
+
return []
|
|
182
|
+
return [{"source": "clickhouse", "scope": qid, "detail": f"MEMORY_LIMIT_EXCEEDED: {txt}"} for qid, txt in r]
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
class MySQLWarehouse(Warehouse):
|
|
186
|
+
"""MySQL/MariaDB (read-only; `READ ONLY` session). Env: MYSQL_HOST, [MYSQL_PORT=3306, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE]."""
|
|
187
|
+
dialect, name = "mysql", "mysql"
|
|
188
|
+
str_type = "char"
|
|
189
|
+
|
|
190
|
+
def _bucket(self, text):
|
|
191
|
+
return f"(crc32({text}) % 10000)"
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def __init__(self, connection=None):
|
|
195
|
+
if connection is None:
|
|
196
|
+
import pymysql # type: ignore
|
|
197
|
+
host = os.environ.get("MYSQL_HOST")
|
|
198
|
+
if not host:
|
|
199
|
+
raise RuntimeError(tr("variable {name} is not set", name="MYSQL_HOST"))
|
|
200
|
+
connection = pymysql.connect(host=host, port=int(os.environ.get("MYSQL_PORT", "3306")), user=os.environ.get("MYSQL_USER", "root"),
|
|
201
|
+
password=os.environ.get("MYSQL_PASSWORD", ""), database=os.environ.get("MYSQL_DATABASE"), autocommit=True,
|
|
202
|
+
connect_timeout=10, read_timeout=300)
|
|
203
|
+
with connection.cursor() as c:
|
|
204
|
+
c.execute("SET SESSION TRANSACTION READ ONLY")
|
|
205
|
+
self.con = connection
|
|
206
|
+
|
|
207
|
+
def quote(self, ident):
|
|
208
|
+
return "`" + ident.replace("`", "") + "`"
|
|
209
|
+
|
|
210
|
+
def differs(self, a, b): # MySQL has no IS DISTINCT FROM; `<=>` is the NULL-safe equality
|
|
211
|
+
return f"not ({a} <=> {b})"
|
|
212
|
+
|
|
213
|
+
def rows(self, sql):
|
|
214
|
+
with self.con.cursor() as c:
|
|
215
|
+
c.execute(sql)
|
|
216
|
+
return [tuple(r) for r in c.fetchall()] if c.description else []
|
|
217
|
+
|
|
218
|
+
def describe(self, rel):
|
|
219
|
+
return [(r[0], str(r[1])) for r in self.rows(f"describe {rel}")]
|
|
220
|
+
|
|
221
|
+
def plan(self, sql):
|
|
222
|
+
raw = self.rows("EXPLAIN FORMAT=JSON " + sql)[0][0]
|
|
223
|
+
doc = json.loads(raw) if isinstance(raw, str) else raw
|
|
224
|
+
ops, rows, cost = [], [], []
|
|
225
|
+
|
|
226
|
+
def walk(n):
|
|
227
|
+
if isinstance(n, dict):
|
|
228
|
+
if "access_type" in n:
|
|
229
|
+
ops.append(f"{n.get('access_type')}:{n.get('table_name', '')}")
|
|
230
|
+
for k in ("rows_examined_per_scan", "rows_produced_per_join"):
|
|
231
|
+
if n.get(k) is not None:
|
|
232
|
+
rows.append(int(n[k]))
|
|
233
|
+
if "query_cost" in (n.get("cost_info") or {}):
|
|
234
|
+
cost.append(float(n["cost_info"]["query_cost"]))
|
|
235
|
+
for v in n.values():
|
|
236
|
+
walk(v)
|
|
237
|
+
elif isinstance(n, list):
|
|
238
|
+
for v in n:
|
|
239
|
+
walk(v)
|
|
240
|
+
walk(doc)
|
|
241
|
+
return {"operators": ops, "max_rows": max(rows) if rows else None, "cost": max(cost) if cost else None}
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
class SQLServerWarehouse(Warehouse):
|
|
245
|
+
"""SQL Server / Azure SQL through `pymssql` (read-only). Env: MSSQL_HOST, [MSSQL_PORT=1433, MSSQL_USER, MSSQL_PASSWORD, MSSQL_DATABASE].
|
|
246
|
+
Verification: fake connection only (no SQL Server container verified here)."""
|
|
247
|
+
dialect, name = "tsql", "sqlserver"
|
|
248
|
+
def _bucket(self, text):
|
|
249
|
+
return f"abs(checksum({text}) % 10000)"
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def __init__(self, connection=None):
|
|
253
|
+
if connection is None:
|
|
254
|
+
import pymssql # type: ignore
|
|
255
|
+
host = os.environ.get("MSSQL_HOST")
|
|
256
|
+
if not host:
|
|
257
|
+
raise RuntimeError(tr("variable {name} is not set", name="MSSQL_HOST"))
|
|
258
|
+
connection = pymssql.connect(server=host, port=int(os.environ.get("MSSQL_PORT", "1433")), user=os.environ.get("MSSQL_USER", ""),
|
|
259
|
+
password=os.environ.get("MSSQL_PASSWORD", ""), database=os.environ.get("MSSQL_DATABASE", ""), autocommit=True,
|
|
260
|
+
login_timeout=10, read_only=True)
|
|
261
|
+
self.con = connection
|
|
262
|
+
|
|
263
|
+
def quote(self, ident):
|
|
264
|
+
return "[" + ident.replace("]", "]]") + "]"
|
|
265
|
+
|
|
266
|
+
def differs(self, a, b): # works on any version (IS DISTINCT FROM only in 2022+)
|
|
267
|
+
return f"not exists (select {a} intersect select {b})"
|
|
268
|
+
|
|
269
|
+
def rows(self, sql):
|
|
270
|
+
cur = self.con.cursor()
|
|
271
|
+
try:
|
|
272
|
+
cur.execute(sql)
|
|
273
|
+
return [tuple(r) for r in cur.fetchall()] if cur.description else []
|
|
274
|
+
finally:
|
|
275
|
+
cur.close()
|
|
276
|
+
|
|
277
|
+
def describe(self, rel):
|
|
278
|
+
parts = [p.strip("[]\"") for p in rel.split(".")]
|
|
279
|
+
tbl, sch = parts[-1], (parts[-2] if len(parts) > 1 else "dbo")
|
|
280
|
+
return [(r[0], str(r[1])) for r in self.rows(
|
|
281
|
+
"select column_name, data_type from information_schema.columns "
|
|
282
|
+
f"where table_name = '{tbl.replace(chr(39), '')}' and table_schema = '{sch.replace(chr(39), '')}' order by ordinal_position")]
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
class AthenaWarehouse(TrinoWarehouse):
|
|
286
|
+
"""Amazon Athena (motor Trino): consultas via API (`StartQueryExecution`), esquema pelo Glue Data Catalog.
|
|
287
|
+
Env: `ATHENA_OUTPUT_LOCATION` (s3://bucket/prefixo/), opcionais `ATHENA_WORKGROUP`, `ATHENA_DATABASE`, `AWS_REGION`."""
|
|
288
|
+
dialect, name = "athena", "athena"
|
|
289
|
+
|
|
290
|
+
def __init__(self, client=None, workgroup: str | None = None, database: str | None = None, output: str | None = None, poll=0.5, timeout=300):
|
|
291
|
+
if client is None:
|
|
292
|
+
from .. import orchestrators # noqa: F401
|
|
293
|
+
from ..orchestrators.aws import client as _client
|
|
294
|
+
client = _client("athena")
|
|
295
|
+
self.c, self.poll, self.timeout = client, poll, timeout
|
|
296
|
+
self.workgroup = workgroup or os.environ.get("ATHENA_WORKGROUP", "primary")
|
|
297
|
+
self.database = database or os.environ.get("ATHENA_DATABASE")
|
|
298
|
+
self.output = output or os.environ.get("ATHENA_OUTPUT_LOCATION")
|
|
299
|
+
|
|
300
|
+
def rows(self, sql):
|
|
301
|
+
import time
|
|
302
|
+
kw = {"QueryString": sql, "WorkGroup": self.workgroup}
|
|
303
|
+
if self.database:
|
|
304
|
+
kw["QueryExecutionContext"] = {"Database": self.database}
|
|
305
|
+
if self.output:
|
|
306
|
+
kw["ResultConfiguration"] = {"OutputLocation": self.output}
|
|
307
|
+
qid = self.c.start_query_execution(**kw)["QueryExecutionId"]
|
|
308
|
+
t0 = time.time()
|
|
309
|
+
while True:
|
|
310
|
+
st = self.c.get_query_execution(QueryExecutionId=qid)["QueryExecution"]["Status"]
|
|
311
|
+
if st["State"] in ("SUCCEEDED", "FAILED", "CANCELLED"):
|
|
312
|
+
break
|
|
313
|
+
if time.time() - t0 > self.timeout:
|
|
314
|
+
raise RuntimeError(tr("Athena: query {id} exceeded {s}s", id=qid, s=self.timeout))
|
|
315
|
+
time.sleep(self.poll)
|
|
316
|
+
if st["State"] != "SUCCEEDED":
|
|
317
|
+
raise RuntimeError(f"Athena: {st['State']}: {st.get('StateChangeReason', '')[:200]}")
|
|
318
|
+
out, first, token = [], True, None
|
|
319
|
+
while True:
|
|
320
|
+
r = self.c.get_query_results(QueryExecutionId=qid, **({"NextToken": token} if token else {}))
|
|
321
|
+
for row in r["ResultSet"]["Rows"]:
|
|
322
|
+
vals = tuple(d.get("VarCharValue") for d in row["Data"])
|
|
323
|
+
if first: # the first row of the first page is the header (data queries)
|
|
324
|
+
first = False
|
|
325
|
+
if not sql.lstrip().lower().startswith(("explain", "show", "describe")):
|
|
326
|
+
continue
|
|
327
|
+
out.append(vals)
|
|
328
|
+
token = r.get("NextToken")
|
|
329
|
+
if not token:
|
|
330
|
+
return out
|
|
331
|
+
|
|
332
|
+
def describe(self, rel):
|
|
333
|
+
parts = [p.strip('`"') for p in rel.split(".")]
|
|
334
|
+
db, tbl = (parts[-2], parts[-1]) if len(parts) > 1 else (self.database, parts[-1])
|
|
335
|
+
md = self.c.get_table_metadata(CatalogName="AwsDataCatalog", DatabaseName=db, TableName=tbl)["TableMetadata"]
|
|
336
|
+
return [(c["Name"], c.get("Type", "")) for c in md.get("Columns", [])]
|
|
337
|
+
|
|
338
|
+
def memory_failures(self, hours=24):
|
|
339
|
+
return []
|
|
340
|
+
|
|
341
|
+
def spill_report(self, hours=24):
|
|
342
|
+
return []
|