pytest-dbt-macros 0.2.1__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.
- pytest_dbt_macros/__init__.py +3 -0
- pytest_dbt_macros/core.py +318 -0
- pytest_dbt_macros/plugin.py +15 -0
- pytest_dbt_macros/vendored/SOURCES.json +7 -0
- pytest_dbt_macros/vendored/bigquery/LICENSE +201 -0
- pytest_dbt_macros/vendored/bigquery/array_append.sql +3 -0
- pytest_dbt_macros/vendored/bigquery/array_concat.sql +3 -0
- pytest_dbt_macros/vendored/bigquery/array_construct.sql +7 -0
- pytest_dbt_macros/vendored/bigquery/bool_or.sql +5 -0
- pytest_dbt_macros/vendored/bigquery/date.sql +3 -0
- pytest_dbt_macros/vendored/bigquery/date_trunc.sql +7 -0
- pytest_dbt_macros/vendored/bigquery/dateadd.sql +8 -0
- pytest_dbt_macros/vendored/bigquery/datediff.sql +15 -0
- pytest_dbt_macros/vendored/bigquery/equals.sql +7 -0
- pytest_dbt_macros/vendored/bigquery/escape_single_quotes.sql +4 -0
- pytest_dbt_macros/vendored/bigquery/except.sql +5 -0
- pytest_dbt_macros/vendored/bigquery/get_columns_spec_ddl.sql +37 -0
- pytest_dbt_macros/vendored/bigquery/hash.sql +3 -0
- pytest_dbt_macros/vendored/bigquery/intersect.sql +5 -0
- pytest_dbt_macros/vendored/bigquery/listagg.sql +14 -0
- pytest_dbt_macros/vendored/bigquery/position.sql +9 -0
- pytest_dbt_macros/vendored/bigquery/right.sql +12 -0
- pytest_dbt_macros/vendored/bigquery/safe_cast.sql +27 -0
- pytest_dbt_macros/vendored/bigquery/split_part.sql +20 -0
- pytest_dbt_macros/vendored/bigquery/string_literal.sql +3 -0
- pytest_dbt_macros/vendored/bigquery/timestamps.sql +12 -0
- pytest_dbt_macros/vendored/duckdb/LICENSE +201 -0
- pytest_dbt_macros/vendored/duckdb/any_value.sql +5 -0
- pytest_dbt_macros/vendored/duckdb/date.sql +3 -0
- pytest_dbt_macros/vendored/duckdb/dateadd.sql +22 -0
- pytest_dbt_macros/vendored/duckdb/datediff.sql +12 -0
- pytest_dbt_macros/vendored/duckdb/external_location.sql +8 -0
- pytest_dbt_macros/vendored/duckdb/generate_series.sql +5 -0
- pytest_dbt_macros/vendored/duckdb/lastday.sql +14 -0
- pytest_dbt_macros/vendored/duckdb/listagg.sql +22 -0
- pytest_dbt_macros/vendored/duckdb/normalize.sql +19 -0
- pytest_dbt_macros/vendored/duckdb/splitpart.sql +3 -0
- pytest_dbt_macros/vendored/duckdb/upstream.sql +42 -0
- pytest_dbt_macros/vendored/global_project/LICENSE +201 -0
- pytest_dbt_macros/vendored/global_project/_timestamps.sql +52 -0
- pytest_dbt_macros/vendored/global_project/any_value.sql +9 -0
- pytest_dbt_macros/vendored/global_project/array_append.sql +8 -0
- pytest_dbt_macros/vendored/global_project/array_concat.sql +7 -0
- pytest_dbt_macros/vendored/global_project/array_construct.sql +12 -0
- pytest_dbt_macros/vendored/global_project/bool_or.sql +9 -0
- pytest_dbt_macros/vendored/global_project/cast.sql +7 -0
- pytest_dbt_macros/vendored/global_project/cast_bool_to_text.sql +7 -0
- pytest_dbt_macros/vendored/global_project/concat.sql +7 -0
- pytest_dbt_macros/vendored/global_project/data_types.sql +129 -0
- pytest_dbt_macros/vendored/global_project/date.sql +10 -0
- pytest_dbt_macros/vendored/global_project/date_spine.sql +75 -0
- pytest_dbt_macros/vendored/global_project/date_trunc.sql +7 -0
- pytest_dbt_macros/vendored/global_project/dateadd.sql +14 -0
- pytest_dbt_macros/vendored/global_project/datediff.sql +14 -0
- pytest_dbt_macros/vendored/global_project/equals.sql +14 -0
- pytest_dbt_macros/vendored/global_project/escape_single_quotes.sql +8 -0
- pytest_dbt_macros/vendored/global_project/except.sql +9 -0
- pytest_dbt_macros/vendored/global_project/generate_series.sql +53 -0
- pytest_dbt_macros/vendored/global_project/hash.sql +7 -0
- pytest_dbt_macros/vendored/global_project/intersect.sql +9 -0
- pytest_dbt_macros/vendored/global_project/last_day.sql +15 -0
- pytest_dbt_macros/vendored/global_project/length.sql +11 -0
- pytest_dbt_macros/vendored/global_project/listagg.sql +30 -0
- pytest_dbt_macros/vendored/global_project/literal.sql +7 -0
- pytest_dbt_macros/vendored/global_project/position.sql +11 -0
- pytest_dbt_macros/vendored/global_project/replace.sql +14 -0
- pytest_dbt_macros/vendored/global_project/right.sql +12 -0
- pytest_dbt_macros/vendored/global_project/safe_cast.sql +9 -0
- pytest_dbt_macros/vendored/global_project/split_part.sql +26 -0
- pytest_dbt_macros/vendored/postgres/LICENSE +201 -0
- pytest_dbt_macros/vendored/postgres/_timestamps.sql +20 -0
- pytest_dbt_macros/vendored/postgres/any_value.sql +7 -0
- pytest_dbt_macros/vendored/postgres/columns_spec_ddl.sql +0 -0
- pytest_dbt_macros/vendored/postgres/dateadd.sql +5 -0
- pytest_dbt_macros/vendored/postgres/datediff.sql +32 -0
- pytest_dbt_macros/vendored/postgres/equals.sql +7 -0
- pytest_dbt_macros/vendored/postgres/last_day.sql +14 -0
- pytest_dbt_macros/vendored/postgres/listagg.sql +23 -0
- pytest_dbt_macros/vendored/postgres/split_part.sql +9 -0
- pytest_dbt_macros/vendored/snowflake/LICENSE +201 -0
- pytest_dbt_macros/vendored/snowflake/array_construct.sql +3 -0
- pytest_dbt_macros/vendored/snowflake/bool_or.sql +5 -0
- pytest_dbt_macros/vendored/snowflake/cast.sql +9 -0
- pytest_dbt_macros/vendored/snowflake/equals.sql +7 -0
- pytest_dbt_macros/vendored/snowflake/escape_single_quotes.sql +4 -0
- pytest_dbt_macros/vendored/snowflake/optional.sql +16 -0
- pytest_dbt_macros/vendored/snowflake/right.sql +12 -0
- pytest_dbt_macros/vendored/snowflake/safe_cast.sql +13 -0
- pytest_dbt_macros/vendored/snowflake/timestamps.sql +20 -0
- pytest_dbt_macros-0.2.1.dist-info/METADATA +203 -0
- pytest_dbt_macros-0.2.1.dist-info/RECORD +95 -0
- pytest_dbt_macros-0.2.1.dist-info/WHEEL +4 -0
- pytest_dbt_macros-0.2.1.dist-info/entry_points.txt +2 -0
- pytest_dbt_macros-0.2.1.dist-info/licenses/LICENSE +21 -0
- pytest_dbt_macros-0.2.1.dist-info/licenses/NOTICE +28 -0
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
"""Render dbt macros with plain Jinja: no dbt-core, no adapter, no profiles.yml, no database."""
|
|
2
|
+
import collections.abc
|
|
3
|
+
import datetime
|
|
4
|
+
import functools
|
|
5
|
+
import itertools
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from types import SimpleNamespace
|
|
10
|
+
|
|
11
|
+
import jinja2
|
|
12
|
+
import sqlglot
|
|
13
|
+
import yaml
|
|
14
|
+
from jinja2 import nodes
|
|
15
|
+
from jinja2.ext import Extension
|
|
16
|
+
from sqlglot.optimizer.normalize_identifiers import normalize_identifiers
|
|
17
|
+
|
|
18
|
+
VENDORED = Path(__file__).parent / "vendored" # dbt's cross-database macros (Apache-2.0), see NOTICE
|
|
19
|
+
_MISSING = object()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class CompilationError(Exception):
|
|
23
|
+
"""Raised by `exceptions.raise_compiler_error` and by unsupported stubs."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class _Return(Exception):
|
|
27
|
+
def __init__(self, value):
|
|
28
|
+
self.value = value
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class _SkipBlocks(Extension):
|
|
32
|
+
"""dbt-only block tags (`{% test %}` etc.) are parsed and dropped, so files containing them load."""
|
|
33
|
+
|
|
34
|
+
tags = {"test", "materialization", "snapshot"}
|
|
35
|
+
|
|
36
|
+
def parse(self, parser):
|
|
37
|
+
tag = next(parser.stream).value
|
|
38
|
+
while parser.stream.current.type != "block_end":
|
|
39
|
+
next(parser.stream)
|
|
40
|
+
parser.parse_statements((f"name:end{tag}",), drop_needle=True)
|
|
41
|
+
return nodes.Output([])
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
_ENV = jinja2.Environment(extensions=["jinja2.ext.do", "jinja2.ext.loopcontrols", _SkipBlocks])
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@functools.lru_cache(maxsize=None)
|
|
48
|
+
def _parse(path, text):
|
|
49
|
+
"""Parse a file once per process; returns {macro name: AST of that macro alone}.
|
|
50
|
+
|
|
51
|
+
Like dbt, every macro becomes its own template, so sibling calls go through the namespace
|
|
52
|
+
(and therefore through `return` handling) instead of Jinja's file-local variables."""
|
|
53
|
+
ast = _ENV.parse(text, filename=path)
|
|
54
|
+
return {n.name: nodes.Template([n], lineno=n.lineno) for n in ast.body if isinstance(n, nodes.Macro)}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@functools.lru_cache(maxsize=None)
|
|
58
|
+
def _compile(path, name, text):
|
|
59
|
+
return _ENV.template_class.from_code(_ENV, _ENV.compile(_parse(path, text)[name], filename=path), _ENV.globals)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class Relation(str):
|
|
63
|
+
"""What `ref()`/`source()` return: renders as the bare name (like SQLFluff's mock), not a quoted path."""
|
|
64
|
+
|
|
65
|
+
def __new__(cls, identifier, schema=None, database=None):
|
|
66
|
+
self = super().__new__(cls, identifier)
|
|
67
|
+
self.identifier, self.schema, self.database = identifier, schema, database
|
|
68
|
+
self.is_cte = False
|
|
69
|
+
return self
|
|
70
|
+
|
|
71
|
+
def get(self, key, default=None): # dbt-utils' _is_relation() wants a mapping with metadata.type
|
|
72
|
+
return {"metadata": {"type": "Relation"}}.get(key, default)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
collections.abc.Mapping.register(Relation)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class _Namespace:
|
|
79
|
+
"""`dbt_utils.star(...)`: attribute access on a package name."""
|
|
80
|
+
|
|
81
|
+
def __init__(self, project, package):
|
|
82
|
+
self._p, self._pkg = project, package
|
|
83
|
+
|
|
84
|
+
def __getattr__(self, name):
|
|
85
|
+
if name.startswith("__") or name not in self._p._macros.get(self._pkg, {}):
|
|
86
|
+
raise AttributeError(f"package '{self._pkg}' has no macro '{name}'")
|
|
87
|
+
return functools.partial(self._p._call, self._pkg, name)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class _Adapter:
|
|
91
|
+
"""The `adapter` context object. Only what rendering needs; everything else needs a database."""
|
|
92
|
+
|
|
93
|
+
def __init__(self, project, package):
|
|
94
|
+
self._p, self._pkg = project, package
|
|
95
|
+
|
|
96
|
+
def type(self):
|
|
97
|
+
return self._p.target["type"]
|
|
98
|
+
|
|
99
|
+
def quote(self, identifier):
|
|
100
|
+
q = "`" if self.type() == "bigquery" else '"'
|
|
101
|
+
return f"{q}{identifier}{q}"
|
|
102
|
+
|
|
103
|
+
def get_columns_in_relation(self, relation):
|
|
104
|
+
cols = self._p.columns
|
|
105
|
+
if relation.identifier not in cols:
|
|
106
|
+
raise CompilationError(f"no columns declared for '{relation.identifier}'; set dbt_macros.columns['{relation.identifier}'] = [...]")
|
|
107
|
+
return [SimpleNamespace(column=c, name=c) for c in cols[relation.identifier]]
|
|
108
|
+
|
|
109
|
+
def __getattr__(self, name):
|
|
110
|
+
raise CompilationError(f"adapter.{name} needs a database connection; pytest-dbt-macros has none")
|
|
111
|
+
|
|
112
|
+
def dispatch(self, macro_name, macro_namespace=None, packages=None):
|
|
113
|
+
# Mirrors dbt-core's ProviderContext.dispatch.
|
|
114
|
+
p = self._p
|
|
115
|
+
if "." in macro_name:
|
|
116
|
+
raise CompilationError(f'In adapter.dispatch, got a macro name of "{macro_name}", but "." is not valid')
|
|
117
|
+
if packages is not None:
|
|
118
|
+
raise CompilationError("adapter.dispatch(packages=...) was removed; use macro_namespace")
|
|
119
|
+
search = [None]
|
|
120
|
+
if macro_namespace is not None:
|
|
121
|
+
order = next((d["search_order"] for d in p.dispatch if d.get("macro_namespace") == macro_namespace), None)
|
|
122
|
+
if order:
|
|
123
|
+
search = order
|
|
124
|
+
elif macro_namespace in p.dependencies:
|
|
125
|
+
search = [p.root, macro_namespace]
|
|
126
|
+
t = p.target["type"]
|
|
127
|
+
tried = []
|
|
128
|
+
for package in search:
|
|
129
|
+
for prefix in [t, *p.parents.get(t, []), "default"]:
|
|
130
|
+
name = f"{prefix}__{macro_name}"
|
|
131
|
+
tried.append(f"{package}.{name}" if package else name)
|
|
132
|
+
if found := p._lookup(self._pkg, package, name):
|
|
133
|
+
return found
|
|
134
|
+
raise CompilationError(
|
|
135
|
+
f"In dispatch: No macro named '{macro_name}' found within namespace: '{macro_namespace}'\n"
|
|
136
|
+
f" Searched for: {', '.join(map(repr, tried))}"
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class _Config:
|
|
141
|
+
def __call__(self, *args, **kwargs):
|
|
142
|
+
return ""
|
|
143
|
+
|
|
144
|
+
def get(self, key, default=None):
|
|
145
|
+
return default
|
|
146
|
+
|
|
147
|
+
def require(self, key):
|
|
148
|
+
raise CompilationError(f"config.require('{key}'): model config is not available in macro tests")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class MacroProject:
|
|
152
|
+
"""A dbt project's macros, callable from Python.
|
|
153
|
+
|
|
154
|
+
>>> p = MacroProject("path/to/dbt/project", target="snowflake")
|
|
155
|
+
>>> p.dbt_utils.generate_surrogate_key(["a", "b"]) # package namespace
|
|
156
|
+
>>> p.my_macro(1, 2) # macro of the project itself
|
|
157
|
+
>>> p.render("{{ my_macro(1) }}") # any Jinja, in the project's context
|
|
158
|
+
Change `p.target["type"]`, `p.vars`, `p.env` at any time; macros read them at call time.
|
|
159
|
+
"""
|
|
160
|
+
|
|
161
|
+
def __init__(self, project_dir=".", target="postgres", vars=None, env=None):
|
|
162
|
+
self.target = {"type": target, "name": "test", "schema": "public", "database": "db", "threads": 1}
|
|
163
|
+
self.env = dict(env or {}) # overrides os.environ for env_var()
|
|
164
|
+
self.parents = {"redshift": ["postgres"]} # adapter -> parent adapters for dispatch
|
|
165
|
+
self.columns = {} # relation name -> column names, what adapter.get_columns_in_relation() returns
|
|
166
|
+
self.logs = [] # messages from log() / exceptions.warn()
|
|
167
|
+
self._macros = {} # package -> {macro name: [(path, name, text), jinja macro once loaded]}
|
|
168
|
+
self._ctx_cache = {}
|
|
169
|
+
project_dir = Path(project_dir)
|
|
170
|
+
for f in sorted(VENDORED.rglob("*.sql")):
|
|
171
|
+
self._add("dbt", f)
|
|
172
|
+
cfg = self._add_project(project_dir)
|
|
173
|
+
self.root = cfg["name"]
|
|
174
|
+
self.dispatch = cfg.get("dispatch") or []
|
|
175
|
+
pv = cfg.get("vars") or {}
|
|
176
|
+
self.vars = {**{k: v for k, v in pv.items() if k != self.root}, **(pv.get(self.root) or {}), **(vars or {})}
|
|
177
|
+
self.dependencies = set()
|
|
178
|
+
for d in sorted((project_dir / cfg.get("packages-install-path", "dbt_packages")).glob("*/dbt_project.yml")):
|
|
179
|
+
self.dependencies.add(self._add_project(d.parent)["name"])
|
|
180
|
+
self._stubs = self._make_stubs()
|
|
181
|
+
|
|
182
|
+
# -- loading -----------------------------------------------------------------------------
|
|
183
|
+
def _add(self, package, path):
|
|
184
|
+
text = path.read_text()
|
|
185
|
+
for name in _parse(str(path), text):
|
|
186
|
+
self._macros.setdefault(package, {})[name] = [(str(path), name, text), None] # [source, loaded macro]
|
|
187
|
+
|
|
188
|
+
def _add_project(self, path):
|
|
189
|
+
cfg = yaml.safe_load((path / "dbt_project.yml").read_text()) if (path / "dbt_project.yml").exists() else {}
|
|
190
|
+
cfg.setdefault("name", "project")
|
|
191
|
+
for rel in cfg.get("macro-paths", ["macros"]):
|
|
192
|
+
for f in sorted((path / rel).rglob("*.sql")):
|
|
193
|
+
self._add(cfg["name"], f)
|
|
194
|
+
return cfg
|
|
195
|
+
|
|
196
|
+
# -- the Jinja context dbt macros see ------------------------------------------------------
|
|
197
|
+
def _make_stubs(self):
|
|
198
|
+
def var(name, default=_MISSING):
|
|
199
|
+
if name in self.vars:
|
|
200
|
+
return self.vars[name]
|
|
201
|
+
if default is _MISSING:
|
|
202
|
+
raise CompilationError(f"Required var '{name}' not found; pass vars={{'{name}': ...}} to MacroProject")
|
|
203
|
+
return default
|
|
204
|
+
|
|
205
|
+
def env_var(name, default=_MISSING):
|
|
206
|
+
value = {**os.environ, **self.env}.get(name, default)
|
|
207
|
+
if value is _MISSING:
|
|
208
|
+
raise CompilationError(f"Env var required but not provided: '{name}'")
|
|
209
|
+
return value
|
|
210
|
+
|
|
211
|
+
def ref(*args, **kwargs):
|
|
212
|
+
return Relation(args[-1], self.target["schema"], self.target["database"])
|
|
213
|
+
|
|
214
|
+
def source(source_name, table_name):
|
|
215
|
+
return Relation(f"{source_name}.{table_name}", self.target["schema"], self.target["database"])
|
|
216
|
+
|
|
217
|
+
def return_(value):
|
|
218
|
+
raise _Return(value)
|
|
219
|
+
|
|
220
|
+
def log(msg, info=False):
|
|
221
|
+
self.logs.append(str(msg))
|
|
222
|
+
return ""
|
|
223
|
+
|
|
224
|
+
def needs_db(name):
|
|
225
|
+
def fail(*args, **kwargs):
|
|
226
|
+
raise CompilationError(f"{name} needs a database connection; pytest-dbt-macros has none")
|
|
227
|
+
|
|
228
|
+
return fail
|
|
229
|
+
|
|
230
|
+
def raise_compiler_error(msg, node=None):
|
|
231
|
+
raise CompilationError(str(msg))
|
|
232
|
+
|
|
233
|
+
exceptions = SimpleNamespace(
|
|
234
|
+
raise_compiler_error=raise_compiler_error,
|
|
235
|
+
raise_not_implemented=raise_compiler_error,
|
|
236
|
+
warn=lambda msg, node=None: self.logs.append(str(msg)) or "",
|
|
237
|
+
)
|
|
238
|
+
return dict(
|
|
239
|
+
var=var, env_var=env_var, ref=ref, source=source, log=log, exceptions=exceptions,
|
|
240
|
+
**{n: needs_db(n) for n in ('run_query', 'statement', 'load_result')},
|
|
241
|
+
target=self.target, flags=SimpleNamespace(WHICH="compile"), config=_Config(), execute=True, api=SimpleNamespace(Column=self._column_api()),
|
|
242
|
+
dbt_version="1.12.6", # the version the baselines were compiled with
|
|
243
|
+
modules=SimpleNamespace(datetime=datetime, re=re, itertools=itertools),
|
|
244
|
+
**{"return": return_},
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
def _column_api(self):
|
|
248
|
+
"""api.Column.translate_type / numeric_type, as in dbt-adapters' Column (BigQuery differs, the rest share it)."""
|
|
249
|
+
bigquery = lambda: self.target["type"] == "bigquery" # noqa: E731
|
|
250
|
+
|
|
251
|
+
def translate_type(dtype):
|
|
252
|
+
labels = {"TEXT": "STRING", "FLOAT": "FLOAT64", "INTEGER": "INT64"} if bigquery() else {"STRING": "TEXT"}
|
|
253
|
+
return labels.get(dtype.upper(), dtype)
|
|
254
|
+
|
|
255
|
+
def numeric_type(dtype, precision, scale):
|
|
256
|
+
return dtype if bigquery() or precision is None or scale is None else f"{dtype}({precision},{scale})"
|
|
257
|
+
|
|
258
|
+
return SimpleNamespace(translate_type=translate_type, numeric_type=numeric_type)
|
|
259
|
+
|
|
260
|
+
def _context(self, package):
|
|
261
|
+
"""Names visible inside `package`'s macros, lowest to highest priority (same order as dbt)."""
|
|
262
|
+
if package not in self._ctx_cache:
|
|
263
|
+
ctx = dict(self._stubs, adapter=_Adapter(self, package))
|
|
264
|
+
ctx.update(self._flat("dbt")) # dbt's own macros are callable bare, too
|
|
265
|
+
ctx.update({pkg: _Namespace(self, pkg) for pkg in self._macros})
|
|
266
|
+
ctx.update(self._flat(self.root))
|
|
267
|
+
ctx.update(self._flat(package))
|
|
268
|
+
self._ctx_cache[package] = ctx
|
|
269
|
+
return self._ctx_cache[package]
|
|
270
|
+
|
|
271
|
+
def _flat(self, package):
|
|
272
|
+
return {n: functools.partial(self._call, package, n) for n in self._macros.get(package, {})}
|
|
273
|
+
|
|
274
|
+
def _lookup(self, from_package, package, name):
|
|
275
|
+
"""dispatch lookup: a named package, or (None) the calling package, then the root project, then dbt."""
|
|
276
|
+
for pkg in [package] if package else [from_package, self.root, "dbt"]:
|
|
277
|
+
if name in self._macros.get(pkg, {}):
|
|
278
|
+
return functools.partial(self._call, pkg, name)
|
|
279
|
+
|
|
280
|
+
def _call(self, package, name, *args, **kwargs):
|
|
281
|
+
entry = self._macros[package][name]
|
|
282
|
+
if entry[1] is None: # define the macro once, in this package's context
|
|
283
|
+
template = _compile(*entry[0])
|
|
284
|
+
context = template.new_context(self._context(package))
|
|
285
|
+
for _ in template.root_render_func(context):
|
|
286
|
+
pass
|
|
287
|
+
entry[1] = context.vars[name]
|
|
288
|
+
try:
|
|
289
|
+
return str(entry[1](*args, **kwargs))
|
|
290
|
+
except _Return as r:
|
|
291
|
+
return r.value
|
|
292
|
+
|
|
293
|
+
# -- public API ----------------------------------------------------------------------------
|
|
294
|
+
def render(self, source, **context):
|
|
295
|
+
"""Render a Jinja string as if it were a model body, in the root project's context."""
|
|
296
|
+
return _ENV.from_string(source).render({**self._context(self.root), **context})
|
|
297
|
+
|
|
298
|
+
def __getattr__(self, name):
|
|
299
|
+
if name.startswith("_") or "_macros" not in self.__dict__:
|
|
300
|
+
raise AttributeError(name)
|
|
301
|
+
if name in self._macros:
|
|
302
|
+
return _Namespace(self, name)
|
|
303
|
+
if name in self._macros.get(self.root, {}):
|
|
304
|
+
return functools.partial(self._call, self.root, name)
|
|
305
|
+
raise AttributeError(f"no package or root macro named '{name}'")
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _normalize(sql, dialect):
|
|
309
|
+
try:
|
|
310
|
+
return ";\n".join(normalize_identifiers(t, dialect).sql(dialect=dialect) for t in sqlglot.parse(sql, read=dialect) if t)
|
|
311
|
+
except sqlglot.errors.SqlglotError: # not parseable (e.g. a bare column list): compare whitespace-insensitively
|
|
312
|
+
return " ".join(sql.split())
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def assert_sql_equal(actual, expected, dialect=None):
|
|
316
|
+
"""Assert two SQL strings are equal after sqlglot normalization (whitespace, keyword case, identifier case)."""
|
|
317
|
+
a, b = _normalize(actual, dialect), _normalize(expected, dialect)
|
|
318
|
+
assert a == b, f"SQL differs ({dialect or 'generic'}):\n actual: {a}\n expected: {b}"
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
|
|
3
|
+
from .core import MacroProject
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@pytest.fixture
|
|
7
|
+
def dbt_project_dir(request):
|
|
8
|
+
"""Directory holding dbt_project.yml (default: where pytest was started). Override this fixture to point elsewhere."""
|
|
9
|
+
return request.config.invocation_params.dir
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@pytest.fixture
|
|
13
|
+
def dbt_macros(dbt_project_dir):
|
|
14
|
+
"""The project's macros as Python callables; see MacroProject."""
|
|
15
|
+
return MacroProject(dbt_project_dir)
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "{}"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2021 dbt Labs, Inc.
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{% macro bigquery__datediff(first_date, second_date, datepart) -%}
|
|
2
|
+
|
|
3
|
+
{% if dbt_version[0] == 1 and dbt_version[2] >= 2 %}
|
|
4
|
+
{{ return(dbt.datediff(first_date, second_date, datepart)) }}
|
|
5
|
+
{% else %}
|
|
6
|
+
|
|
7
|
+
datetime_diff(
|
|
8
|
+
cast({{second_date}} as datetime),
|
|
9
|
+
cast({{first_date}} as datetime),
|
|
10
|
+
{{datepart}}
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
{% endif %}
|
|
14
|
+
|
|
15
|
+
{%- endmacro %}
|