Skip to content

Commit deb9277

Browse files
committed
fix!: fix macros with spaces to make them more consistent
this could break existing macro usage with variables that have spaces
1 parent a796474 commit deb9277

2 files changed

Lines changed: 40 additions & 2 deletions

File tree

sqlmesh/core/macros.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -240,8 +240,7 @@ def evaluate_macros(
240240
text = self.template(node.this, {})
241241
if node.this != text:
242242
changed = True
243-
node.args["this"] = text
244-
return node
243+
return exp.to_identifier(text, quoted=node.quoted or None)
245244
if node.is_string:
246245
text = node.this
247246
if has_jinja(text):
@@ -1389,6 +1388,10 @@ def _convert_sql(v: t.Any, dialect: DialectType) -> t.Any:
13891388
pass
13901389

13911390
if isinstance(v, exp.Expression):
1391+
if (isinstance(v, exp.Column) and not v.table) or (
1392+
isinstance(v, exp.Identifier) or v.is_string
1393+
):
1394+
return v.name
13921395
v = v.sql(dialect=dialect)
13931396
return v
13941397

tests/core/test_macros.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1082,3 +1082,38 @@ def test_resolve_template_table():
10821082
evaluator.transform(parsed_sql).sql(identify=True)
10831083
== 'SELECT * FROM "test_catalog"."sqlmesh__test"."test__test_model__2517971505$partitions"'
10841084
)
1085+
1086+
1087+
def test_macro_with_spaces():
1088+
sql = parse_one(
1089+
"""
1090+
SELECT
1091+
@x,
1092+
@{x},
1093+
a_@x,
1094+
a.@x,
1095+
@y,
1096+
@{y},
1097+
a_@y,
1098+
a.@y,
1099+
FROM a.@x, a."@{x}", foo(@'@x')
1100+
"""
1101+
)
1102+
evaluator = MacroEvaluator()
1103+
evaluator.evaluate(d.parse_one(""" @DEF(x, "a b") """))
1104+
evaluator.evaluate(d.parse_one(""" @DEF(y, 'a b') """))
1105+
evaluator.evaluate(d.parse_one(""" @DEF(z, a."b c") """))
1106+
1107+
for sql, expected in (
1108+
("@x", '"a b"'),
1109+
("@{x}", '"a b"'),
1110+
("a_@x", '"a_a b"'),
1111+
("a.@x", 'a."a b"'),
1112+
("@y", "'a b'"),
1113+
("@{y}", '"a b"'), # a little tricky here as it's not a string
1114+
("a_@y", '"a_a b"'),
1115+
("a.@{y}", 'a."a b"'),
1116+
("@z", 'a."b c"'),
1117+
("d.@z", 'd.a."b c"'),
1118+
):
1119+
assert evaluator.transform(parse_one(sql)).sql() == expected

0 commit comments

Comments
 (0)