tdfs4ds.agent.sql_context¶
tdfs4ds.agent.sql_context
¶
Where a feature's expression is computed: grain and filters (0.3.1.240).
An EXPLAIN answer gives the formula of a feature; this module says in which context the formula is evaluated, read from the process view DDL by code:
- the grain: the GROUP BY keys of the aggregation it sits in, or the window
(
PARTITION BY/ORDER BY) of an analytic function; - the filters deciding which rows reach it - explicit (
WHERE,HAVING,QUALIFY) and implicit: an INNER join keeps only rows with a match, a semi-join (IN (SELECT ...)/EXISTS) keeps rows found elsewhere, a predicate on the outer side of a LEFT join written inWHEREturns it into an inner join, and a TimeManager / FilterManager read restricts the rows to the current business date or segment.
The walk starts at the feature's item in the view's outer SELECT and follows the
derived tables and CTEs the expression reads, level by level. It reuses the
tokenizer of :mod:tdfs4ds.agent.sql_qualify (no new parser, no dependency).
Pure and fail-open: an unreadable view gives None.
_JOIN_WORDS
module-attribute
¶
_AGG_RE
module-attribute
¶
_AGG_RE = re.compile('\\b(SUM|AVG|COUNT|MIN|MAX|STDDEV_SAMP|STDDEV_POP|VAR_SAMP|VAR_POP|MEDIAN|PERCENTILE_CONT|PERCENTILE_DISC|CORR|COVAR_SAMP|REGR_\\w+)\\s*\\(', re.I)
_PRED_KEYWORDS
module-attribute
¶
_PRED_KEYWORDS = {'AND', 'OR', 'NOT', 'NULL', 'IS', 'IN', 'BETWEEN', 'LIKE', 'ESCAPE', 'EXISTS', 'ANY', 'ALL', 'SOME', 'CASE', 'WHEN', 'THEN', 'ELSE', 'END', 'AS', 'DATE', 'TIME', 'TIMESTAMP', 'INTERVAL', 'AT', 'ZONE', 'LOCAL', 'DAY', 'MONTH', 'YEAR', 'HOUR', 'MINUTE', 'SECOND', 'TO', 'CURRENT_DATE', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'USER', 'SESSION', 'TRUE', 'FALSE', 'UNKNOWN', 'SELECT', 'SEL', 'FROM', 'WHERE', 'OVERLAPS', 'PERIOD', 'CHARACTER', 'CHAR', 'VARCHAR', 'INTEGER', 'INT', 'DECIMAL', 'FORMAT', 'TITLE', 'CASESPECIFIC', 'UPPERCASE', 'LATIN', 'UNICODE', 'WITH', 'TIMEZONE', 'SET', 'ON'}
_collect_ctes
¶
Map CTE name → index of the ( opening its body.
Handles WITH a AS (...), b AS (...). A CTE with an explicit column list
(WITH a (c1, c2) AS (...)) is recorded with its declared columns.
_find_matching_close
¶
Index of the ) matching the ( at open_idx (or len(toks)).
_scope_extent
¶
Index one past the last token belonging to this SELECT's scope.
_tokenize
¶
Split SQL into tokens, tracking paren depth.
Comments and whitespace are skipped. String literals and quoted identifiers are emitted as single opaque tokens so their contents can never be mistaken for column references.
_paren_before
¶
Index of the '(' directly enclosing a scope (derived table / CTE body).
_clause_bounds
¶
{clause: (start_token, end_token)} for FROM, WHERE, GROUP, HAVING,
QUALIFY, ORDER at the scope's depth (the keyword itself excluded).
_split_top
¶
Split tokens [a, b) on sep (',' or 'AND') at depth d.
_between_and
¶
True when the AND at i belongs to a BETWEEN ... AND ... at depth d.
_relations
¶
FROM / JOIN entries: [{alias, name, kind, join, on, paren}].
_refs
¶
(qualified, bare) column references in tokens [a, b): qualified as
(ALIAS, COL), bare as COL.
computation_context
¶
computation_context(ddl: str, feature_name: str, managers: Optional[Dict[str, str]] = None) -> Optional[Dict[str, Any]]
The grain and the filters a feature's expression is computed under.
managers: {'DB.VIEW' or 'VIEW': 'time' | 'filter'} (e.g. from
:func:tdfs4ds.lineage.time_drivers.manager_index). Returns None when the
DDL cannot be read or the feature is not in the outer SELECT list; else::
{"feature", "expression", "levels": [{"level", "relation", "span", "group_by",
"window", "where", "having", "qualify", "distinct", "aggregated", "joins",
"semi_joins", "outer_join_as_inner", "managers"}],
"grain", "filter_columns", "join_filters", "has_filters"}
column_origin
¶
Where an output column of a view comes from, unchanged (0.3.3.25).
{"relation": <name as written>, "column": <COL>} when the column is a
plain reference (optionally aliased) all the way down through derived tables
and CTEs to a named relation; else {"reason": ...}: "transformed" (an
expression or a CAST changes the values, so a hash on it is another hash),
"ambiguous" (a bare name with several relations), "not found",
"unreadable". Pure, same tokenizer as :func:computation_context.
_simple_ref
¶
(qualifier or None, column) when seg (an item's tokens, alias
removed) is a bare or qualified column reference, else None.
column_lineage
¶
Follow :func:column_origin across views until a table: {"node",
"column"} or {"reason"}. texts: {node id: view DDL}; a relation
is matched to the current node's successors in the lineage graph by name,
so an unqualified name resolves to the object the graph recorded. Pure.
render_computation_context
¶
The fixed "Computed at" block of an EXPLAIN answer (markdown).
_pred_ops
¶
(op, index of its first token, number of tokens) of the comparison at depth d in [a, b).
_pred_refs
¶
Column references in tokens [a, b): [(qualifier or None, COLUMN)], skipping literals,
keywords, function names and every nested (SELECT ...). (refs, has_subquery).
_pred_split
¶
The conjuncts of [a, b) at depth d: split on AND (BETWEEN ... AND kept whole); a top-level OR (AND binds tighter, so splitting would change the meaning) keeps the whole range as one group.
_pred_shape
¶
(kind, sides) of one conjunct: join (column = column of another relation), equality
(column = constant, or IN a list of constants), range (<, <=, >, >=, BETWEEN), null (IS [NOT]
NULL), other. sides: the column references of the constrained side, and wrapped when that
side is more than the bare column (a function or arithmetic around it).
_plain_len
¶
Number of tokens a bare (possibly qualified) column name takes at the start of [a, b).
view_predicates
¶
The filter and join conditions of a view, conjunct by conjunct, with the relation each column
belongs to. Pure and fail-open ({"ok": False, "reason"} for an unreadable text).
Every query level is read (the outer SELECT, each derived table and CTE): the WHERE conjuncts
and the ON conjuncts of each join, split on a top-level AND. BETWEEN x AND y stays one
conjunct; a WHERE holding a top-level OR stays one group (AND binds tighter than OR).
Comments and string literals never split anything (the tokenizer reads them whole). Each predicate::
{"level", "relation_of_level", "clause": "WHERE" | "ON", "text", "kind": "join" | "equality" |
"range" | "null" | "other", "wrapped", "has_subquery",
"columns": [{"qualifier", "alias", "relation", "column", "base"}]}
relation is the name the level's FROM gives the alias (db.table when written so, the view's
database added to a bare name), (derived x) / (cte x) for a derived table; base is True
for a named relation. A bare column is given the level's only relation, else relation None.
A column of a derived table is not followed into it (its own level lists its conditions).