Skip to content

Commit

Permalink
Var substitution (#51)
Browse files Browse the repository at this point in the history
* moves var expand line to command.py

* adds test
  • Loading branch information
edublancas authored Dec 30, 2022
1 parent 0b1aea3 commit 0d7ecc8
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 4 deletions.
4 changes: 4 additions & 0 deletions src/sql/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ class SQLCommand:
"""

def __init__(self, magic, user_ns, line, cell) -> None:
# Parse variables (words wrapped in {}) for %%sql magic
# (for %sql this is done automatically)
cell = magic.shell.var_expand(cell)

self.args = parse.magic_args(magic.execute, line)

if (
Expand Down
4 changes: 0 additions & 4 deletions src/sql/magic.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,10 +232,6 @@ def execute(self, line="", cell="", local_ns={}):
user_ns = self.shell.user_ns.copy()
user_ns.update(local_ns)

# Parse variables (words wrapped in {}) for %%sql magic
# (for %sql this is done automatically)
cell = self.shell.var_expand(cell)

command = SQLCommand(self, user_ns, line, cell)
# args.line: contains the line after the magic with all options removed
args = command.args
Expand Down
13 changes: 13 additions & 0 deletions src/tests/test_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,16 @@ def test_parse_sql_when_passing_engine(ip, sql_magic, tmp_empty, line):
assert cmd.connection is engine
assert cmd.sql == sql_expected
assert cmd.sql_original == sql_expected


def test_variable_substitution_cell_magic(ip, sql_magic):
ip.user_global_ns["username"] = "some-user"

cmd = SQLCommand(
sql_magic,
ip.user_ns,
line="",
cell="GRANT CONNECT ON DATABASE postgres TO $username;",
)

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

0 comments on commit 0d7ecc8

Please sign in to comment.