Skip to content

Commit

Permalink
Fix bug where undefined Jinja variable in macro file crashes linter (s…
Browse files Browse the repository at this point in the history
…qlfluff#3751)

Co-authored-by: Barry Hart <[email protected]>
  • Loading branch information
barrywhart and Barry Hart authored Aug 16, 2022
1 parent d43e6c9 commit b720f98
Show file tree
Hide file tree
Showing 6 changed files with 26 additions and 5 deletions.
17 changes: 12 additions & 5 deletions src/sqlfluff/core/templaters/jinja.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
meta,
)
from jinja2.environment import Template
from jinja2.exceptions import UndefinedError
from jinja2.sandbox import SandboxedEnvironment

from sqlfluff.core.config import FluffConfig
Expand Down Expand Up @@ -57,11 +58,17 @@ def _extract_macros_from_template(template, env, ctx):
context = {}
macro_template = env.from_string(template, globals=ctx)
# This is kind of low level and hacky but it works
for k in macro_template.module.__dict__:
attr = getattr(macro_template.module, k)
# Is it a macro? If so install it at the name of the macro
if isinstance(attr, Macro):
context[k] = attr
try:
for k in macro_template.module.__dict__:
attr = getattr(macro_template.module, k)
# Is it a macro? If so install it at the name of the macro
if isinstance(attr, Macro):
context[k] = attr
except UndefinedError:
# This occurs if any file in the macro path references an
# undefined Jinja variable. It's safe to ignore this. Any
# meaningful issues will surface later at linting time.
pass
# Return the context
return context

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[sqlfluff]
dialect = ansi

[sqlfluff:templater:jinja]
load_macros_from_path = test/fixtures/linter/autofix/ansi/macro_file_jinja_include_undefined_variable/macros
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
SELECT id
FROM records
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
SELECT
id
FROM records
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{% include sql_file %}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
test-config:
rules:
- L036

0 comments on commit b720f98

Please sign in to comment.