Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
singlestore-labs
GitHub Repository: singlestore-labs/singlestoredb-python
Path: blob/main/singlestoredb/magics/run_shared.py
469 views
1
import os
2
import tempfile
3
from pathlib import Path
4
from typing import Any
5
from warnings import warn
6
7
from IPython.core.interactiveshell import InteractiveShell
8
from IPython.core.magic import line_magic
9
from IPython.core.magic import Magics
10
from IPython.core.magic import magics_class
11
from IPython.core.magic import needs_local_scope
12
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
15
from jinja2 import Template
16
17
18
@magics_class
19
class RunSharedMagic(Magics):
20
def __init__(self, shell: InteractiveShell):
21
Magics.__init__(self, shell=shell)
22
23
@no_var_expand
24
@needs_local_scope
25
@line_magic('run_shared')
26
def run_shared(self, line: str, local_ns: Any = None) -> Any:
27
"""
28
Downloads a shared file using the %sql magic and then runs it using %run.
29
30
Examples::
31
32
# Line usage
33
34
%run_shared shared_file.ipynb
35
36
%run_shared {{ sample_notebook_name }}
37
38
"""
39
40
template = Template(line.strip())
41
shared_file = template.render(local_ns)
42
if not shared_file:
43
raise ValueError('No shared file specified.')
44
if (shared_file.startswith("'") and shared_file.endswith("'")) or \
45
(shared_file.startswith('"') and shared_file.endswith('"')):
46
shared_file = shared_file[1:-1]
47
if not shared_file:
48
raise ValueError('No personal file specified.')
49
50
with tempfile.TemporaryDirectory() as temp_dir:
51
temp_file_path = os.path.join(temp_dir, shared_file)
52
sql_command = f"DOWNLOAD SHARED FILE '{shared_file}' TO '{temp_file_path}'"
53
54
# Execute the SQL command
55
self.shell.run_line_magic('sql', sql_command)
56
# Run the downloaded file
57
with preserve_keys(self.shell.user_ns, '__file__'):
58
self.shell.user_ns['__file__'] = temp_file_path
59
self.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 not cell.source.strip():
107
continue
108
if getattr(cell, 'metadata', {}).get('language', '') == 'sql':
109
output_redirect = getattr(
110
cell, 'metadata', {},
111
).get('output_variable', '') or ''
112
if output_redirect:
113
output_redirect = f' {output_redirect} <<'
114
yield f'%%sql{output_redirect}\n{cell.source}'
115
else:
116
yield cell.source
117
else:
118
yield fpath.read_text(encoding='utf-8')
119
120
with prepended_to_syspath(dname):
121
try:
122
for cell in get_cells():
123
result = self.shell.run_cell(
124
cell, silent=True, shell_futures=shell_futures,
125
)
126
if raise_exceptions:
127
result.raise_error()
128
elif not result.success:
129
break
130
except Exception:
131
if raise_exceptions:
132
raise
133
self.shell.showtraceback()
134
warn('Unknown failure executing file: <%s>' % fpath)
135
136