skifer-engine 4.2.0__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.
- skifer/core/interpreter.py +609 -0
- skifer/core/loaders.py +123 -0
- skifer/core/rule_executor.py +172 -0
- skifer/core/spark_backend.py +1523 -0
- skifer/core/writer.py +174 -0
- skifer/spark_factory.py +144 -0
- skifer_engine-4.2.0.dist-info/METADATA +766 -0
- skifer_engine-4.2.0.dist-info/RECORD +10 -0
- skifer_engine-4.2.0.dist-info/WHEEL +4 -0
- skifer_engine-4.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,609 @@
|
|
|
1
|
+
"""
|
|
2
|
+
SchemaInterpreter — translates a normalized schema dict into DataFrame operations.
|
|
3
|
+
|
|
4
|
+
Extracted from SkiferEngine (plan17-2.3) so that the engine class is a thin
|
|
5
|
+
facade over composable components. The interpreter owns the three stateful
|
|
6
|
+
processing methods:
|
|
7
|
+
|
|
8
|
+
- get_select_expressions — parse select_final / fields op-strings into columns
|
|
9
|
+
- _apply_business_rules — run registered rules through RulePlanner/RuleExecutor
|
|
10
|
+
- process_schema — full pipeline: load → filter → join → rules → select
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import logging
|
|
15
|
+
from functools import reduce
|
|
16
|
+
from typing import TYPE_CHECKING, Any
|
|
17
|
+
|
|
18
|
+
from skifer.core.ir import _normalise_join_type, _parse_op
|
|
19
|
+
from skifer.core.registry import RuleRegistry
|
|
20
|
+
from skifer.core.sandbox import SandboxResolver
|
|
21
|
+
from skifer.core.rule_analyzer import RuleAnalyzer
|
|
22
|
+
from skifer.core.rule_planner import RulePlanner
|
|
23
|
+
from skifer.core.rule_executor import RuleExecutor
|
|
24
|
+
from skifer.core import loaders # noqa: F401 — registers built-in loaders where they are consumed
|
|
25
|
+
|
|
26
|
+
if TYPE_CHECKING:
|
|
27
|
+
from skifer.core.context import ExecutionContext
|
|
28
|
+
|
|
29
|
+
logger = logging.getLogger(__name__)
|
|
30
|
+
|
|
31
|
+
_LEFT_ONLY_JOIN_TYPES = {"left_anti", "left_semi"}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class SchemaInterpreter:
|
|
35
|
+
"""
|
|
36
|
+
Translates a normalized schema dict into DataFrame operations.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
backend: SparkBackend (tests may pass a duck-typed double).
|
|
40
|
+
context: ExecutionContext providing env, config, is_job_execution, etc.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(self, backend: Any, context: "ExecutionContext") -> None:
|
|
44
|
+
self._backend = backend
|
|
45
|
+
self._context = context
|
|
46
|
+
# Shared resolver for sandbox memoization — reused across all process_schema calls
|
|
47
|
+
# on this interpreter instance so cloned tables are never re-checked.
|
|
48
|
+
self._sandbox_resolver: SandboxResolver | None = None
|
|
49
|
+
|
|
50
|
+
def resolve_source_table(self, name: str) -> str:
|
|
51
|
+
"""
|
|
52
|
+
Resolve a declared table name to the FQN actually read (Plan 28).
|
|
53
|
+
|
|
54
|
+
In interactive mode the sandbox suffix redirects reads to the user's own
|
|
55
|
+
schema, cloning the table on demand. In job/prod mode the declared name
|
|
56
|
+
is used as-is. Shared by the DataFrame path and the SQL compiler so both
|
|
57
|
+
read exactly the same tables.
|
|
58
|
+
"""
|
|
59
|
+
ctx = self._context
|
|
60
|
+
if not (ctx.schema_suffix and not ctx.is_job_execution):
|
|
61
|
+
return name
|
|
62
|
+
missing_behavior = ctx.config.get("sandbox", {}).get("missing_table", "copy")
|
|
63
|
+
if self._sandbox_resolver is None:
|
|
64
|
+
self._sandbox_resolver = SandboxResolver(backend=self._backend)
|
|
65
|
+
return self._sandbox_resolver.resolve(name, ctx.schema_suffix, missing_behavior)
|
|
66
|
+
|
|
67
|
+
# ------------------------------------------------------------------
|
|
68
|
+
# Public helpers
|
|
69
|
+
# ------------------------------------------------------------------
|
|
70
|
+
|
|
71
|
+
def get_select_expressions(self, field_list: list, allow_raw_sql: bool = True) -> list:
|
|
72
|
+
"""
|
|
73
|
+
Parse a 'select_final' or 'fields' block into a list of backend column expressions.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
field_list: List of field definitions (list-form or dict-form).
|
|
77
|
+
allow_raw_sql: When False, expr: raises ValueError.
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
List of column expressions ready for backend.select().
|
|
81
|
+
"""
|
|
82
|
+
b = self._backend
|
|
83
|
+
select_exprs = []
|
|
84
|
+
i = 0
|
|
85
|
+
while i < len(field_list):
|
|
86
|
+
config = field_list[i]
|
|
87
|
+
|
|
88
|
+
# Multi-condition dict form: {source, target, ops: [{when, then}, ..., {else}]}
|
|
89
|
+
if isinstance(config, dict):
|
|
90
|
+
source_col = config.get("source")
|
|
91
|
+
target_col = config["target"]
|
|
92
|
+
ops = config.get("ops", [])
|
|
93
|
+
c = b.col(source_col) if source_col else None
|
|
94
|
+
|
|
95
|
+
when_conditions = [op for op in ops if "when" in op]
|
|
96
|
+
else_op = next((op for op in ops if "else" in op), None)
|
|
97
|
+
|
|
98
|
+
if when_conditions:
|
|
99
|
+
pairs = [
|
|
100
|
+
(
|
|
101
|
+
b.apply_op(c, _parse_op(f"when:{wc['when']}"), allow_raw_sql),
|
|
102
|
+
b.apply_op(c, _parse_op(wc["then"]), allow_raw_sql),
|
|
103
|
+
)
|
|
104
|
+
for wc in when_conditions
|
|
105
|
+
]
|
|
106
|
+
otherwise_val = (
|
|
107
|
+
b.apply_op(c, _parse_op(else_op["else"]), allow_raw_sql)
|
|
108
|
+
if else_op else b.lit(None)
|
|
109
|
+
)
|
|
110
|
+
result_col = b.when_chain(pairs, otherwise_val)
|
|
111
|
+
select_exprs.append(result_col.alias(target_col))
|
|
112
|
+
else:
|
|
113
|
+
for op_str in ops:
|
|
114
|
+
c = b.apply_op(c, _parse_op(op_str if isinstance(op_str, str) else str(op_str)), allow_raw_sql)
|
|
115
|
+
if c is not None:
|
|
116
|
+
select_exprs.append(c.alias(target_col))
|
|
117
|
+
i += 1
|
|
118
|
+
continue
|
|
119
|
+
|
|
120
|
+
source_col = config[0]
|
|
121
|
+
target_col = config[1]
|
|
122
|
+
operations = config[2] if len(config) > 2 else []
|
|
123
|
+
|
|
124
|
+
c = b.col(source_col) if source_col else None
|
|
125
|
+
|
|
126
|
+
# Compact when/then/else chain — validated at load time, guarded here too
|
|
127
|
+
if operations and isinstance(operations[0], str) and operations[0].startswith("when:"):
|
|
128
|
+
if len(operations) != 3:
|
|
129
|
+
raise ValueError(
|
|
130
|
+
f"Compact when/then/else chain for target '{target_col}' must have exactly "
|
|
131
|
+
f"3 elements [when:..., then:..., else:...], got {len(operations)}: {operations}. "
|
|
132
|
+
"Use load_schema() to catch this at schema load time."
|
|
133
|
+
)
|
|
134
|
+
if not isinstance(operations[1], str) or not operations[1].startswith("then:"):
|
|
135
|
+
raise ValueError(
|
|
136
|
+
f"Element [1] of compact when/then/else for '{target_col}' must start with "
|
|
137
|
+
f"'then:', got '{operations[1]}'."
|
|
138
|
+
)
|
|
139
|
+
if not isinstance(operations[2], str) or not operations[2].startswith("else:"):
|
|
140
|
+
raise ValueError(
|
|
141
|
+
f"Element [2] of compact when/then/else for '{target_col}' must start with "
|
|
142
|
+
f"'else:', got '{operations[2]}'."
|
|
143
|
+
)
|
|
144
|
+
cond_col = b.apply_op(c, _parse_op(operations[0]), allow_raw_sql)
|
|
145
|
+
then_col = b.apply_op(c, _parse_op(operations[1]), allow_raw_sql)
|
|
146
|
+
else_col = b.apply_op(c, _parse_op(operations[2]), allow_raw_sql)
|
|
147
|
+
c = b.otherwise(b.when(cond_col, then_col), else_col)
|
|
148
|
+
else:
|
|
149
|
+
for op_str in operations:
|
|
150
|
+
c = b.apply_op(c, _parse_op(op_str), allow_raw_sql)
|
|
151
|
+
|
|
152
|
+
if c is not None:
|
|
153
|
+
select_exprs.append(c.alias(target_col))
|
|
154
|
+
i += 1
|
|
155
|
+
return select_exprs
|
|
156
|
+
|
|
157
|
+
def _apply_business_rules(self, df: Any, rules_list: list, fuse_rules: bool = True) -> Any:
|
|
158
|
+
"""
|
|
159
|
+
Apply a list of registered business rules to a DataFrame.
|
|
160
|
+
|
|
161
|
+
When fuse_rules=True (default), consecutive projection rules are fused into
|
|
162
|
+
a single select() call by RulePlanner/RuleExecutor. Aggregation rules sharing
|
|
163
|
+
the same groupBy keys are fused into one groupBy().agg(). Transform rules run
|
|
164
|
+
sequentially.
|
|
165
|
+
|
|
166
|
+
Args:
|
|
167
|
+
df: Input DataFrame.
|
|
168
|
+
rules_list: List of rule names registered in RuleRegistry.
|
|
169
|
+
fuse_rules: Set False to run rules sequentially without fusion.
|
|
170
|
+
|
|
171
|
+
Returns:
|
|
172
|
+
Transformed DataFrame.
|
|
173
|
+
"""
|
|
174
|
+
if not rules_list:
|
|
175
|
+
return df
|
|
176
|
+
|
|
177
|
+
# In interactive mode, surface rule redundancy warnings once per call.
|
|
178
|
+
if not self._context.is_job_execution:
|
|
179
|
+
try:
|
|
180
|
+
analyzer = RuleAnalyzer()
|
|
181
|
+
profiles = analyzer.analyze_rules(rules_list)
|
|
182
|
+
for w in analyzer.detect_warnings(profiles):
|
|
183
|
+
logger.warning("[RuleAnalyzer] %s: %s", w.code, w.message)
|
|
184
|
+
except Exception:
|
|
185
|
+
pass # analysis is best-effort; never block execution
|
|
186
|
+
|
|
187
|
+
if not fuse_rules:
|
|
188
|
+
for rule_name in rules_list:
|
|
189
|
+
logger.info(" -> [Rule] Applying: %s", rule_name)
|
|
190
|
+
rule_spec = RuleRegistry.get_rule(rule_name)
|
|
191
|
+
result = rule_spec.func(df)
|
|
192
|
+
if rule_spec.kind == "projection":
|
|
193
|
+
if not isinstance(result, dict):
|
|
194
|
+
raise TypeError(
|
|
195
|
+
f"Rule '{rule_name}' is declared as kind='projection' but returned "
|
|
196
|
+
f"{type(result).__name__} instead of dict[str, Column]. "
|
|
197
|
+
"Either return a dict or change kind to 'transform'."
|
|
198
|
+
)
|
|
199
|
+
for col_name, col_expr in result.items():
|
|
200
|
+
df = df.withColumn(col_name, col_expr)
|
|
201
|
+
else:
|
|
202
|
+
df = result
|
|
203
|
+
return df
|
|
204
|
+
|
|
205
|
+
planner = RulePlanner()
|
|
206
|
+
executor = RuleExecutor()
|
|
207
|
+
stages = planner.plan(rules_list)
|
|
208
|
+
|
|
209
|
+
for stage in stages:
|
|
210
|
+
for name in [s.name for s in stage.rules]:
|
|
211
|
+
logger.info(" -> [Rule] Applying: %s", name)
|
|
212
|
+
df = executor.execute(df, [stage])
|
|
213
|
+
|
|
214
|
+
return df
|
|
215
|
+
|
|
216
|
+
_PARTIAL_MODES = ("inline", "temp_view", "table")
|
|
217
|
+
|
|
218
|
+
def _expand_partials(self, schema_dict: dict, intermediate_mode: str, dfs: dict) -> None:
|
|
219
|
+
"""Execute each nested partial and inject its output DataFrame under its alias.
|
|
220
|
+
|
|
221
|
+
Runs before source loading. The child schema goes through the full
|
|
222
|
+
``process_schema`` path (recursively, same ``intermediate_mode``) and never
|
|
223
|
+
writes a final table — the write lives in ``run_process_to_table``, not here.
|
|
224
|
+
A partial alias already present in ``dfs`` (provided via ``dataframes_in``) is
|
|
225
|
+
left untouched, letting callers override a partial with a pre-built DataFrame.
|
|
226
|
+
"""
|
|
227
|
+
partials = schema_dict.get("partials")
|
|
228
|
+
if not partials:
|
|
229
|
+
return
|
|
230
|
+
if intermediate_mode not in self._PARTIAL_MODES:
|
|
231
|
+
raise ValueError(
|
|
232
|
+
f"[partials] Unknown intermediate_mode '{intermediate_mode}'. "
|
|
233
|
+
f"Valid modes: {list(self._PARTIAL_MODES)}"
|
|
234
|
+
)
|
|
235
|
+
for p in partials:
|
|
236
|
+
alias = p["alias"]
|
|
237
|
+
if alias in dfs:
|
|
238
|
+
logger.info(" -> [Partial] '%s' provided by caller — skipping execution.", alias)
|
|
239
|
+
continue
|
|
240
|
+
logger.info(
|
|
241
|
+
" -> [Partial] Executing sub-transformation '%s' (mode=%s)",
|
|
242
|
+
alias, intermediate_mode,
|
|
243
|
+
)
|
|
244
|
+
child_df = self.process_schema(p["schema"], intermediate_mode=intermediate_mode)
|
|
245
|
+
dfs[alias] = self._materialize_partial(child_df, alias, intermediate_mode)
|
|
246
|
+
|
|
247
|
+
#: Schema that holds materialized partial tables (``table`` mode), sandbox-suffixed.
|
|
248
|
+
_PARTIAL_SCHEMA = "skifer_partials"
|
|
249
|
+
|
|
250
|
+
def _partial_debug_name(self, alias: str) -> str:
|
|
251
|
+
"""Deterministic, sandbox-aware identifier for a partial's temp view."""
|
|
252
|
+
suffix = getattr(self._context, "schema_suffix", "") or ""
|
|
253
|
+
return f"{alias}_{suffix}" if suffix else alias
|
|
254
|
+
|
|
255
|
+
def _partial_table_target(self, alias: str) -> tuple[str, str]:
|
|
256
|
+
"""Deterministic, env-aware (schema_fqn, table_fqn) for ``table`` mode.
|
|
257
|
+
|
|
258
|
+
Writes into a dedicated intermediate schema suffixed with the sandbox suffix
|
|
259
|
+
so concurrent interactive runs never collide. The partial ``alias`` is the
|
|
260
|
+
table name — no ``debug_name`` required.
|
|
261
|
+
"""
|
|
262
|
+
ctx = self._context
|
|
263
|
+
suffix = getattr(ctx, "schema_suffix", "") or ""
|
|
264
|
+
schema = f"{self._PARTIAL_SCHEMA}{suffix}"
|
|
265
|
+
catalog = getattr(ctx, "db", None)
|
|
266
|
+
schema_fqn = f"{catalog}.{schema}" if catalog else schema
|
|
267
|
+
table_fqn = self._backend.build_fqn(catalog, schema, alias)
|
|
268
|
+
return schema_fqn, table_fqn
|
|
269
|
+
|
|
270
|
+
def _materialize_partial(self, df: Any, alias: str, mode: str) -> Any:
|
|
271
|
+
"""Apply the materialization mode to a partial's output DataFrame.
|
|
272
|
+
|
|
273
|
+
``inline`` keeps the DataFrame in memory (no storage). ``temp_view``
|
|
274
|
+
registers a session-scoped view for interactive inspection.
|
|
275
|
+
``table`` writes a physical intermediate table with a deterministic,
|
|
276
|
+
env-aware FQN for restartability / perf inspection. In every mode the
|
|
277
|
+
parent keeps using the DataFrame directly.
|
|
278
|
+
"""
|
|
279
|
+
if mode == "inline":
|
|
280
|
+
return df
|
|
281
|
+
if mode == "temp_view":
|
|
282
|
+
view_name = self._partial_debug_name(alias)
|
|
283
|
+
self._backend.register_temp_view(df, view_name)
|
|
284
|
+
logger.info(" -> [Partial] Registered temp view '%s' for partial '%s'.", view_name, alias)
|
|
285
|
+
return df
|
|
286
|
+
if mode == "table":
|
|
287
|
+
schema_fqn, table_fqn = self._partial_table_target(alias)
|
|
288
|
+
self._backend.ensure_schema_exists(schema_fqn)
|
|
289
|
+
self._backend.write_table(df, table_fqn)
|
|
290
|
+
logger.info(" -> [Partial] Materialized table '%s' for partial '%s'.", table_fqn, alias)
|
|
291
|
+
return df
|
|
292
|
+
raise ValueError(
|
|
293
|
+
f"[partials] Unknown intermediate_mode '{mode}' (partial '{alias}')."
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
def _streaming_preflight(self, schema_dict: dict, intermediate_mode: str) -> None:
|
|
297
|
+
"""
|
|
298
|
+
Run-time streaming checks (Plan 27) that load-time validation cannot do.
|
|
299
|
+
|
|
300
|
+
- ``intermediate_mode`` is a run param (invisible at load): ``table``
|
|
301
|
+
would batch-write mid-pipeline — forbidden with streaming sources.
|
|
302
|
+
- Rule kinds live in the RuleRegistry (requires user imports): reject
|
|
303
|
+
``aggregation`` rules — streaming aggregations need watermark support.
|
|
304
|
+
- Re-check the per-table incompatibilities for hand-built schema dicts
|
|
305
|
+
that bypassed ``load_schema`` (limit/window ops are illegal on streams).
|
|
306
|
+
"""
|
|
307
|
+
if intermediate_mode == "table":
|
|
308
|
+
raise ValueError(
|
|
309
|
+
"[streaming] intermediate_mode='table' is incompatible with streaming "
|
|
310
|
+
"sources — partials would batch-write mid-pipeline. Use 'inline' or "
|
|
311
|
+
"'temp_view'."
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
agg_rules = []
|
|
315
|
+
for rule_entry in schema_dict.get("business_rules", []):
|
|
316
|
+
if not isinstance(rule_entry, str):
|
|
317
|
+
continue
|
|
318
|
+
try:
|
|
319
|
+
kind = RuleRegistry.get_rule(rule_entry).kind
|
|
320
|
+
except ValueError:
|
|
321
|
+
continue # unregistered — the rules step raises its own clear error
|
|
322
|
+
if kind == "aggregation":
|
|
323
|
+
agg_rules.append(rule_entry)
|
|
324
|
+
if agg_rules:
|
|
325
|
+
raise ValueError(
|
|
326
|
+
f"[streaming] aggregation rule(s) {agg_rules} cannot run on a streaming "
|
|
327
|
+
"pipeline — streaming aggregations require watermark support (planned "
|
|
328
|
+
"for a later plan). Aggregate downstream in a batch pipeline (or a "
|
|
329
|
+
"future materialized view) reading this streaming table."
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
if schema_dict.get("aggregate"):
|
|
333
|
+
raise ValueError(
|
|
334
|
+
"[streaming] the 'aggregate' block cannot run on a streaming pipeline — "
|
|
335
|
+
"streaming aggregations require watermark support (planned for a later "
|
|
336
|
+
"plan). Aggregate downstream in a batch pipeline or a materialized view "
|
|
337
|
+
"reading this streaming table."
|
|
338
|
+
)
|
|
339
|
+
|
|
340
|
+
for t in schema_dict.get("tables", []):
|
|
341
|
+
if not t.get("streaming"):
|
|
342
|
+
continue
|
|
343
|
+
label = t.get("alias") or t.get("name", "?")
|
|
344
|
+
if t.get("dev_limit") or schema_dict.get("dev_limit"):
|
|
345
|
+
raise ValueError(
|
|
346
|
+
f"[streaming] table '{label}': 'dev_limit' is incompatible with "
|
|
347
|
+
"streaming sources — limit() is unsupported on streaming DataFrames."
|
|
348
|
+
)
|
|
349
|
+
if "qualify" in (t.get("preprocess") or {}):
|
|
350
|
+
raise ValueError(
|
|
351
|
+
f"[streaming] table '{label}': 'preprocess.qualify' is incompatible "
|
|
352
|
+
"with streaming sources — row_number() windows are unsupported."
|
|
353
|
+
)
|
|
354
|
+
if (t.get("quality_checks") or {}).get("drop_duplicates_on"):
|
|
355
|
+
raise ValueError(
|
|
356
|
+
f"[streaming] table '{label}': 'drop_duplicates_on' is unbounded-state "
|
|
357
|
+
"on a stream. Use 'materialization: {type: streaming_table, "
|
|
358
|
+
"write_mode: upsert, keys: [...]}' instead."
|
|
359
|
+
)
|
|
360
|
+
|
|
361
|
+
def process_schema(
|
|
362
|
+
self,
|
|
363
|
+
schema_dict: dict,
|
|
364
|
+
dataframes_in: dict | None = None,
|
|
365
|
+
intermediate_mode: str = "inline",
|
|
366
|
+
) -> Any:
|
|
367
|
+
"""
|
|
368
|
+
Main pipeline logic: partials → load sources → filters → joins → rules → select.
|
|
369
|
+
|
|
370
|
+
Args:
|
|
371
|
+
schema_dict: Normalized pipeline schema dict.
|
|
372
|
+
dataframes_in: Pre-loaded DataFrames keyed by alias (bypass loading).
|
|
373
|
+
intermediate_mode: Materialization mode for nested ``partials:``
|
|
374
|
+
("inline" | "temp_view" | "table"). Global run-scoped knob; defaults
|
|
375
|
+
to "inline" (no durable storage). Propagated to nested partials.
|
|
376
|
+
|
|
377
|
+
Returns:
|
|
378
|
+
Processed DataFrame.
|
|
379
|
+
|
|
380
|
+
Raises:
|
|
381
|
+
ValueError: If no tables can be loaded.
|
|
382
|
+
"""
|
|
383
|
+
logger.info("Processing schema logic...")
|
|
384
|
+
b = self._backend
|
|
385
|
+
ctx = self._context
|
|
386
|
+
dfs = dataframes_in.copy() if dataframes_in else {}
|
|
387
|
+
|
|
388
|
+
# Streaming preflight (Plan 27) — run-time checks the loader cannot do.
|
|
389
|
+
if any(t.get("streaming") for t in schema_dict.get("tables", [])):
|
|
390
|
+
self._streaming_preflight(schema_dict, intermediate_mode)
|
|
391
|
+
|
|
392
|
+
# 0. PARTIALS — execute nested sub-transformations, expose them under their alias.
|
|
393
|
+
self._expand_partials(schema_dict, intermediate_mode, dfs)
|
|
394
|
+
|
|
395
|
+
allow_raw_sql = ctx.env_config().get("allow_raw_sql", True)
|
|
396
|
+
|
|
397
|
+
# 1. LOADERS & SOURCES
|
|
398
|
+
for t in schema_dict.get("tables", []):
|
|
399
|
+
alias = t.get("alias", t["name"])
|
|
400
|
+
|
|
401
|
+
if t["name"] in dfs:
|
|
402
|
+
if alias != t["name"]:
|
|
403
|
+
dfs[alias] = dfs[t["name"]]
|
|
404
|
+
else:
|
|
405
|
+
logger.info(" -> [Load] Loading table/source: %s", t["name"])
|
|
406
|
+
|
|
407
|
+
is_streaming_table = bool(t.get("streaming"))
|
|
408
|
+
if t.get("source_type") == "loader":
|
|
409
|
+
loader_func = RuleRegistry.get_loader(t["function_name"])
|
|
410
|
+
df = loader_func(ctx.config, backend=b, **t.get("arguments", {}))
|
|
411
|
+
elif "source" in t:
|
|
412
|
+
src_conf = t["source"]
|
|
413
|
+
logger.info(
|
|
414
|
+
" -> [Load] Reading external source: %s (%s @ %s)%s",
|
|
415
|
+
t["name"], src_conf["type"], src_conf["path"],
|
|
416
|
+
" [stream]" if is_streaming_table else "",
|
|
417
|
+
)
|
|
418
|
+
read_source = b.read_source_stream if is_streaming_table else b.read_source
|
|
419
|
+
df = read_source(
|
|
420
|
+
source_type=src_conf["type"],
|
|
421
|
+
path=src_conf["path"],
|
|
422
|
+
options=src_conf.get("options", {}),
|
|
423
|
+
)
|
|
424
|
+
else:
|
|
425
|
+
actual_table_name = self.resolve_source_table(t["name"])
|
|
426
|
+
if is_streaming_table:
|
|
427
|
+
logger.info(" -> [Load] Reading as stream: %s", actual_table_name)
|
|
428
|
+
df = b.read_table_stream(actual_table_name)
|
|
429
|
+
else:
|
|
430
|
+
df = b.read_table(actual_table_name)
|
|
431
|
+
|
|
432
|
+
# Filters — filters are already normalized dicts by schema_loader
|
|
433
|
+
if "filter" in t:
|
|
434
|
+
from skifer.core.ir import ParsedFilter
|
|
435
|
+
pf_list = [ParsedFilter(d["column"], d["operator"], d.get("value")) for d in t["filter"]]
|
|
436
|
+
if pf_list:
|
|
437
|
+
cond = reduce(lambda a, c: a & c, [b.build_filter(pf, allow_raw_sql) for pf in pf_list])
|
|
438
|
+
df = b.filter(df, cond)
|
|
439
|
+
|
|
440
|
+
# Preprocess qualify
|
|
441
|
+
if "preprocess" in t and "qualify" in t["preprocess"]:
|
|
442
|
+
p = t["preprocess"]["qualify"]
|
|
443
|
+
df = b.row_number_over(df, p["partition_by"], p["order_by"])
|
|
444
|
+
df = b.filter(df, b.col("_rn") == 1)
|
|
445
|
+
df = b.drop_columns(df, ["_rn"])
|
|
446
|
+
|
|
447
|
+
# Quality checks
|
|
448
|
+
if "quality_checks" in t:
|
|
449
|
+
qc = t["quality_checks"]
|
|
450
|
+
if "drop_nulls_in" in qc:
|
|
451
|
+
cols = qc["drop_nulls_in"]
|
|
452
|
+
logger.info(" -> [QualityCheck] drop_nulls_in: %s", cols)
|
|
453
|
+
df = b.drop_nulls(df, cols)
|
|
454
|
+
if "drop_duplicates_on" in qc:
|
|
455
|
+
cols = qc["drop_duplicates_on"]
|
|
456
|
+
logger.info(" -> [QualityCheck] drop_duplicates_on: %s", cols)
|
|
457
|
+
df = b.drop_duplicates(df, cols)
|
|
458
|
+
|
|
459
|
+
# filter_groups (OR-of-ANDs)
|
|
460
|
+
# Groups may be string-form when passed raw; normalize defensively.
|
|
461
|
+
if "filter_groups" in t:
|
|
462
|
+
from skifer.core.ir import ParsedFilter
|
|
463
|
+
from skifer.core.schema_loader import _normalize_filters
|
|
464
|
+
group_conditions = []
|
|
465
|
+
for group in t["filter_groups"]:
|
|
466
|
+
if group and isinstance(group[0], str):
|
|
467
|
+
group = _normalize_filters(group)
|
|
468
|
+
pf_list = [ParsedFilter(d["column"], d["operator"], d.get("value")) for d in group]
|
|
469
|
+
if pf_list:
|
|
470
|
+
gc = reduce(lambda a, c: a & c, [b.build_filter(pf, allow_raw_sql) for pf in pf_list])
|
|
471
|
+
group_conditions.append(gc)
|
|
472
|
+
if group_conditions:
|
|
473
|
+
combined = reduce(lambda a, c: a | c, group_conditions)
|
|
474
|
+
df = b.filter(df, combined)
|
|
475
|
+
|
|
476
|
+
# dev_limit AFTER filters (non-prod interactive only)
|
|
477
|
+
dev_limit = t.get("dev_limit") or schema_dict.get("dev_limit")
|
|
478
|
+
if dev_limit and not ctx.is_job_execution:
|
|
479
|
+
if not ctx.is_production:
|
|
480
|
+
logger.debug(
|
|
481
|
+
" -> [Dev] dev_limit=%s applied on %s after filters.", dev_limit, t["name"]
|
|
482
|
+
)
|
|
483
|
+
df = b.limit(df, dev_limit)
|
|
484
|
+
|
|
485
|
+
dfs[alias] = df
|
|
486
|
+
|
|
487
|
+
# Field selection at source
|
|
488
|
+
if "fields" in t:
|
|
489
|
+
dfs[alias] = b.select(dfs[alias], self.get_select_expressions(t["fields"], allow_raw_sql))
|
|
490
|
+
|
|
491
|
+
# 2. JOINS
|
|
492
|
+
if not dfs:
|
|
493
|
+
raise ValueError("No tables loaded to process.")
|
|
494
|
+
|
|
495
|
+
base_alias = schema_dict.get("join", [{}])[0].get("table_from") if "join" in schema_dict else list(dfs.keys())[0]
|
|
496
|
+
if isinstance(base_alias, list):
|
|
497
|
+
base_alias = base_alias[0]
|
|
498
|
+
if base_alias not in dfs:
|
|
499
|
+
base_alias = list(dfs.keys())[0]
|
|
500
|
+
|
|
501
|
+
df_main = dfs[base_alias]
|
|
502
|
+
|
|
503
|
+
if "join" in schema_dict:
|
|
504
|
+
for j in schema_dict["join"]:
|
|
505
|
+
table_from = j["table_from"]
|
|
506
|
+
table_to = j["table_to"]
|
|
507
|
+
if isinstance(table_from, list):
|
|
508
|
+
alias_l, key_l = table_from[0], table_from[1]
|
|
509
|
+
else:
|
|
510
|
+
alias_l = table_from
|
|
511
|
+
key_l = j.get("on_from")
|
|
512
|
+
if isinstance(table_to, list):
|
|
513
|
+
alias_r, key_r = table_to[0], table_to[1]
|
|
514
|
+
else:
|
|
515
|
+
alias_r = table_to
|
|
516
|
+
key_r = j.get("on_to")
|
|
517
|
+
|
|
518
|
+
on_l = key_l if isinstance(key_l, list) else [key_l]
|
|
519
|
+
on_r = key_r if isinstance(key_r, list) else [key_r]
|
|
520
|
+
join_type = _normalise_join_type(j.get("type", "left"))
|
|
521
|
+
|
|
522
|
+
logger.info(" -> [Join] %s JOIN %s(%s) -> %s(%s)", join_type.upper(), alias_l, on_l, alias_r, on_r)
|
|
523
|
+
df_to = dfs[alias_r]
|
|
524
|
+
|
|
525
|
+
if join_type == "cross":
|
|
526
|
+
if key_l is not None or key_r is not None:
|
|
527
|
+
logger.warning(" -> [Join] cross join: declared keys %s/%s are ignored", on_l, on_r)
|
|
528
|
+
df_main = b.join(df_main, df_to, on=None, how="cross")
|
|
529
|
+
elif on_l == on_r:
|
|
530
|
+
df_main = b.join(df_main, df_to, on=on_l, how=join_type)
|
|
531
|
+
else:
|
|
532
|
+
cond = reduce(lambda x, y: x & y, [df_main[lk] == df_to[rk] for lk, rk in zip(on_l, on_r)])
|
|
533
|
+
df_main = b.join(df_main, df_to, cond, join_type)
|
|
534
|
+
if join_type not in _LEFT_ONLY_JOIN_TYPES:
|
|
535
|
+
df_main = b.drop_columns(df_main, [df_to[r] for r in on_r])
|
|
536
|
+
|
|
537
|
+
# 2.5. WHERE — post-join filters (Plan 43). Applied on the joined
|
|
538
|
+
# DataFrame, never pushed down to a table: 'LEFT JOIN b WHERE b.x = v'
|
|
539
|
+
# is not equivalent to filtering b before the join (it also drops the
|
|
540
|
+
# unmatched left rows an outer join is meant to keep).
|
|
541
|
+
if "where" in schema_dict:
|
|
542
|
+
from skifer.core.ir import ParsedFilter
|
|
543
|
+
pf_list = [ParsedFilter(d["column"], d["operator"], d.get("value")) for d in schema_dict["where"]]
|
|
544
|
+
if pf_list:
|
|
545
|
+
cond = reduce(lambda a, c: a & c, [b.build_filter(pf, allow_raw_sql) for pf in pf_list])
|
|
546
|
+
df_main = b.filter(df_main, cond)
|
|
547
|
+
|
|
548
|
+
if "where_groups" in schema_dict:
|
|
549
|
+
from skifer.core.ir import ParsedFilter
|
|
550
|
+
group_conditions = []
|
|
551
|
+
for group in schema_dict["where_groups"]:
|
|
552
|
+
pf_list = [ParsedFilter(d["column"], d["operator"], d.get("value")) for d in group]
|
|
553
|
+
if pf_list:
|
|
554
|
+
gc = reduce(lambda a, c: a & c, [b.build_filter(pf, allow_raw_sql) for pf in pf_list])
|
|
555
|
+
group_conditions.append(gc)
|
|
556
|
+
if group_conditions:
|
|
557
|
+
combined = reduce(lambda a, c: a | c, group_conditions)
|
|
558
|
+
df_main = b.filter(df_main, combined)
|
|
559
|
+
|
|
560
|
+
# 3. BUSINESS RULES
|
|
561
|
+
if "business_rules" in schema_dict:
|
|
562
|
+
df_main = self._apply_business_rules(df_main, schema_dict["business_rules"])
|
|
563
|
+
|
|
564
|
+
# 4. SELECT FINAL / keep_all_columns + add_columns
|
|
565
|
+
if schema_dict.get("keep_all_columns"):
|
|
566
|
+
if "select_final" in schema_dict:
|
|
567
|
+
raise ValueError("'keep_all_columns' and 'select_final' are mutually exclusive.")
|
|
568
|
+
df_main = self._apply_add_columns(df_main, schema_dict.get("add_columns"), allow_raw_sql)
|
|
569
|
+
elif "select_final" in schema_dict:
|
|
570
|
+
df_main = b.select(df_main, self.get_select_expressions(schema_dict["select_final"], allow_raw_sql))
|
|
571
|
+
elif "aggregate" in schema_dict:
|
|
572
|
+
# add_columns run before the aggregation so they can feed group_by keys.
|
|
573
|
+
df_main = self._apply_add_columns(df_main, schema_dict.get("add_columns"), allow_raw_sql)
|
|
574
|
+
|
|
575
|
+
# 5. AGGREGATE (Plan 28) — declarative GROUP BY, terminal step
|
|
576
|
+
if "aggregate" in schema_dict:
|
|
577
|
+
df_main = self._apply_aggregate(df_main, schema_dict["aggregate"], allow_raw_sql)
|
|
578
|
+
|
|
579
|
+
return df_main
|
|
580
|
+
|
|
581
|
+
def _apply_add_columns(self, df: Any, add_columns: list | None, allow_raw_sql: bool) -> Any:
|
|
582
|
+
"""Append each ``add_columns`` entry to *df* without dropping existing columns."""
|
|
583
|
+
if not add_columns:
|
|
584
|
+
return df
|
|
585
|
+
for field_def in add_columns:
|
|
586
|
+
target_col = field_def["target"] if isinstance(field_def, dict) else field_def[1]
|
|
587
|
+
exprs = self.get_select_expressions([field_def], allow_raw_sql)
|
|
588
|
+
if exprs:
|
|
589
|
+
df = self._backend.with_column(df, target_col, exprs[0])
|
|
590
|
+
return df
|
|
591
|
+
|
|
592
|
+
def _apply_aggregate(self, df: Any, aggregate: dict, allow_raw_sql: bool) -> Any:
|
|
593
|
+
"""Apply the normalized ``aggregate:`` block — groupBy/agg then HAVING."""
|
|
594
|
+
from skifer.core.ir import ParsedFilter
|
|
595
|
+
|
|
596
|
+
b = self._backend
|
|
597
|
+
keys = aggregate["group_by"]
|
|
598
|
+
measures = aggregate["measures"]
|
|
599
|
+
logger.info(" -> [Aggregate] group_by=%s, %d measure(s)", keys, len(measures))
|
|
600
|
+
|
|
601
|
+
exprs = {m["target"]: b.agg_expr(m["func"], m["source"]) for m in measures}
|
|
602
|
+
df = b.group_by_agg(df, keys, exprs)
|
|
603
|
+
|
|
604
|
+
having = aggregate.get("having")
|
|
605
|
+
if having:
|
|
606
|
+
pf_list = [ParsedFilter(h["column"], h["operator"], h.get("value")) for h in having]
|
|
607
|
+
cond = reduce(lambda a, c: a & c, [b.build_filter(pf, allow_raw_sql) for pf in pf_list])
|
|
608
|
+
df = b.filter(df, cond)
|
|
609
|
+
return df
|