Skip to content

Commit 1b5fd9d

Browse files
committed
Fix %%sql cells in %run_shared magic
1 parent 960cefe commit 1b5fd9d

File tree

1 file changed

+73
-1
lines changed

1 file changed

+73
-1
lines changed

singlestoredb/magics/run_shared.py

Lines changed: 73 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
11
import os
22
import tempfile
3+
from pathlib import Path
34
from typing import Any
5+
from warnings import warn
46

57
from IPython.core.interactiveshell import InteractiveShell
68
from IPython.core.magic import line_magic
79
from IPython.core.magic import Magics
810
from IPython.core.magic import magics_class
911
from IPython.core.magic import needs_local_scope
1012
from IPython.core.magic import no_var_expand
13+
from IPython.utils.contexts import preserve_keys
14+
from IPython.utils.syspathcontext import prepended_to_syspath
1115
from jinja2 import Template
1216

1317

@@ -50,4 +54,72 @@ def run_shared(self, line: str, local_ns: Any = None) -> Any:
5054
# Execute the SQL command
5155
self.shell.run_line_magic('sql', sql_command)
5256
# Run the downloaded file
53-
self.shell.run_line_magic('run', f'"{temp_file_path}"')
57+
with preserve_keys(self.shell.user_ns, '__file__'):
58+
self.shell.user_ns['__file__'] = temp_file_path
59+
self.shell.safe_execfile_ipy(temp_file_path, raise_exceptions=True)
60+
61+
def safe_execfile_ipy(
62+
self,
63+
fname: str,
64+
shell_futures: bool = False,
65+
raise_exceptions: bool = False,
66+
) -> None:
67+
"""Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
68+
69+
Parameters
70+
----------
71+
fname : str
72+
The name of the file to execute. The filename must have a
73+
.ipy or .ipynb extension.
74+
shell_futures : bool (False)
75+
If True, the code will share future statements with the interactive
76+
shell. It will both be affected by previous __future__ imports, and
77+
any __future__ imports in the code will affect the shell. If False,
78+
__future__ imports are not shared in either direction.
79+
raise_exceptions : bool (False)
80+
If True raise exceptions everywhere. Meant for testing.
81+
"""
82+
fpath = Path(fname).expanduser().resolve()
83+
84+
# Make sure we can open the file
85+
try:
86+
with fpath.open('rb'):
87+
pass
88+
except Exception:
89+
warn('Could not open file <%s> for safe execution.' % fpath)
90+
return
91+
92+
# Find things also in current directory. This is needed to mimic the
93+
# behavior of running a script from the system command line, where
94+
# Python inserts the script's directory into sys.path
95+
dname = str(fpath.parent)
96+
97+
def get_cells() -> Any:
98+
"""generator for sequence of code blocks to run"""
99+
if fpath.suffix == '.ipynb':
100+
from nbformat import read
101+
nb = read(fpath, as_version=4)
102+
if not nb.cells:
103+
return
104+
for cell in nb.cells:
105+
if cell.cell_type == 'code':
106+
if getattr(cell, 'metadata', {}).get('language', '') == 'sql':
107+
yield f'%%sql\n{cell.source}'
108+
else:
109+
yield cell.source
110+
else:
111+
yield fpath.read_text(encoding='utf-8')
112+
113+
with prepended_to_syspath(dname):
114+
try:
115+
for cell in get_cells():
116+
result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
117+
if raise_exceptions:
118+
result.raise_error()
119+
elif not result.success:
120+
break
121+
except Exception:
122+
if raise_exceptions:
123+
raise
124+
self.showtraceback()
125+
warn('Unknown failure executing file: <%s>' % fpath)

0 commit comments

Comments
 (0)