1
+ """A simple SQLite CLI for the sqlite3 module.
2
+
3
+ Apart from using 'argparse' for the command-line interface,
4
+ this module implements the REPL as a thin wrapper around
5
+ the InteractiveConsole class from the 'code' stdlib module.
6
+ """
1
7
import sqlite3
2
8
import sys
3
9
7
13
8
14
9
15
def execute (c , sql , suppress_errors = True ):
16
+ """Helper that wraps execution of SQL code.
17
+
18
+ This is used both by the REPL and by direct execution from the CLI.
19
+
20
+ 'c' may be a cursor or a connection.
21
+ 'sql' is the SQL string to execute.
22
+ """
23
+
10
24
try :
11
25
for row in c .execute (sql ):
12
26
print (row )
@@ -21,13 +35,19 @@ def execute(c, sql, suppress_errors=True):
21
35
22
36
23
37
class SqliteInteractiveConsole (InteractiveConsole ):
38
+ """A simple SQLite REPL."""
24
39
25
40
def __init__ (self , connection ):
26
41
super ().__init__ ()
27
42
self ._con = connection
28
43
self ._cur = connection .cursor ()
29
44
30
45
def runsource (self , source , filename = "<input>" , symbol = "single" ):
46
+ """Override runsource, the core of the InteractiveConsole REPL.
47
+
48
+ Return True if more input is needed; buffering is done automatically.
49
+ Return False is input is a complete statement ready for execution.
50
+ """
31
51
match source :
32
52
case ".version" :
33
53
print (f"{ sqlite3 .sqlite_version } " )
@@ -73,6 +93,7 @@ def main():
73
93
else :
74
94
db_name = repr (args .filename )
75
95
96
+ # Prepare REPL banner and prompts.
76
97
banner = dedent (f"""
77
98
sqlite3 shell, running on SQLite version { sqlite3 .sqlite_version }
78
99
Connected to { db_name }
@@ -86,8 +107,10 @@ def main():
86
107
con = sqlite3 .connect (args .filename , isolation_level = None )
87
108
try :
88
109
if args .sql :
110
+ # SQL statement provided on the command-line; execute it directly.
89
111
execute (con , args .sql , suppress_errors = False )
90
112
else :
113
+ # No SQL provided; start the REPL.
91
114
console = SqliteInteractiveConsole (con )
92
115
console .interact (banner , exitmsg = "" )
93
116
finally :
0 commit comments