Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions sqlmesh/core/dialect.py
Original file line number Diff line number Diff line change
Expand Up @@ -782,6 +782,10 @@ def _parse_interval_span(self: Parser, this: exp.Expr) -> exp.Interval:

def _override(klass: t.Type[Tokenizer | Parser], func: t.Callable) -> None:
name = func.__name__
if getattr(klass, name, None) is func:
# Already overridden. Re-applying would save the override itself as the
# "original", making the wrapper call itself and recurse infinitely.
return
setattr(klass, f"_{name}", getattr(klass, name))
setattr(klass, name, func)

Expand Down Expand Up @@ -1170,11 +1174,12 @@ def extend_sqlglot() -> None:
MacroDef,
)

generator.UNWRAPPED_INTERVAL_VALUES = (
*generator.UNWRAPPED_INTERVAL_VALUES,
MacroStrReplace,
MacroVar,
)
if MacroVar not in generator.UNWRAPPED_INTERVAL_VALUES:
generator.UNWRAPPED_INTERVAL_VALUES = (
*generator.UNWRAPPED_INTERVAL_VALUES,
MacroStrReplace,
MacroVar,
)

_override(Parser, _parse_select)
_override(Parser, _parse_statement)
Expand Down
14 changes: 14 additions & 0 deletions tests/core/test_dialect.py
Original file line number Diff line number Diff line change
Expand Up @@ -1185,3 +1185,17 @@ def test_pipe_syntax():
ast.sql("bigquery")
== "SELECT * FROM (WITH __tmp1 AS (SELECT id FROM t2) SELECT * FROM __tmp1)"
)


def test_extend_sqlglot_is_idempotent():
# extend_sqlglot() runs at import time; calling it again must not re-wrap the
# already-installed overrides, otherwise they call themselves (RecursionError).
from sqlglot.generator import Generator

before = Generator.UNWRAPPED_INTERVAL_VALUES

d.extend_sqlglot()

assert parse_one("SELECT CAST(1 AS INT)").sql() == "SELECT CAST(1 AS INT)"
# The class-level registries must not grow on repeated calls.
assert Generator.UNWRAPPED_INTERVAL_VALUES == before