Skip to content

Commit

Permalink
fix: jinja templates containing parentheses or curly braces are not l…
Browse files Browse the repository at this point in the history
…imited to output strings anymore (#1769)

* fix: fix jinja detection (allow parentheses and curly braces which are valid)

* chore: update CHANGELOG.md
  • Loading branch information
fspot authored Sep 13, 2024
1 parent 3763087 commit 8a418b0
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

## Unreleased

### Changed

- jinja templates :: expressions containing parentheses or curly braces are not limited to output
strings anymore.

## [7.0.1] 2024-09-10

### Fix
Expand Down
10 changes: 10 additions & 0 deletions tests/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,16 @@ def test_apply_parameter_to_query_do_nothing():
{"city": "Paris"},
{"domain": "Test"},
),
(
{"answer": "{{ foo + bar }}"},
{"foo": 40, "bar": 2},
{"answer": 42},
),
(
{"value": "{{ (user or dict()).get('attributes', dict()).get('LABEL', 250) }}"},
{},
{"value": 250},
),
],
)
def test_nosql_apply_parameters_to_query(query, params, expected):
Expand Down
11 changes: 8 additions & 3 deletions toucan_connectors/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,13 @@ def is_jinja_alone(s: str) -> bool:
In the 2nd case, we will always render the result as a string.
"""
return re.match(RE_JINJA_ALONE, s) or (s.startswith("{%") and s.endswith("%}"))
if s.startswith("{{") and s.endswith("}}"):
inside = s[2:-2]
return "{{" not in inside and "}}" not in inside
elif s.startswith("{%") and s.endswith("%}"):
return True
else:
return False


def _has_parameters(query: dict | list[dict] | tuple | str) -> bool:
Expand Down Expand Up @@ -155,10 +161,9 @@ def _render_query(query: dict | list[dict] | tuple | str, parameters: dict | Non

# Add quotes to string parameters to keep type if not complex
clean_p = deepcopy(parameters)
if re.match(RE_JINJA_ALONE, query):
clean_p = _prepare_parameters(clean_p)

if is_jinja_alone(query):
clean_p = _prepare_parameters(clean_p)
env = NativeEnvironment()
else:
env = Environment() # noqa: S701
Expand Down

0 comments on commit 8a418b0

Please sign in to comment.