Skip to content

Commit 6fb471f

Browse files
authored
Feat: add dbt builtin global try_or_compiler_error (#5504)
1 parent 5edf538 commit 6fb471f

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

sqlmesh/dbt/builtin.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,22 @@ def warn(self, msg: str) -> str:
5050
return ""
5151

5252

53+
def try_or_compiler_error(
54+
message_if_exception: str, func: t.Callable, *args: t.Any, **kwargs: t.Any
55+
) -> t.Any:
56+
try:
57+
return func(*args, **kwargs)
58+
except Exception:
59+
if DBT_VERSION >= (1, 4, 0):
60+
from dbt.exceptions import CompilationError
61+
62+
raise CompilationError(message_if_exception)
63+
else:
64+
from dbt.exceptions import CompilationException # type: ignore
65+
66+
raise CompilationException(message_if_exception)
67+
68+
5369
class Api:
5470
def __init__(self, dialect: t.Optional[str]) -> None:
5571
if dialect:
@@ -411,6 +427,7 @@ def debug() -> str:
411427
"sqlmesh_incremental": True,
412428
"tojson": to_json,
413429
"toyaml": to_yaml,
430+
"try_or_compiler_error": try_or_compiler_error,
414431
"zip": do_zip,
415432
"zip_strict": lambda *args: list(zip(*args)),
416433
}

tests/dbt/test_transformation.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1592,6 +1592,29 @@ def test_exceptions(sushi_test_project: Project):
15921592
context.render('{{ exceptions.raise_compiler_error("Error") }}')
15931593

15941594

1595+
@pytest.mark.xdist_group("dbt_manifest")
1596+
def test_try_or_compiler_error(sushi_test_project: Project):
1597+
context = sushi_test_project.context
1598+
1599+
result = context.render(
1600+
'{{ try_or_compiler_error("Error message", modules.datetime.datetime.strptime, "2023-01-15", "%Y-%m-%d") }}'
1601+
)
1602+
assert "2023-01-15" in result
1603+
1604+
with pytest.raises(CompilationError, match="Invalid date format"):
1605+
context.render(
1606+
'{{ try_or_compiler_error("Invalid date format", modules.datetime.datetime.strptime, "invalid", "%Y-%m-%d") }}'
1607+
)
1608+
1609+
# built-in macro calling try_or_compiler_error works
1610+
result = context.render(
1611+
'{{ dbt.dates_in_range("2023-01-01", "2023-01-03", "%Y-%m-%d", "%Y-%m-%d") }}'
1612+
)
1613+
assert "2023-01-01" in result
1614+
assert "2023-01-02" in result
1615+
assert "2023-01-03" in result
1616+
1617+
15951618
@pytest.mark.xdist_group("dbt_manifest")
15961619
def test_modules(sushi_test_project: Project):
15971620
context = sushi_test_project.context

0 commit comments

Comments
 (0)