Skip to content
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

Var substitution #51

Merged
merged 2 commits into from
Dec 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;"