Skip to content
Open
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
71 changes: 71 additions & 0 deletions tests/core/test_macros.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import importlib.util
import sys
import textwrap
import typing as t
from datetime import datetime, date
from pathlib import Path

import pytest
from sqlglot import MappingSchema, ParseError, exp, parse_one
Expand Down Expand Up @@ -1362,3 +1366,70 @@ def test_safe_arithmetic_macros_keep_precedence_after_optimization(
rendered_projection = model.render_query_or_raise().selects[0]

assert rendered_projection.sql() == f'{expected} AS "result"'


def test_macro_annotation_alias_coerces_after_serialization(tmp_path: Path) -> None:
# Rendering re-executes the serialized macro. `SQL` is injected into that
# environment, but an alias used only in an annotation is not, so coercion
# is skipped and the macro receives the raw expression.
macro_path = tmp_path / "macros" / "annotation_alias.py"
macro_path.parent.mkdir()
macro_path.write_text(
textwrap.dedent(
"""
from __future__ import annotations

from sqlglot import exp
from sqlmesh import SQL as SQLType, macro
from sqlmesh.core.macros import MacroEvaluator, SQL

@macro()
def plain_sql_annotation(evaluator: MacroEvaluator, fallback_value: SQL):
if not isinstance(fallback_value, str):
raise TypeError(
f"plain expected SQL string, got {type(fallback_value).__name__}"
)
return exp.Literal.string(fallback_value)

@macro()
def alias_sql_annotation(evaluator: MacroEvaluator, fallback_value: SQLType):
if not isinstance(fallback_value, str):
got = type(fallback_value).__name__
raise TypeError(f"alias expected SQL string, got {got}: {fallback_value}")
return exp.Literal.string(fallback_value)
"""
)
)

module_name = "annotation_alias_macros"
spec = importlib.util.spec_from_file_location(module_name, macro_path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module

def load(name: str, macro_name: str):
return load_sql_based_model(
d.parse(
f"""
MODEL (name db.{name});
SELECT @{macro_name}(es.seat_id) AS result
"""
),
module_path=tmp_path,
path=tmp_path / "models" / f"{name}.sql",
dialect="duckdb",
)

try:
spec.loader.exec_module(module)
expected = "SELECT 'es.seat_id' AS \"result\""
assert load("plain_annotation", "plain_sql_annotation").render_query_or_raise().sql() == (
expected
)
assert load("alias_annotation", "alias_sql_annotation").render_query_or_raise().sql() == (
expected
)
finally:
for name in ("plain_sql_annotation", "alias_sql_annotation"):
macro.registry().pop(name, None)
sys.modules.pop(module_name, None)
Loading