Skip to content

Commit

Permalink
Fix - Issue better detect the user uses sqlalchemy variable expansion (
Browse files Browse the repository at this point in the history
…catherinedevlin#215)

* Add: fail test case

* Add: better check for variable usage
  • Loading branch information
tonykploomber authored Mar 7, 2023
1 parent a25b3db commit 4d9ec3b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
4 changes: 2 additions & 2 deletions src/sql/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,8 @@ def _var_expand(self, sql, user_ns, magic):
sql = Template(sql).render(user_ns)
parsed_sql = magic.shell.var_expand(sql, depth=2)

has_SQLAlchemy_var_expand = ":" in sql
# parsed_sql != sql: detect if using IPython fashion - {a} or $a
has_SQLAlchemy_var_expand = any((':' + ns_var_key in sql
for ns_var_key in user_ns.keys()))
# has_SQLAlchemy_var_expand: detect if using Sqlalchemy fashion - :a

msg = (
Expand Down
14 changes: 12 additions & 2 deletions src/tests/test_command.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from pathlib import Path
import warnings

import pytest
from sqlalchemy import create_engine
Expand Down Expand Up @@ -209,6 +210,17 @@ def test_variable_substitution_legacy_warning_message_colon(ip, sql_magic, capsy
""",
)

with warnings.catch_warnings():
warnings.simplefilter("error")
ip.user_global_ns["limit_number"] = 1
ip.run_cell_magic(
"sql",
"",
"""
SELECT * FROM author WHERE last_name = 'Something with : inside'
""",
)


def test_variable_substitution_legacy_dollar_prefix_cell_magic(ip, sql_magic):
ip.user_global_ns["username"] = "some-user"
Expand Down Expand Up @@ -246,7 +258,6 @@ def test_variable_substitution_double_curly_cell_magic(ip, sql_magic):
cell="GRANT CONNECT ON DATABASE postgres TO {{username}};",
)

print("cmd.parsed['sql']", cmd.parsed["sql"])
assert cmd.parsed["sql"] == "\nGRANT CONNECT ON DATABASE postgres TO some-user;"


Expand All @@ -260,5 +271,4 @@ def test_variable_substitution_double_curly_line_magic(ip, sql_magic):
cell="",
)

# print ("cmd.parsed['sql']", cmd.parsed["sql"])
assert cmd.parsed["sql"] == "SELECT first_name FROM author LIMIT 5;"

0 comments on commit 4d9ec3b

Please sign in to comment.