Skip to content

Commit

Permalink
Fix: redshift adapter can also use postgres adapter dispatch methods (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
crericha authored Jun 14, 2024
1 parent a1048c3 commit 9d24bca
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
26 changes: 19 additions & 7 deletions sqlmesh/dbt/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,15 +97,27 @@ def quote(self, identifier: str) -> str:

def dispatch(self, name: str, package: t.Optional[str] = None) -> t.Callable:
"""Returns a dialect-specific version of a macro with the given name."""
package = package or "dbt"
target_type = self.jinja_globals["target"]["type"]
references_to_try = [
MacroReference(package=f"{package}_{target_type}", name=f"{target_type}__{name}"),
MacroReference(package=package, name=f"{target_type}__{name}"),
MacroReference(package=package, name=f"default__{name}"),
macro_suffix = f"__{name}"

def _relevance(macro: MacroReference) -> int:
"""Lower scores more relevant."""
if macro.name.startswith("default"):
return 2
elif macro.name.startswith(target_type):
return 0
return 1

macros = [
MacroReference(package=macro_package, name=macro_name)
for macro_package, macros in self.jinja_macros.packages.items()
if (macro_package == package) or (package == "dbt" and macro_package.startswith("dbt_"))
for macro_name in macros.keys()
if macro_name.endswith(macro_suffix)
]

for reference in references_to_try:
macro_callable = self.jinja_macros.build_macro(reference, **self.jinja_globals)
for macro in sorted(macros, key=_relevance):
macro_callable = self.jinja_macros.build_macro(macro, **self.jinja_globals)
if macro_callable is not None:
return macro_callable

Expand Down
4 changes: 4 additions & 0 deletions tests/dbt/test_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,9 +148,13 @@ def test_adapter_dispatch(sushi_test_project: Project, runtime_renderer: t.Calla
context = sushi_test_project.context
renderer = runtime_renderer(context)
assert renderer("{{ adapter.dispatch('current_engine', 'customers')() }}") == "duckdb"
assert renderer("{{ adapter.dispatch('current_timestamp')() }}") == "now()"
assert renderer("{{ adapter.dispatch('current_timestamp', 'dbt')() }}") == "now()"

with pytest.raises(ConfigError, match=r"Macro 'current_engine'.*was not found."):
renderer("{{ adapter.dispatch('current_engine')() }}")
with pytest.raises(ConfigError, match=r"Macro 'current_timestamp'.*was not found."):
assert renderer("{{ adapter.dispatch('current_timestamp', 'customers')() }}")


def test_adapter_map_snapshot_tables(
Expand Down

0 comments on commit 9d24bca

Please sign in to comment.