Skip to content

Commit 638e7cb

Browse files
authored
Fix: hydrate python env. with vars used in MacroStrReplace, MacroSQL (#2748)
1 parent 9790182 commit 638e7cb

File tree

2 files changed

+21
-7
lines changed

2 files changed

+21
-7
lines changed

sqlmesh/core/model/definition.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1983,10 +1983,10 @@ def _python_env(
19831983
elif name in variables:
19841984
used_variables.add(name)
19851985
elif (
1986-
isinstance(macro_func_or_var, exp.Identifier) and "@" in macro_func_or_var.this
1987-
):
1986+
isinstance(macro_func_or_var, (exp.Identifier, d.MacroStrReplace, d.MacroSQL))
1987+
) and "@" in macro_func_or_var.name:
19881988
for _, identifier, braced_identifier, _ in MacroStrTemplate.pattern.findall(
1989-
macro_func_or_var.this
1989+
macro_func_or_var.name
19901990
):
19911991
var_name = braced_identifier or identifier
19921992
if var_name in variables:

tests/core/test_model.py

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3887,20 +3887,34 @@ def test_macro_var(evaluator) -> exp.Expression:
38873887
kind FULL,
38883888
);
38893889
3890-
SELECT @VAR('TEST_VAR_A') AS a, @VAR('test_var_b', 'default_value') AS b, @VAR('test_var_c') AS c, @TEST_MACRO_VAR() AS d;
3890+
SELECT
3891+
@VAR('TEST_VAR_A') AS a,
3892+
@VAR('test_var_b', 'default_value') AS b,
3893+
@VAR('test_var_c') AS c,
3894+
@TEST_MACRO_VAR() AS d,
3895+
@'foo_@{test_var_e}' AS e,
3896+
@SQL(foo_@{test_var_f}) AS f,
3897+
'foo_@{test_var_unused}' AS g
38913898
""",
38923899
default_dialect="bigquery",
38933900
)
38943901

38953902
model = load_sql_based_model(
3896-
expressions, variables={"test_var_a": "test_value", "test_var_d": 1, "test_var_unused": 2}
3903+
expressions,
3904+
variables={
3905+
"test_var_a": "test_value",
3906+
"test_var_d": 1,
3907+
"test_var_e": 4,
3908+
"test_var_f": 5,
3909+
"test_var_unused": 2,
3910+
},
38973911
)
38983912
assert model.python_env[c.SQLMESH_VARS] == Executable.value(
3899-
{"test_var_a": "test_value", "test_var_d": 1}
3913+
{"test_var_a": "test_value", "test_var_d": 1, "test_var_e": 4, "test_var_f": 5}
39003914
)
39013915
assert (
39023916
model.render_query().sql(dialect="bigquery")
3903-
== "SELECT 'test_value' AS `a`, 'default_value' AS `b`, NULL AS `c`, 11 AS `d`"
3917+
== "SELECT 'test_value' AS `a`, 'default_value' AS `b`, NULL AS `c`, 11 AS `d`, 'foo_4' AS `e`, `foo_5` AS `f`, 'foo_@{test_var_unused}' AS `g`"
39043918
)
39053919

39063920
with pytest.raises(ConfigError, match=r"Macro VAR requires at least one argument.*"):

0 commit comments

Comments
 (0)