Repository navigation
fix(jinja): route recursive macro calls through the registry wrapper #6139
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
raams95
wants to merge
1
commit into
SQLMesh:main
Choose a base branch
from
raams95:fix/jinja-recursive-macro-return
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+61
−18
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -542,9 +542,12 @@ def _parse_macro(self, name: str, package: t.Optional[str]) -> Template: | |
| macro = self._get_macro(name, package) | ||
|
|
||
| definition: nodes.Template = self._environment.parse(macro.definition) | ||
| if _is_private_macro(name): | ||
| # A workaround to expose private jinja macros. | ||
| definition = self._to_non_private_macro_def(name, definition) | ||
| # Define the macro under an internal name, so that references to it from its own body | ||
| # (e.g. recursive calls) resolve to its _MacroWrapper, which handles return(). This | ||
| # also exposes private macros, since names starting with "_" are not exported by Jinja. | ||
| for node in definition.find_all(nodes.Macro): | ||
| if node.name == name: | ||
| node.name = _internal_macro_name(name) | ||
|
|
||
| self._parser_cache[cache_key] = self._environment.from_string(definition) | ||
| return self._parser_cache[cache_key] | ||
|
|
@@ -600,15 +603,6 @@ def _macro_exists(self, name: str, package: t.Optional[str]) -> bool: | |
| def _get_macro(self, name: str, package: t.Optional[str]) -> MacroInfo: | ||
| return self.packages[package][name] if package is not None else self.root_macros[name] | ||
|
|
||
| def _to_non_private_macro_def(self, name: str, template: nodes.Template) -> nodes.Template: | ||
| for node in template.find_all((nodes.Macro, nodes.Call)): | ||
| if isinstance(node, nodes.Macro): | ||
| node.name = _non_private_name(name) | ||
| elif isinstance(node, nodes.Call) and isinstance(node.node, nodes.Name): | ||
| node.node.name = _non_private_name(name) | ||
|
|
||
| return template | ||
|
|
||
| def _create_builtin_globals(self, global_vars: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]: | ||
| """Creates Jinja builtin globals using a factory function defined in the provided module.""" | ||
| engine_adapter = global_vars.pop("engine_adapter", None) | ||
|
|
@@ -647,20 +641,19 @@ def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any: | |
|
|
||
| template = self.registry._parse_macro(self.name, self.package) | ||
| macro_callable = getattr( | ||
| template.make_module(vars=context), _non_private_name(self.name) | ||
| template.make_module(vars=context), _internal_macro_name(self.name) | ||
| ) | ||
| try: | ||
| return macro_callable(*args, **kwargs) | ||
| except MacroReturnVal as ret: | ||
| return ret.value | ||
|
|
||
|
|
||
| def _is_private_macro(name: str) -> bool: | ||
| return name.startswith("_") | ||
| _INTERNAL_MACRO_NAME_PREFIX = "sqlmesh_macro__" | ||
|
|
||
|
|
||
| def _non_private_name(name: str) -> str: | ||
| return name.lstrip("_") | ||
| def _internal_macro_name(name: str) -> str: | ||
| return f"{_INTERNAL_MACRO_NAME_PREFIX}{name}" | ||
|
|
||
|
|
||
| JINJA_REGEX = re.compile(r"({{|{%)") | ||
|
|
@@ -741,7 +734,8 @@ def extract_error_details(ex: Exception) -> str: | |
| if frame.f_code.co_name == "_invoke": | ||
| macro = frame.f_locals.get("self") | ||
| if isinstance(macro, Macro): | ||
| error_details += f" in macro: '{macro.name}'\n" | ||
| macro_name = macro.name.removeprefix(_INTERNAL_MACRO_NAME_PREFIX) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good call keeping the original name here. Maybe add one assert for a recursive or private macro so this path is covered with the prefix? |
||
| error_details += f" in macro: '{macro_name}'\n" | ||
| break | ||
| except: | ||
| # to fall back to the generic error message if frame analysis fails | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Small thing: Jinja's own errors now show the internal name. Calling
{% macro foo(a) %}with two args givesTypeError: macro 'sqlmesh_macro__foo' takes not more than 1 argument(s), on main it says'foo'. Not a blocker, but dbt folks might get confused by it. Could strip the prefix where the wrapper catches errors, or just pin the current message in a test so it's on purpose.