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
intentflow/pyflow.py
ADDED
|
@@ -0,0 +1,554 @@
|
|
|
1
|
+
"""Static analysis of a Python job (PySpark/pandas): what it reads, what it writes and how each output column derives from the inputs.
|
|
2
|
+
|
|
3
|
+
Interprets the AST without running the code. A DataFrame is a `Frame`: known columns (`cols`: output → {(dataset, column)}),
|
|
4
|
+
datasets read whole (`whole`: columns not named yet, passed along), columns used only in filters/joins (`ind`) and
|
|
5
|
+
`opaque` (an operation it does not understand: the output becomes conservative). It follows variables, chained calls, functions of the
|
|
6
|
+
same file and of sibling modules imported (inside the declaration directory), SQL built by concatenation/f-string/`format`/`%`,
|
|
7
|
+
`spark.sql(...)`, `filter/join/groupBy.agg/withColumn/select/rename/drop`, and in pandas `df["c"] = ...`, `merge`, `rename`, `drop`.
|
|
8
|
+
Best-effort heuristic: what it does not understand is marked `opaque` and never silently disappears.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import ast
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from .external import ExtRead, render_sql, sql_reads
|
|
17
|
+
from .i18n import tr
|
|
18
|
+
|
|
19
|
+
_READ_FMT = {"parquet", "csv", "json", "orc", "load", "table", "avro", "text", "delta"}
|
|
20
|
+
_PD_READ = {"read_csv", "read_parquet", "read_json", "read_orc", "read_table", "read_sql_table", "read_feather", "read_excel"}
|
|
21
|
+
_WRITE_FMT = {"parquet", "csv", "json", "orc", "save", "avro", "text", "saveAsTable", "insertInto", "to_parquet", "to_csv", "to_json",
|
|
22
|
+
"to_orc", "to_feather", "to_sql", "to_excel"}
|
|
23
|
+
_PASS = {"orderBy", "sort", "sort_values", "limit", "distinct", "drop_duplicates", "dropDuplicates", "repartition", "coalesce", "cache",
|
|
24
|
+
"persist", "alias", "copy", "reset_index", "head", "tail", "sample", "na", "fillna", "dropna", "toDF", "checkpoint", "hint",
|
|
25
|
+
"withWatermark", "toPandas", "to_pandas", "astype"}
|
|
26
|
+
_MAX_DEPTH = 6
|
|
27
|
+
_MAX_STEPS = 20_000 # evaluations per job: the file may come from a PR; functions calling each other several times grow exponentially
|
|
28
|
+
_MAX_NODES = 200_000 # AST nodes summed (file + imported modules)
|
|
29
|
+
_MAX_MODULES = 20
|
|
30
|
+
_MAX_STR = 1_000_000
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class _Budget(Exception):
|
|
34
|
+
pass
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class Frame:
|
|
39
|
+
cols: dict = field(default_factory=dict) # output column → {(dataset, column)}
|
|
40
|
+
whole: set = field(default_factory=set) # datasets whose columns pass along unnamed
|
|
41
|
+
ind: set = field(default_factory=set) # {(dataset, column)} used only in filter/join/grouping
|
|
42
|
+
opaque: bool = False
|
|
43
|
+
|
|
44
|
+
def copy(self) -> Frame:
|
|
45
|
+
return Frame({k: set(v) for k, v in self.cols.items()}, set(self.whole), set(self.ind), self.opaque)
|
|
46
|
+
|
|
47
|
+
def resolve(self, name: str) -> set:
|
|
48
|
+
name = name.lower()
|
|
49
|
+
if name in self.cols:
|
|
50
|
+
return set(self.cols[name])
|
|
51
|
+
return {(d, name) for d in self.whole}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class _Mark: # Spark session / reader / writer / grouping
|
|
56
|
+
kind: str
|
|
57
|
+
frame: Frame | None = None
|
|
58
|
+
keys: set = field(default_factory=set)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class _Run:
|
|
62
|
+
def __init__(self, base: Path | None, params, dialect, project):
|
|
63
|
+
self.base, self.params, self.dialect, self.project = base, params, dialect, project
|
|
64
|
+
self.outputs: list[tuple[str, Frame]] = []
|
|
65
|
+
self.reads: list[str] = []
|
|
66
|
+
self.funcs: dict[str, tuple[ast.FunctionDef, dict]] = {}
|
|
67
|
+
self.mods: dict[str, Path] = {}
|
|
68
|
+
self.loaded: set[str] = set()
|
|
69
|
+
self.depth = 0
|
|
70
|
+
self.unknown_sql = False
|
|
71
|
+
self.steps = 0
|
|
72
|
+
self.nodes = 0
|
|
73
|
+
self.truncated = False
|
|
74
|
+
|
|
75
|
+
def tick(self, n: int = 1):
|
|
76
|
+
self.steps += n
|
|
77
|
+
if self.steps > _MAX_STEPS:
|
|
78
|
+
raise _Budget()
|
|
79
|
+
|
|
80
|
+
# ---- sibling modules (only inside the declaration directory) ----
|
|
81
|
+
def _load_module(self, dotted: str):
|
|
82
|
+
if self.base is None or dotted in self.loaded:
|
|
83
|
+
return
|
|
84
|
+
if len(self.loaded) >= _MAX_MODULES:
|
|
85
|
+
return
|
|
86
|
+
self.loaded.add(dotted)
|
|
87
|
+
root = self.base.resolve()
|
|
88
|
+
path = (root / (dotted.replace(".", "/") + ".py")).resolve()
|
|
89
|
+
if not path.is_relative_to(root) or not path.is_file() or path.stat().st_size > 1_000_000:
|
|
90
|
+
return
|
|
91
|
+
try:
|
|
92
|
+
tree = ast.parse(path.read_text())
|
|
93
|
+
except (SyntaxError, ValueError, RecursionError):
|
|
94
|
+
return
|
|
95
|
+
self.nodes += sum(1 for _ in ast.walk(tree))
|
|
96
|
+
if self.nodes > _MAX_NODES:
|
|
97
|
+
return
|
|
98
|
+
for n in tree.body:
|
|
99
|
+
if isinstance(n, ast.FunctionDef):
|
|
100
|
+
self.funcs.setdefault(f"{dotted}.{n.name}", (n, {}))
|
|
101
|
+
self.funcs.setdefault(n.name, (n, {})) if False else None
|
|
102
|
+
|
|
103
|
+
# ---- strings (built SQL) ----
|
|
104
|
+
def string(self, n, env) -> str | None:
|
|
105
|
+
r = self._string(n, env)
|
|
106
|
+
return r if r is None or len(r) <= _MAX_STR else r[:_MAX_STR]
|
|
107
|
+
|
|
108
|
+
def _string(self, n, env) -> str | None:
|
|
109
|
+
self.tick()
|
|
110
|
+
if isinstance(n, ast.Constant) and isinstance(n.value, str):
|
|
111
|
+
return n.value
|
|
112
|
+
if isinstance(n, ast.JoinedStr):
|
|
113
|
+
return "".join(v.value if isinstance(v, ast.Constant) else self._hole(v.value, env) for v in n.values)
|
|
114
|
+
if isinstance(n, ast.BinOp) and isinstance(n.op, ast.Add):
|
|
115
|
+
a, b = self.string(n.left, env), self.string(n.right, env)
|
|
116
|
+
return None if a is None and b is None else (a or self._hole(n.left, env)) + (b or self._hole(n.right, env))
|
|
117
|
+
if isinstance(n, ast.BinOp) and isinstance(n.op, ast.Mod):
|
|
118
|
+
a = self.string(n.left, env)
|
|
119
|
+
return None if a is None else __import__("re").sub(r"%[sdrfi]", lambda m: "{arg}", a)
|
|
120
|
+
if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute):
|
|
121
|
+
if n.func.attr == "format":
|
|
122
|
+
a = self.string(n.func.value, env)
|
|
123
|
+
return None if a is None else __import__("re").sub(r"\{[^{}]*\}", lambda m: "{arg}", a)
|
|
124
|
+
if n.func.attr == "join" and n.args:
|
|
125
|
+
return self.string(n.args[0], env)
|
|
126
|
+
if n.func.attr in ("strip", "lstrip", "rstrip", "replace", "lower", "upper", "dedent"):
|
|
127
|
+
return self.string(n.func.value, env)
|
|
128
|
+
if isinstance(n, ast.Name) and isinstance(env.get(n.id), str):
|
|
129
|
+
return env[n.id]
|
|
130
|
+
if isinstance(n, ast.Call) and isinstance(n.func, ast.Name) and n.func.id in ("dedent", "str", "textwrap") and n.args:
|
|
131
|
+
return self.string(n.args[0], env)
|
|
132
|
+
return None
|
|
133
|
+
|
|
134
|
+
def _hole(self, n, env) -> str:
|
|
135
|
+
s = self.string(n, env) if not isinstance(n, str) else n
|
|
136
|
+
if s is not None:
|
|
137
|
+
return s
|
|
138
|
+
return "{" + (n.id if isinstance(n, ast.Name) else "arg") + "}"
|
|
139
|
+
|
|
140
|
+
# ---- column expressions ----
|
|
141
|
+
def refs(self, expr, frame: Frame) -> set:
|
|
142
|
+
out = set()
|
|
143
|
+
for x in ast.walk(expr):
|
|
144
|
+
self.tick()
|
|
145
|
+
if isinstance(x, ast.Constant) and isinstance(x.value, str) and x.value.isidentifier():
|
|
146
|
+
out |= frame.resolve(x.value)
|
|
147
|
+
elif isinstance(x, ast.Attribute) and isinstance(x.value, ast.Name) and x.value.id in ("df", "data", "frame", "d"):
|
|
148
|
+
out |= frame.resolve(x.attr)
|
|
149
|
+
return out
|
|
150
|
+
|
|
151
|
+
def out_name(self, expr) -> str | None:
|
|
152
|
+
if isinstance(expr, ast.Call) and isinstance(expr.func, ast.Attribute) and expr.func.attr in ("alias", "name") and expr.args:
|
|
153
|
+
s = expr.args[0]
|
|
154
|
+
return s.value.lower() if isinstance(s, ast.Constant) and isinstance(s.value, str) else None
|
|
155
|
+
if isinstance(expr, ast.Constant) and isinstance(expr.value, str) and expr.value.isidentifier():
|
|
156
|
+
return expr.value.lower()
|
|
157
|
+
if isinstance(expr, ast.Call) and isinstance(expr.func, (ast.Attribute, ast.Name)):
|
|
158
|
+
f = expr.func.attr if isinstance(expr.func, ast.Attribute) else expr.func.id
|
|
159
|
+
if f == "col" and expr.args and isinstance(expr.args[0], ast.Constant):
|
|
160
|
+
return str(expr.args[0].value).lower()
|
|
161
|
+
if isinstance(expr, ast.Subscript) and isinstance(expr.slice, ast.Constant) and isinstance(expr.slice.value, str):
|
|
162
|
+
return expr.slice.value.lower()
|
|
163
|
+
return None
|
|
164
|
+
|
|
165
|
+
# ---- evaluation ----
|
|
166
|
+
def ev(self, n, env):
|
|
167
|
+
self.tick()
|
|
168
|
+
if isinstance(n, ast.Name):
|
|
169
|
+
if env.get(n.id) is not None:
|
|
170
|
+
return env[n.id]
|
|
171
|
+
return _Mark("session") if n.id in ("spark", "sqlContext", "sc", "session", "SparkSession", "SQLContext", "HiveContext") else None
|
|
172
|
+
if isinstance(n, ast.Constant):
|
|
173
|
+
return n.value
|
|
174
|
+
if isinstance(n, (ast.JoinedStr, ast.BinOp)):
|
|
175
|
+
s = self.string(n, env)
|
|
176
|
+
return s
|
|
177
|
+
if isinstance(n, ast.Attribute):
|
|
178
|
+
b = self.ev(n.value, env)
|
|
179
|
+
if isinstance(b, _Mark) and b.kind == "session" and n.attr == "read":
|
|
180
|
+
return _Mark("reader")
|
|
181
|
+
if isinstance(b, _Mark) and b.kind == "session" and n.attr == "catalog":
|
|
182
|
+
return _Mark("session")
|
|
183
|
+
if isinstance(b, Frame) and n.attr == "write":
|
|
184
|
+
return _Mark("writer", b)
|
|
185
|
+
if isinstance(b, Frame) and n.attr in ("columns", "na", "T"):
|
|
186
|
+
return b
|
|
187
|
+
return b if isinstance(b, (Frame, _Mark)) else None
|
|
188
|
+
if isinstance(n, ast.Subscript):
|
|
189
|
+
b = self.ev(n.value, env)
|
|
190
|
+
if isinstance(b, Frame): # df[["a","b"]] = selection; df["a"] = column (assignment is handled in `stmt`)
|
|
191
|
+
if isinstance(n.slice, (ast.List, ast.Tuple)):
|
|
192
|
+
names = [self.out_name(e) for e in n.slice.elts]
|
|
193
|
+
f = b.copy()
|
|
194
|
+
f.cols = {c: b.resolve(c) for c in names if c}
|
|
195
|
+
f.whole = set()
|
|
196
|
+
return f
|
|
197
|
+
return b
|
|
198
|
+
return None
|
|
199
|
+
if isinstance(n, ast.Call):
|
|
200
|
+
return self.call(n, env)
|
|
201
|
+
return None
|
|
202
|
+
|
|
203
|
+
def read(self, ds, kind="read") -> Frame:
|
|
204
|
+
self.reads.append(ds)
|
|
205
|
+
return Frame(whole={ds})
|
|
206
|
+
|
|
207
|
+
def call(self, n: ast.Call, env):
|
|
208
|
+
fn = n.func
|
|
209
|
+
for a in n.args: # evaluated for their side effects on env (nested reads/assignments)
|
|
210
|
+
self.ev(a, env)
|
|
211
|
+
if isinstance(fn, ast.Name):
|
|
212
|
+
return self.call_user(fn.id, n, env)
|
|
213
|
+
if not isinstance(fn, ast.Attribute):
|
|
214
|
+
return None
|
|
215
|
+
m = fn.attr
|
|
216
|
+
base = self.ev(fn.value, env)
|
|
217
|
+
s0 = self.string(n.args[0], env) if n.args else None
|
|
218
|
+
if isinstance(fn.value, ast.Name) and fn.value.id in ("pd", "pandas", "dd", "pl", "polars") and m in _PD_READ and s0:
|
|
219
|
+
return self.read(s0)
|
|
220
|
+
if isinstance(fn.value, ast.Name) and env.get(fn.value.id) is None and not isinstance(base, _Mark): # module.function
|
|
221
|
+
u = self.call_user(f"{fn.value.id}.{m}", n, env)
|
|
222
|
+
if u is not None:
|
|
223
|
+
return u
|
|
224
|
+
if isinstance(base, _Mark):
|
|
225
|
+
k = base.kind
|
|
226
|
+
if k == "session":
|
|
227
|
+
if m == "table" and s0:
|
|
228
|
+
return self.read(s0)
|
|
229
|
+
if m == "sql" and s0 is not None:
|
|
230
|
+
return self.sql(s0)
|
|
231
|
+
if m in ("builder", "appName", "master", "config", "getOrCreate", "enableHiveSupport"):
|
|
232
|
+
return base
|
|
233
|
+
if m in ("createDataFrame", "range"):
|
|
234
|
+
return Frame()
|
|
235
|
+
return base
|
|
236
|
+
if k == "reader":
|
|
237
|
+
if m in _READ_FMT and s0 and m != "load" or (m == "load" and s0):
|
|
238
|
+
return self.read(s0)
|
|
239
|
+
if m == "table" and s0:
|
|
240
|
+
return self.read(s0)
|
|
241
|
+
return base # format/option/schema/...
|
|
242
|
+
if k == "writer":
|
|
243
|
+
if m in _WRITE_FMT and s0:
|
|
244
|
+
self.outputs.append((s0, base.frame))
|
|
245
|
+
return None
|
|
246
|
+
return base # mode/option/format/partitionBy...
|
|
247
|
+
if k == "grouped":
|
|
248
|
+
f = base.frame.copy()
|
|
249
|
+
if m == "agg":
|
|
250
|
+
f.cols = {c: base.frame.resolve(c) for c in base.keys}
|
|
251
|
+
for a in n.args:
|
|
252
|
+
nm = self.out_name(a)
|
|
253
|
+
if nm:
|
|
254
|
+
f.cols[nm] = self.refs(a, base.frame)
|
|
255
|
+
for kw in n.keywords: # pandas: agg(total=("amount", "sum"))
|
|
256
|
+
if kw.arg:
|
|
257
|
+
f.cols[kw.arg.lower()] = self.refs(kw.value, base.frame)
|
|
258
|
+
else: # count/sum/avg/max/min(col...)
|
|
259
|
+
f.cols = {c: base.frame.resolve(c) for c in base.keys}
|
|
260
|
+
for a in n.args:
|
|
261
|
+
s = self.string(a, env)
|
|
262
|
+
if s:
|
|
263
|
+
f.cols[f"{m}({s.lower()})"] = base.frame.resolve(s)
|
|
264
|
+
f.cols[s.lower()] = base.frame.resolve(s)
|
|
265
|
+
f.cols.setdefault("count", set())
|
|
266
|
+
f.whole = set()
|
|
267
|
+
f.ind |= {x for c in base.keys for x in base.frame.resolve(c)}
|
|
268
|
+
return f
|
|
269
|
+
return None
|
|
270
|
+
if isinstance(base, Frame):
|
|
271
|
+
return self.frame_method(base, m, n, env, s0)
|
|
272
|
+
# DataFrame.write on an unknown object, `to_*` on an unknown frame: no information
|
|
273
|
+
return None
|
|
274
|
+
|
|
275
|
+
def frame_method(self, b: Frame, m: str, n: ast.Call, env, s0):
|
|
276
|
+
f = b.copy()
|
|
277
|
+
if m in ("select", "selectExpr"):
|
|
278
|
+
cols: dict = {}
|
|
279
|
+
for a in n.args:
|
|
280
|
+
if isinstance(a, ast.Constant) and a.value == "*":
|
|
281
|
+
cols.update(f.cols)
|
|
282
|
+
continue
|
|
283
|
+
if m == "selectExpr" and isinstance(a, ast.Constant) and isinstance(a.value, str):
|
|
284
|
+
nm = a.value.rsplit(" as ", 1)[-1].strip().lower() if " as " in a.value.lower() else a.value.strip().lower()
|
|
285
|
+
cols[nm.split(".")[-1]] = {r for w in __import__("re").findall(r"[A-Za-z_]\w*", a.value) for r in f.resolve(w)}
|
|
286
|
+
continue
|
|
287
|
+
if isinstance(a, (ast.List, ast.Tuple)):
|
|
288
|
+
for e in a.elts:
|
|
289
|
+
nm = self.out_name(e)
|
|
290
|
+
if nm:
|
|
291
|
+
cols[nm] = self.refs(e, f) or f.resolve(nm)
|
|
292
|
+
continue
|
|
293
|
+
nm = self.out_name(a)
|
|
294
|
+
if nm:
|
|
295
|
+
cols[nm] = self.refs(a, f) or f.resolve(nm)
|
|
296
|
+
else:
|
|
297
|
+
f.opaque = True
|
|
298
|
+
keep_whole = any(isinstance(a, ast.Constant) and a.value == "*" for a in n.args)
|
|
299
|
+
f.cols = {**({} if not keep_whole else f.cols), **cols}
|
|
300
|
+
if not keep_whole:
|
|
301
|
+
f.whole = set()
|
|
302
|
+
return f
|
|
303
|
+
if m == "withColumn" and len(n.args) == 2:
|
|
304
|
+
nm = self.string(n.args[0], env)
|
|
305
|
+
if nm:
|
|
306
|
+
f.cols[nm.lower()] = self.refs(n.args[1], f)
|
|
307
|
+
return f
|
|
308
|
+
f.opaque = True
|
|
309
|
+
return f
|
|
310
|
+
if m == "withColumnRenamed" and len(n.args) == 2:
|
|
311
|
+
a, c = self.string(n.args[0], env), self.string(n.args[1], env)
|
|
312
|
+
if a and c:
|
|
313
|
+
f.cols[c.lower()] = f.cols.pop(a.lower(), None) or f.resolve(a)
|
|
314
|
+
return f
|
|
315
|
+
f.opaque = True
|
|
316
|
+
return f
|
|
317
|
+
if m == "rename":
|
|
318
|
+
for kw in n.keywords:
|
|
319
|
+
if kw.arg == "columns" and isinstance(kw.value, ast.Dict):
|
|
320
|
+
for k, v in zip(kw.value.keys, kw.value.values):
|
|
321
|
+
if isinstance(k, ast.Constant) and isinstance(v, ast.Constant):
|
|
322
|
+
f.cols[str(v.value).lower()] = f.cols.pop(str(k.value).lower(), None) or f.resolve(str(k.value))
|
|
323
|
+
return f
|
|
324
|
+
if m in ("drop", "drop_duplicates") and m == "drop":
|
|
325
|
+
names = [self.string(a, env) for a in n.args] + [self.string(e, env) for kw in n.keywords if kw.arg == "columns"
|
|
326
|
+
for e in (kw.value.elts if isinstance(kw.value, (ast.List, ast.Tuple)) else [kw.value])]
|
|
327
|
+
for x in names:
|
|
328
|
+
if x:
|
|
329
|
+
f.cols.pop(x.lower(), None)
|
|
330
|
+
return f
|
|
331
|
+
if m in ("filter", "where", "query", "loc", "isin"):
|
|
332
|
+
for a in n.args:
|
|
333
|
+
f.ind |= self.refs(a, f) if not isinstance(a, ast.Constant) or not isinstance(a.value, str) else \
|
|
334
|
+
{r for w in __import__("re").findall(r"[A-Za-z_]\w*", a.value) for r in f.resolve(w)}
|
|
335
|
+
return f
|
|
336
|
+
if m in ("groupBy", "groupby", "group_by", "rollup", "cube"):
|
|
337
|
+
keys = set()
|
|
338
|
+
for a in n.args:
|
|
339
|
+
for e in (a.elts if isinstance(a, (ast.List, ast.Tuple)) else [a]):
|
|
340
|
+
s = self.string(e, env) or self.out_name(e)
|
|
341
|
+
if s:
|
|
342
|
+
keys.add(s.lower())
|
|
343
|
+
return _Mark("grouped", f, keys)
|
|
344
|
+
if m in ("join", "merge", "crossJoin"):
|
|
345
|
+
other = self.ev(n.args[0], env) if n.args else None
|
|
346
|
+
if isinstance(other, Frame):
|
|
347
|
+
for a in n.args[1:] + [kw.value for kw in n.keywords if kw.arg in ("on", "left_on", "right_on")]:
|
|
348
|
+
f.ind |= self.refs(a, f) | self.refs(a, other)
|
|
349
|
+
f.cols = {**{c: set(v) for c, v in other.cols.items()}, **f.cols}
|
|
350
|
+
f.whole |= other.whole
|
|
351
|
+
f.ind |= other.ind
|
|
352
|
+
f.opaque = f.opaque or other.opaque
|
|
353
|
+
return f
|
|
354
|
+
f.opaque = True
|
|
355
|
+
return f
|
|
356
|
+
if m in ("union", "unionByName", "unionAll", "concat", "append"):
|
|
357
|
+
other = self.ev(n.args[0], env) if n.args else None
|
|
358
|
+
if isinstance(other, Frame):
|
|
359
|
+
for c, v in other.cols.items():
|
|
360
|
+
f.cols.setdefault(c, set()).update(v)
|
|
361
|
+
f.whole |= other.whole
|
|
362
|
+
f.ind |= other.ind
|
|
363
|
+
return f
|
|
364
|
+
f.opaque = True
|
|
365
|
+
return f
|
|
366
|
+
if m in _WRITE_FMT and (s0 or m.startswith("to_")):
|
|
367
|
+
if s0:
|
|
368
|
+
self.outputs.append((s0, f))
|
|
369
|
+
return None
|
|
370
|
+
if m in ("write",):
|
|
371
|
+
return _Mark("writer", f)
|
|
372
|
+
if m == "sql" and s0 is not None:
|
|
373
|
+
return self.sql(s0)
|
|
374
|
+
if m in _PASS:
|
|
375
|
+
return f
|
|
376
|
+
f.opaque = True # mapInPandas, applyInPandas, rdd.map, apply, transform(func): the output is unknown
|
|
377
|
+
return f
|
|
378
|
+
|
|
379
|
+
def sql(self, text: str) -> Frame:
|
|
380
|
+
txt, _ = render_sql(text, self.params)
|
|
381
|
+
try:
|
|
382
|
+
rs = sql_reads("job", None, ("__out__",), txt, self.dialect, self.project)
|
|
383
|
+
except ValueError:
|
|
384
|
+
self.unknown_sql = True
|
|
385
|
+
return Frame(opaque=True)
|
|
386
|
+
f = Frame()
|
|
387
|
+
for r in rs:
|
|
388
|
+
self.reads.append(r.dataset)
|
|
389
|
+
if r.column == "*":
|
|
390
|
+
f.whole.add(r.dataset)
|
|
391
|
+
for _d, c in r.feeds:
|
|
392
|
+
if c == "*":
|
|
393
|
+
f.ind.add((r.dataset, r.column))
|
|
394
|
+
else:
|
|
395
|
+
f.cols.setdefault(c, set()).add((r.dataset, r.column))
|
|
396
|
+
if not r.feeds and r.column != "*":
|
|
397
|
+
f.ind.add((r.dataset, r.column))
|
|
398
|
+
target = _sql_target(txt, self.dialect)
|
|
399
|
+
if target: # INSERT/CREATE ... AS inside spark.sql: it is a write
|
|
400
|
+
self.outputs.append((target, f))
|
|
401
|
+
return f
|
|
402
|
+
|
|
403
|
+
def call_user(self, name: str, n: ast.Call, env):
|
|
404
|
+
entry = self.funcs.get(name)
|
|
405
|
+
if entry is None or self.depth >= _MAX_DEPTH:
|
|
406
|
+
return None
|
|
407
|
+
fd = entry[0]
|
|
408
|
+
local = {}
|
|
409
|
+
names = [a.arg for a in fd.args.args]
|
|
410
|
+
for i, a in enumerate(n.args):
|
|
411
|
+
if i < len(names):
|
|
412
|
+
local[names[i]] = self.ev(a, env)
|
|
413
|
+
for kw in n.keywords:
|
|
414
|
+
if kw.arg:
|
|
415
|
+
local[kw.arg] = self.ev(kw.value, env)
|
|
416
|
+
self.depth += 1
|
|
417
|
+
try:
|
|
418
|
+
return self.block(fd.body, local, ret=True)
|
|
419
|
+
finally:
|
|
420
|
+
self.depth -= 1
|
|
421
|
+
|
|
422
|
+
def stmt(self, s, env):
|
|
423
|
+
self.tick()
|
|
424
|
+
if isinstance(s, ast.Assign):
|
|
425
|
+
v = self.ev(s.value, env)
|
|
426
|
+
for t in s.targets:
|
|
427
|
+
if isinstance(t, ast.Name):
|
|
428
|
+
env[t.id] = v
|
|
429
|
+
elif isinstance(t, ast.Subscript) and isinstance(t.value, ast.Name) and isinstance(env.get(t.value.id), Frame):
|
|
430
|
+
nm = self.string(t.slice, env) if isinstance(t.slice, ast.Constant) else None
|
|
431
|
+
fr = env[t.value.id]
|
|
432
|
+
if nm:
|
|
433
|
+
fr.cols[nm.lower()] = self.refs(s.value, fr)
|
|
434
|
+
else:
|
|
435
|
+
fr.opaque = True
|
|
436
|
+
elif isinstance(t, ast.Tuple) and isinstance(s.value, ast.Tuple):
|
|
437
|
+
for tt, vv in zip(t.elts, s.value.elts):
|
|
438
|
+
if isinstance(tt, ast.Name):
|
|
439
|
+
env[tt.id] = self.ev(vv, env)
|
|
440
|
+
elif isinstance(s, ast.AugAssign) and isinstance(s.target, ast.Name):
|
|
441
|
+
a, b = self.string(s.target, env), self.string(s.value, env)
|
|
442
|
+
if isinstance(s.op, ast.Add) and a is not None and b is not None:
|
|
443
|
+
env[s.target.id] = a + b
|
|
444
|
+
elif isinstance(s, ast.Expr):
|
|
445
|
+
self.ev(s.value, env)
|
|
446
|
+
elif isinstance(s, ast.FunctionDef):
|
|
447
|
+
self.funcs.setdefault(s.name, (s, {}))
|
|
448
|
+
elif isinstance(s, ast.ClassDef):
|
|
449
|
+
for x in s.body:
|
|
450
|
+
if isinstance(x, ast.FunctionDef):
|
|
451
|
+
self.funcs.setdefault(x.name, (x, {}))
|
|
452
|
+
elif isinstance(s, (ast.Import, ast.ImportFrom)):
|
|
453
|
+
if isinstance(s, ast.ImportFrom) and s.module:
|
|
454
|
+
self._load_module(s.module)
|
|
455
|
+
for a in s.names:
|
|
456
|
+
if f"{s.module}.{a.name}" in self.funcs:
|
|
457
|
+
self.funcs.setdefault(a.asname or a.name, self.funcs[f"{s.module}.{a.name}"])
|
|
458
|
+
elif isinstance(s, ast.Import):
|
|
459
|
+
for a in s.names:
|
|
460
|
+
self._load_module(a.name)
|
|
461
|
+
for k, v in list(self.funcs.items()):
|
|
462
|
+
if k.startswith(a.name + ".") and a.asname:
|
|
463
|
+
self.funcs.setdefault(a.asname + k[len(a.name):], v)
|
|
464
|
+
elif isinstance(s, ast.Return):
|
|
465
|
+
return self.ev(s.value, env) if s.value is not None else None
|
|
466
|
+
elif isinstance(s, (ast.If, ast.For, ast.While, ast.With, ast.Try)):
|
|
467
|
+
for part in ("body", "orelse", "finalbody"):
|
|
468
|
+
r = self.block(getattr(s, part, []) or [], env, ret=True)
|
|
469
|
+
if r is not None:
|
|
470
|
+
return r
|
|
471
|
+
for h in getattr(s, "handlers", []):
|
|
472
|
+
self.block(h.body, env)
|
|
473
|
+
return None
|
|
474
|
+
|
|
475
|
+
def block(self, body, env, ret=False):
|
|
476
|
+
# functions first: `main()` may be called before its `def` appears in the file (module execution order is by call)
|
|
477
|
+
for s in body:
|
|
478
|
+
if isinstance(s, ast.FunctionDef):
|
|
479
|
+
self.funcs.setdefault(s.name, (s, {}))
|
|
480
|
+
out = None
|
|
481
|
+
for s in body:
|
|
482
|
+
r = self.stmt(s, env)
|
|
483
|
+
if r is not None and ret:
|
|
484
|
+
out = r
|
|
485
|
+
return out
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def _sql_target(text: str, dialect: str) -> str | None:
|
|
489
|
+
import sqlglot
|
|
490
|
+
from sqlglot import exp
|
|
491
|
+
try:
|
|
492
|
+
for st in sqlglot.parse(text, read=dialect):
|
|
493
|
+
if isinstance(st, (exp.Create, exp.Insert)):
|
|
494
|
+
t = st.this if isinstance(st.this, exp.Table) else getattr(st.this, "this", None)
|
|
495
|
+
if isinstance(t, exp.Table):
|
|
496
|
+
return ".".join(x for x in (t.catalog, t.db, t.name) if x)
|
|
497
|
+
except sqlglot.errors.SqlglotError:
|
|
498
|
+
return None
|
|
499
|
+
return None
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def reads(name: str, owner, src: str, writes: tuple, dialect: str, project, params: dict | None = None, base: Path | None = None) -> list[ExtRead]:
|
|
503
|
+
try:
|
|
504
|
+
tree = ast.parse(src)
|
|
505
|
+
except (SyntaxError, ValueError, RecursionError):
|
|
506
|
+
raise ValueError(tr("job '{job}': py_file is not valid Python", job=name)) from None
|
|
507
|
+
run = _Run(base, params, dialect, project)
|
|
508
|
+
run.nodes = sum(1 for _ in ast.walk(tree))
|
|
509
|
+
if run.nodes > _MAX_NODES:
|
|
510
|
+
raise ValueError(tr("job '{job}': py_file too large to analyze (> {n} nodes)", job=name, n=_MAX_NODES))
|
|
511
|
+
env: dict = {}
|
|
512
|
+
try:
|
|
513
|
+
run.block(tree.body, env, ret=True)
|
|
514
|
+
if not run.outputs and not run.reads:
|
|
515
|
+
# nothing recognized: run the file's functions as entry points (e.g. `def main(spark)` called by a scheduler)
|
|
516
|
+
for _fn, (fd, _) in list(run.funcs.items()):
|
|
517
|
+
local = {a.arg: (_Mark("session") if a.arg in ("spark", "session") else None) for a in fd.args.args}
|
|
518
|
+
run.block(fd.body, local, ret=True)
|
|
519
|
+
except (_Budget, RecursionError):
|
|
520
|
+
run.truncated = True # budget exceeded: what was seen counts, and the output becomes conservative
|
|
521
|
+
w = tuple(dict.fromkeys(writes or [d for d, _ in run.outputs]))
|
|
522
|
+
out: list[ExtRead] = []
|
|
523
|
+
seen: set = set()
|
|
524
|
+
|
|
525
|
+
def add(ds, col, feeds):
|
|
526
|
+
k = (ds, col, feeds)
|
|
527
|
+
if k not in seen:
|
|
528
|
+
seen.add(k)
|
|
529
|
+
out.append(ExtRead(name, ds, col, "declared", owner, w, feeds))
|
|
530
|
+
|
|
531
|
+
used: set = set()
|
|
532
|
+
targets = list(run.outputs) or ([(w[0], Frame(whole=set(run.reads), opaque=True))] if w else [])
|
|
533
|
+
if run.truncated:
|
|
534
|
+
targets = [(d, Frame(cols=fr.cols, whole=fr.whole | set(run.reads), ind=fr.ind, opaque=True)) for d, fr in targets] or \
|
|
535
|
+
([(w[0], Frame(whole=set(run.reads), opaque=True))] if w else [])
|
|
536
|
+
for ds, fr in targets:
|
|
537
|
+
for c, srcs in fr.cols.items():
|
|
538
|
+
for sds, scol in srcs:
|
|
539
|
+
add(sds, scol, ((ds, c),))
|
|
540
|
+
used.add(sds)
|
|
541
|
+
for sds in fr.whole:
|
|
542
|
+
add(sds, "*", ((ds, "*"),))
|
|
543
|
+
used.add(sds)
|
|
544
|
+
for sds, scol in fr.ind:
|
|
545
|
+
add(sds, scol, ((ds, "*"),))
|
|
546
|
+
used.add(sds)
|
|
547
|
+
if fr.opaque: # operation not understood: every input may affect any output column
|
|
548
|
+
for srcs in fr.cols.values():
|
|
549
|
+
for sds, scol in srcs:
|
|
550
|
+
add(sds, scol, ((ds, "*"),))
|
|
551
|
+
for ds in dict.fromkeys(run.reads):
|
|
552
|
+
if ds not in used:
|
|
553
|
+
add(ds, "*", ()) # read, but without an identifiable destination: conservative
|
|
554
|
+
return out
|