-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsqlitemagic.py
More file actions
156 lines (129 loc) · 4.34 KB
/
Copy pathsqlitemagic.py
File metadata and controls
156 lines (129 loc) · 4.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
"""
SQLite magics for IPython
=========================
License
-------
ipython-sqlitemagic is licensed under the term of the Simplified
BSD License (BSD 2-clause license), as follows:
Copyright (c) 2012 Takafumi Arakaki
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import itertools
import sqlite3
from IPython.core.magic import Magics, magics_class, line_magic, cell_magic
from IPython.core.magic_arguments import (argument, magic_arguments,
parse_argstring)
import texttable
common_show_arguments = argument(
'--limit', '-l', type=int, default=10,
help="""
Maximum rows to print as table. -1 means no limit.
(default: %(default)s)
""")
@magics_class
class SQLiteMagic(Magics):
@line_magic('sqlite_create')
def create(self, line):
"""
Create in-memory SQLite DB with SQLite magic-friendly setup.
"""
conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row
return conn
@magic_arguments()
@argument(
'conn',
help="`sqlite3.Connection` object."
)
@argument(
'--commit', '-c', action='store_true',
help="Run ``CONN.commit()``."
)
@argument(
'--script', '-s', action='store_true',
help="Run multiple statements. Result table will not be shown."
)
@common_show_arguments
@cell_magic('sqlite_execute')
def execute(self, line, cell):
"""
Run SQL
Example::
%%sqlite conn
SELECT * FROM table
"""
args = parse_argstring(self.execute, line)
conn = self.shell.ev(args.conn)
cursor = conn.cursor()
if args.script:
cursor.executescript(cell)
else:
self.show_rows(cursor.execute(cell), args.limit)
if args.commit:
conn.commit()
@magic_arguments()
@argument(
'cursor'
)
@common_show_arguments
@line_magic('sqlite_show')
def show(self, line):
"""
Show rows as table.
"""
args = parse_argstring(self.show, line)
cursor = self.shell.ev(args.cursor)
self.show_rows(cursor, args.limit)
@staticmethod
def show_rows(cursor, limit):
"""
Show rows generated by `cursor`.
:type cursor: sqlite3.Cursor
"""
tt = texttable.Texttable()
tt.set_deco(texttable.Texttable.HEADER)
rows = itertools.islice(cursor, limit) if limit >= 0 else cursor
try:
row = next(rows)
except StopIteration:
return
try:
tt.header(row.keys())
except AttributeError:
pass
tt.add_row(row)
tt.add_rows(rows, header=False)
print(tt.draw())
if limit >= 0:
try:
next(cursor)
print("More than {0} rows found. Use -l or --limit to "
"change limit.".format(limit))
except:
pass
def load_ipython_extension(ip):
"""Load the extension in IPython."""
global _loaded
if not _loaded:
ip.register_magics(SQLiteMagic)
_loaded = True
_loaded = False