1 import sqlite3 |
|
2 |
|
3 try : |
|
4 conn = sqlite3.connect("db/degal.db") |
|
5 |
|
6 except sqlite3.OperationalError : |
|
7 conn = None |
|
8 |
|
9 def execute (expr, *args) : |
|
10 c = conn.cursor() |
|
11 c.execute(expr, args) |
|
12 |
|
13 return c |
|
14 |
|
15 def execute_many (expr, iter) : |
|
16 c = conn.cursor() |
|
17 c.executemany(expr, iter) |
|
18 |
|
19 return c |
|
20 |
|
21 def insert (expr, *args) : |
|
22 return execute_commit(expr, *args).lastrowid |
|
23 |
|
24 def insert_many (cb, expr, iter) : |
|
25 """ |
|
26 Perform an executemany with the given iterator (which must yield (cb_val, args) tuples), calling the given callback with the args (cb_val, row_id) |
|
27 """ |
|
28 |
|
29 c = conn.cursor() |
|
30 |
|
31 c.executemany(expr, _lastrowid_adapter(c, iter, cb)) |
|
32 |
|
33 return commit(c) |
|
34 |
|
35 def _lastrowid_adapter (c, iter, cb) : |
|
36 for val, args in iter : |
|
37 yield args |
|
38 |
|
39 cb(val, c.lastrowid) |
|
40 |
|
41 def commit (cursor) : |
|
42 try : |
|
43 cursor.execute("COMMIT") |
|
44 except sqlite3.OperationalError : |
|
45 pass # ffs. INSERT just doesn't do anything otherwise |
|
46 |
|
47 return cursor |
|
48 |
|
49 def execute_commit (expr, *args) : |
|
50 return commit(execute(expr, *args)) |
|
51 |
|
52 def execute_commit_many (expr, iter) : |
|
53 return commit(execute_many(expr, iter)) |
|
54 |
|
55 select = execute |
|
56 |
|
57 delete = execute_commit |
|
58 |
|
59 delete_many = execute_commit_many |
|
60 |
|
61 if conn : |
|
62 cursor = conn.cursor |
|
63 |
|
64 |
|