|
| 1 | +"""Direct database query execution via dbt adapter connection. |
| 2 | +
|
| 3 | +Bypasses ``run_operation`` log-parsing entirely so that query results are |
| 4 | +never lost due to intermittent log-capture issues in the CLI / fusion |
| 5 | +runners. |
| 6 | +""" |
| 7 | + |
| 8 | +import json |
| 9 | +import multiprocessing |
| 10 | +import os |
| 11 | +import re |
| 12 | +from datetime import date, datetime, time |
| 13 | +from decimal import Decimal |
| 14 | +from pathlib import Path |
| 15 | +from typing import Any, Dict, List, Optional |
| 16 | + |
| 17 | +from dbt.adapters.base import BaseAdapter |
| 18 | +from logger import get_logger |
| 19 | + |
| 20 | +logger = get_logger(__name__) |
| 21 | + |
| 22 | + |
| 23 | +class UnsupportedJinjaError(Exception): |
| 24 | + """Raised when a query contains Jinja expressions beyond ref()/source().""" |
| 25 | + |
| 26 | + def __init__(self, query: str) -> None: |
| 27 | + self.query = query |
| 28 | + super().__init__( |
| 29 | + "Query contains Jinja expressions beyond {{ ref() }} / {{ source() }} " |
| 30 | + "which cannot be executed via the direct adapter path. " |
| 31 | + "Use the run_operation fallback instead." |
| 32 | + ) |
| 33 | + |
| 34 | + |
| 35 | +# Pattern that matches {{ ref('name') }} or {{ ref("name") }} with optional whitespace |
| 36 | +_REF_PATTERN = re.compile(r"\{\{\s*ref\(\s*['\"]([^'\"]+)['\"]\s*\)\s*\}\}") |
| 37 | + |
| 38 | +# Pattern that matches {{ source('source_name', 'table_name') }} |
| 39 | +_SOURCE_PATTERN = re.compile( |
| 40 | + r"\{\{\s*source\(\s*['\"]([^'\"]+)['\"]\s*,\s*['\"]([^'\"]+)['\"]\s*\)\s*\}\}" |
| 41 | +) |
| 42 | + |
| 43 | +# Pattern that matches any Jinja expression {{ ... }} |
| 44 | +_JINJA_EXPR_PATTERN = re.compile(r"\{\{.*?\}\}") |
| 45 | + |
| 46 | + |
| 47 | +def _serialize_value(val: Any) -> Any: |
| 48 | + """Mimic elementary's ``agate_to_dicts`` serialisation. |
| 49 | +
|
| 50 | + * ``Decimal`` → ``int`` (no fractional part) or ``float`` |
| 51 | + * ``datetime`` / ``date`` / ``time`` → ISO-format string |
| 52 | + * Everything else is returned unchanged. |
| 53 | + """ |
| 54 | + if isinstance(val, Decimal): |
| 55 | + # Match the Jinja macro: normalize, then int or float |
| 56 | + normalized = val.normalize() |
| 57 | + if normalized.as_tuple().exponent >= 0: |
| 58 | + return int(normalized) |
| 59 | + return float(normalized) |
| 60 | + if isinstance(val, (datetime, date, time)): |
| 61 | + return val.isoformat() |
| 62 | + return val |
| 63 | + |
| 64 | + |
| 65 | +class AdapterQueryRunner: |
| 66 | + """Execute SQL directly through a dbt adapter connection. |
| 67 | +
|
| 68 | + Parameters |
| 69 | + ---------- |
| 70 | + project_dir : str |
| 71 | + Path to the dbt project directory. |
| 72 | + target : str |
| 73 | + Name of the dbt target / profile output to use. |
| 74 | + """ |
| 75 | + |
| 76 | + def __init__(self, project_dir: str, target: str) -> None: |
| 77 | + self._project_dir = project_dir |
| 78 | + self._target = target |
| 79 | + self._adapter: BaseAdapter = self._create_adapter(project_dir, target) |
| 80 | + self._ref_map: Optional[Dict[str, str]] = None |
| 81 | + self._source_map: Optional[Dict[tuple, str]] = None |
| 82 | + |
| 83 | + # ------------------------------------------------------------------ |
| 84 | + # Adapter bootstrap |
| 85 | + # ------------------------------------------------------------------ |
| 86 | + |
| 87 | + @staticmethod |
| 88 | + def _create_adapter(project_dir: str, target: str) -> BaseAdapter: |
| 89 | + from argparse import Namespace |
| 90 | + |
| 91 | + from dbt.adapters.factory import get_adapter, register_adapter, reset_adapters |
| 92 | + from dbt.config.runtime import RuntimeConfig |
| 93 | + from dbt.flags import set_from_args |
| 94 | + |
| 95 | + profiles_dir = os.environ.get("DBT_PROFILES_DIR", os.path.expanduser("~/.dbt")) |
| 96 | + args = Namespace( |
| 97 | + project_dir=project_dir, |
| 98 | + profiles_dir=profiles_dir, |
| 99 | + target=target, |
| 100 | + threads=1, |
| 101 | + vars={}, |
| 102 | + profile=None, |
| 103 | + PROFILES_DIR=profiles_dir, |
| 104 | + PROJECT_DIR=project_dir, |
| 105 | + ) |
| 106 | + set_from_args(args, None) |
| 107 | + config = RuntimeConfig.from_args(args) |
| 108 | + |
| 109 | + reset_adapters() |
| 110 | + mp_context = multiprocessing.get_context("spawn") |
| 111 | + register_adapter(config, mp_context) |
| 112 | + return get_adapter(config) |
| 113 | + |
| 114 | + # ------------------------------------------------------------------ |
| 115 | + # Ref resolution |
| 116 | + # ------------------------------------------------------------------ |
| 117 | + |
| 118 | + def _load_manifest_maps(self) -> None: |
| 119 | + """Load ref and source maps from the dbt manifest.""" |
| 120 | + manifest_path = Path(self._project_dir) / "target" / "manifest.json" |
| 121 | + if not manifest_path.exists(): |
| 122 | + raise FileNotFoundError( |
| 123 | + f"Manifest not found at {manifest_path}. " |
| 124 | + "Run `dbt run` or `dbt compile` first." |
| 125 | + ) |
| 126 | + with open(manifest_path) as fh: |
| 127 | + manifest = json.load(fh) |
| 128 | + |
| 129 | + ref_map: Dict[str, str] = {} |
| 130 | + for node in manifest.get("nodes", {}).values(): |
| 131 | + relation_name = node.get("relation_name") |
| 132 | + name = node.get("name") |
| 133 | + if relation_name and name: |
| 134 | + ref_map[name] = relation_name |
| 135 | + |
| 136 | + source_map: Dict[tuple, str] = {} |
| 137 | + for source in manifest.get("sources", {}).values(): |
| 138 | + relation_name = source.get("relation_name") |
| 139 | + name = source.get("name") |
| 140 | + source_name = source.get("source_name") |
| 141 | + if relation_name and source_name and name: |
| 142 | + source_map[(source_name, name)] = relation_name |
| 143 | + # Also register source tables by name for simple ref() lookups |
| 144 | + ref_map.setdefault(name, relation_name) |
| 145 | + |
| 146 | + self._ref_map = ref_map |
| 147 | + self._source_map = source_map |
| 148 | + |
| 149 | + def _ensure_maps_loaded(self) -> None: |
| 150 | + """Lazily load manifest maps on first use.""" |
| 151 | + if self._ref_map is None: |
| 152 | + self._load_manifest_maps() |
| 153 | + |
| 154 | + def resolve_refs(self, query: str) -> str: |
| 155 | + """Replace ``{{ ref('name') }}`` and ``{{ source('x','y') }}`` with relation names.""" |
| 156 | + self._ensure_maps_loaded() |
| 157 | + assert self._ref_map is not None |
| 158 | + assert self._source_map is not None |
| 159 | + |
| 160 | + def _replace_ref(match: re.Match) -> str: # type: ignore[type-arg] |
| 161 | + name = match.group(1) |
| 162 | + if name not in self._ref_map: |
| 163 | + # Manifest may have changed (temp models/seeds); reload once. |
| 164 | + self._load_manifest_maps() |
| 165 | + assert self._ref_map is not None |
| 166 | + if name not in self._ref_map: |
| 167 | + raise ValueError( |
| 168 | + f"Cannot resolve ref('{name}'): not found in dbt manifest." |
| 169 | + ) |
| 170 | + return self._ref_map[name] |
| 171 | + |
| 172 | + def _replace_source(match: re.Match) -> str: # type: ignore[type-arg] |
| 173 | + source_name, table_name = match.group(1), match.group(2) |
| 174 | + key = (source_name, table_name) |
| 175 | + if self._source_map is None or key not in self._source_map: |
| 176 | + self._load_manifest_maps() |
| 177 | + assert self._source_map is not None |
| 178 | + if key not in self._source_map: |
| 179 | + raise ValueError( |
| 180 | + f"Cannot resolve source('{source_name}', '{table_name}'): " |
| 181 | + "not found in dbt manifest." |
| 182 | + ) |
| 183 | + return self._source_map[key] |
| 184 | + |
| 185 | + query = _REF_PATTERN.sub(_replace_ref, query) |
| 186 | + query = _SOURCE_PATTERN.sub(_replace_source, query) |
| 187 | + return query |
| 188 | + |
| 189 | + # ------------------------------------------------------------------ |
| 190 | + # Query execution |
| 191 | + # ------------------------------------------------------------------ |
| 192 | + |
| 193 | + @staticmethod |
| 194 | + def has_non_ref_jinja(query: str) -> bool: |
| 195 | + """Return True if *query* contains Jinja beyond ``{{ ref() }}`` / ``{{ source() }}``.""" |
| 196 | + stripped = _REF_PATTERN.sub("", query) |
| 197 | + stripped = _SOURCE_PATTERN.sub("", stripped) |
| 198 | + return bool(_JINJA_EXPR_PATTERN.search(stripped)) |
| 199 | + |
| 200 | + def run_query(self, prerendered_query: str) -> List[Dict[str, Any]]: |
| 201 | + """Render Jinja refs/sources and execute a query, returning rows as dicts. |
| 202 | +
|
| 203 | + Column names are lower-cased and values are serialised to match the |
| 204 | + behaviour of ``elementary.agate_to_dicts``. |
| 205 | +
|
| 206 | + Only ``{{ ref() }}`` and ``{{ source() }}`` Jinja expressions are |
| 207 | + supported. Raises ``UnsupportedJinjaError`` if the query contains |
| 208 | + other Jinja expressions. |
| 209 | + """ |
| 210 | + if self.has_non_ref_jinja(prerendered_query): |
| 211 | + raise UnsupportedJinjaError(prerendered_query) |
| 212 | + sql = self.resolve_refs(prerendered_query) |
| 213 | + with self._adapter.connection_named("run_query"): |
| 214 | + _response, table = self._adapter.execute(sql, fetch=True) |
| 215 | + |
| 216 | + # Convert agate Table → list[dict] matching agate_to_dicts behaviour |
| 217 | + columns = [c.lower() for c in table.column_names] |
| 218 | + return [ |
| 219 | + {col: _serialize_value(val) for col, val in zip(columns, row)} |
| 220 | + for row in table |
| 221 | + ] |
0 commit comments