DEPosit / Scripts /pipeline_parsers /dbt_parser.py
taher-ghaleb's picture
DEPosit Dataset
031cf82
Raw
History Blame Contribute Delete
7.61 kB
"""
dbt_parser.py
~~~~~~~~~~~~~
Feature extraction for dbt SQL models and dbt_project.yml / schema.yml files.
SQL parsing uses regex rather than a full SQL parser because dbt models
are templated Jinja2+SQL, which most parsers reject. We extract structural
signals (CTEs, JOINs, window functions, ref/source calls) with targeted
patterns rather than attempting full syntax analysis.
"""
import json
import re
from pathlib import PurePosixPath
# ── dbt Jinja macro patterns ──────────────────────────────────────────────────
_REF_RE = re.compile(r"\{\{\s*ref\s*\(\s*['\"](\w+)['\"]\s*\)\s*\}\}", re.I)
_SOURCE_RE = re.compile(r"\{\{\s*source\s*\(", re.I)
_CONFIG_RE = re.compile(r"\{\{\s*config\s*\(([^}]+)\)\s*\}\}", re.I | re.S)
_MAT_RE = re.compile(r"materialized\s*=\s*['\"](\w+)['\"]", re.I)
_UKEY_RE = re.compile(r"unique_key\s*=", re.I)
# ── SQL structural patterns ───────────────────────────────────────────────────
_CTE_RE = re.compile(r"\bWITH\b", re.I)
_JOIN_RE = re.compile(r"\b(?:INNER|LEFT|RIGHT|FULL|CROSS)?\s*JOIN\b", re.I)
_WHERE_RE = re.compile(r"\bWHERE\b", re.I)
_WINDOW_RE = re.compile(r"\bOVER\s*\(", re.I)
_LIMIT_RE = re.compile(r"\bLIMIT\s+(\d+)\b", re.I)
_STAR_RE = re.compile(r"\bSELECT\s+\*", re.I)
_INCR_RE = re.compile(r"is_incremental\s*\(\s*\)", re.I)
# Hardcoded raw table reference (FROM word without ref/source) — rough heuristic
_RAW_FROM_RE = re.compile(r"\bFROM\s+([a-zA-Z_]\w*(?:\.\w+){1,2})\b", re.I)
# ── Model layer inference from path ──────────────────────────────────────────
_LAYER_MAP = {
"staging": "staging",
"stg": "staging",
"intermediate": "intermediate",
"int": "intermediate",
"marts": "marts",
"mart": "marts",
"core": "marts",
"final": "marts",
"reporting": "marts",
}
def _infer_layer(file_path: str) -> str:
parts = PurePosixPath(file_path).parts
for part in parts:
if part.lower() in _LAYER_MAP:
return _LAYER_MAP[part.lower()]
return "other"
def _extract_materialization(content: str) -> str | None:
m = _CONFIG_RE.search(content)
if m:
inner = m.group(1)
mat = _MAT_RE.search(inner)
if mat:
return mat.group(1).lower()
return None
def extract_model(content: str, file_path: str) -> dict:
"""
Parse one dbt SQL model file.
Returns a feature dict ready for INSERT into dbt_model_features.
"""
lines = content.splitlines()
file_lines = len(lines)
model_name = PurePosixPath(file_path).stem
try:
ref_count = len(_REF_RE.findall(content))
source_count = len(_SOURCE_RE.findall(content))
mat = _extract_materialization(content)
uses_incr = int(bool(_INCR_RE.search(content)))
has_ukey = int(bool(_UKEY_RE.search(content)))
cte_count = len(_CTE_RE.findall(content))
has_join = int(bool(_JOIN_RE.search(content)))
has_where = int(bool(_WHERE_RE.search(content)))
has_window = int(bool(_WINDOW_RE.search(content)))
hardcoded_limit = int(bool(_LIMIT_RE.search(content)))
select_star = int(bool(_STAR_RE.search(content)))
# No ref/source + FROM literal table name = hardcoded raw table
raw_froms = _RAW_FROM_RE.findall(content)
antipattern_no_src_ref = int(
ref_count == 0 and source_count == 0 and len(raw_froms) > 0
)
return {
"model_name": model_name,
"model_layer": _infer_layer(file_path),
"materialization": mat,
"ref_count": ref_count,
"source_count": source_count,
"cte_count": cte_count,
"has_where_clause": has_where,
"has_join": has_join,
"has_window_function": has_window,
"uses_incremental": uses_incr,
"has_unique_key": has_ukey,
"hardcoded_limit": hardcoded_limit,
"select_star": select_star,
"file_lines": file_lines,
"antipattern_incremental_no_unique_key": int(uses_incr and not has_ukey),
"antipattern_select_star": select_star,
"antipattern_no_source_no_ref": antipattern_no_src_ref,
"parse_error": None,
}
except Exception as exc: # noqa: BLE001
return {"model_name": model_name, "parse_error": str(exc),
"file_lines": file_lines}
# ── dbt_project.yml / schema.yml ─────────────────────────────────────────────
try:
import yaml as _yaml
_YAML_OK = True
except ImportError:
_YAML_OK = False
_DBT_VERSION_RE = re.compile(r"require-dbt-version\s*:\s*['\"]?([^\s'\"]+)")
_MODEL_PATHS_RE = re.compile(r"model-paths\s*:\s*\[([^\]]+)\]")
def extract_project(content: str, file_path: str) -> dict:
"""
Parse dbt_project.yml and return a summary dict for dbt_project_summary.
"""
result: dict = {"parse_error": None}
fname = PurePosixPath(file_path).name.lower()
if fname not in ("dbt_project.yml", "dbt_project.yaml"):
result["parse_error"] = "not_dbt_project_file"
return result
if _YAML_OK:
try:
data = _yaml.safe_load(content) or {}
result["dbt_version_required"] = str(
data.get("require-dbt-version", "")
) or None
paths = data.get("model-paths") or data.get("source-paths") or []
result["model_paths"] = json.dumps(paths)
result["has_tests_dir"] = int("test-paths" in data or "tests" in data)
result["has_snapshots"] = int("snapshot-paths" in data)
result["has_seeds"] = int("seed-paths" in data)
result["has_analyses"] = int("analysis-paths" in data)
except Exception as exc: # noqa: BLE001
result["parse_error"] = str(exc)
else:
# Regex fallback
m = _DBT_VERSION_RE.search(content)
result["dbt_version_required"] = m.group(1) if m else None
result["has_tests_dir"] = int("test-paths" in content)
result["has_snapshots"] = int("snapshot-paths" in content)
result["has_seeds"] = int("seed-paths" in content)
result["has_analyses"] = int("analysis-paths" in content)
return result
def extract_schema(content: str, file_path: str) -> dict:
"""
Parse a models/**/schema.yml and return per-model test coverage signals.
Returns a lightweight dict: {model_name: has_tests, ...}
Caller merges this into dbt_model_features rows.
"""
coverage: dict[str, int] = {}
if not _YAML_OK:
return coverage
try:
data = _yaml.safe_load(content) or {}
for model in data.get("models", []):
name = model.get("name", "")
tests = model.get("tests", []) or []
col_tests = any(
col.get("tests") for col in model.get("columns", [])
)
coverage[name] = int(bool(tests) or col_tests)
except Exception: # noqa: BLE001
pass
return coverage