- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql_databases.py
More file actions
Latest commit
584 lines (451 loc) · 22.9 KB
/
Copy pathsql_databases.py
File metadata and controls
584 lines (451 loc) · 22.9 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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
# (c) Andrew Chen (https://github.com/achen1296)
importcsv
importjson
importos
importre
importsqlite3
fromdatetimeimportdate, datetime
fromfunctoolsimportcache
frompathlibimportPath
fromtypingimportAny, Iterable, Mapping, Sequence
sqlite3.enable_callback_tracebacks(True)
defadapt_json_serializable(d: dict|list):
returnjson.dumps(d)
sqlite3.register_adapter(dict, adapt_json_serializable)
sqlite3.register_adapter(list, adapt_json_serializable)
defconvert_json(b: bytes):
returnjson.loads(b)
sqlite3.register_converter("json", convert_json)
sqlite3.register_converter("dict", convert_json)
sqlite3.register_converter("object", convert_json)
sqlite3.register_converter("obj", convert_json)
sqlite3.register_converter("list", convert_json)
sqlite3.register_converter("array", convert_json)
defadapt_datetime(d: datetime|date):
returnd.isoformat()
sqlite3.register_adapter(datetime, adapt_datetime)
sqlite3.register_adapter(date, adapt_datetime)
defconvert_datetime(b: bytes):
returndatetime.fromisoformat(b.decode())
sqlite3.register_converter("date", convert_datetime)
sqlite3.register_converter("time", convert_datetime)
sqlite3.register_converter("datetime", convert_datetime)
defadapt_bool(b: bool):
returnint(b)
sqlite3.register_adapter(bool, adapt_bool)
defconvert_bool(b: bytes):
""" Numbers: 0 is false and anything else is true.
Text: keywords "true" or "false", case-insensitive with surrounding whitespace stripped, anything else results in `ValueError`. """
try:
returnfloat(b) !=0.
exceptValueError:
pass
b=b.lower().strip()
ifb==b"true":
returnTrue
ifb==b"false":
returnFalse
raiseValueError(b)
sqlite3.register_converter("bool", convert_bool)
sqlite3.register_converter("str", lambdab: b.decode())
sqlite3.register_converter("int", int)
sqlite3.register_converter("integer", int)
sqlite3.register_converter("float", float)
sqlite3.register_converter("real", float)
defconvert_lenient_int(b: bytes):
""" Find first instance of text convertbile to int (decimal only) and use that, discarding the rest. """
m=re.search(b"(\\+|-)?\\d+", b)
ifnotm:
raiseValueError(b)
returnint(m.group(0))
# https://docs.python.org/3/library/functions.html#float
LENIENT_FLOAT_RE=re.compile(
b"""(\\+|-)? # sign
( # value
inf(inity)?|nan| # special value keywords
(
( \\d*\\.\\d+ | \\d+\\.? ) # digits
( e # optional exponent
(\\+|-)? # exponent sign
\\d+ # exponent digits
)?
)
)
""",
re.VERBOSE|re.I
)
defconvert_lenient_float(b: bytes):
""" Find first instance of text convertbile to float and use that, discarding the rest. """
m=re.search(LENIENT_FLOAT_RE, b)
ifnotm:
raiseValueError(b)
returnfloat(m.group(0))
sqlite3.register_converter("lenient float", convert_lenient_float)
sqlite3.register_converter("lenient_float", convert_lenient_float)
sqlite3.register_converter("lenient real", convert_lenient_float)
sqlite3.register_converter("lenient_real", convert_lenient_float)
sqlite3.register_converter("lenient integer", convert_lenient_int)
sqlite3.register_converter("lenient_integer", convert_lenient_int)
sqlite3.register_converter("lenient int", convert_lenient_int)
sqlite3.register_converter("lenient_int", convert_lenient_int)
defcol_str(column: str|tuple[str, str], table: str|None=None):
ifisinstance(column, str):
c=f'"{column.lower()}"'
else:
c=f'"{column[0].lower()}" "{column[1]}"'
iftableisnotNone:
returnf'"{table}".{c}'
else:
returnc
defcol_name_type(column: str|tuple[str, str]) ->tuple[str, str]:
ifisinstance(column, str):
returncolumn.lower(), ""
else:
return (column[0].lower(), column[1])
defcols_strs(columns: Mapping[str, str] |Iterable[str|tuple[str, str]], table: str|None=None) ->list:
""" `columns`: `Iterable` of either just the column name or `tuple` of the column's name and declared type, or `Mapping` of column name and type. """
ifisinstance(columns, Mapping):
return [col_str((c, columns[c]), table=table) forcincolumns] # type:ignore
else:
return [col_str(c, table=table) forcincolumns]
defcols_names_types(columns: Mapping[str, str] |Iterable[str|tuple[str, str]]) ->Mapping[str, str]:
ifisinstance(columns, Mapping):
returncolumns# type:ignore
else:
return {
c: t
forc, tin (col_name_type(col) forcolincolumns)
}
defcols_joined_str(columns: Mapping[str, str] |Iterable[str|tuple[str, str]], table: str|None=None) ->str:
return",".join(cols_strs(columns, table=table))
classRow(sqlite3.Row):
def__repr__(self):
returnrepr(dict(**self))
def__str__(self):
returnstr(dict(**self))
def__contains__(self, value):
returnvalueinself.keys()
defget(self, key, default=None):
try:
returnself[key]
exceptKeyError:
returndefault
def_add_connection_features(con: sqlite3.Connection):
con.row_factory=Row
con.create_function("regexp", 2, lambdap, s: bool(re.search(p, sor"", re.I)), deterministic=True)
deffetch_rows(db: "Database | Table | sqlite3.Connection", sql: str, parameters=()):
ifisinstance(db, Database) orisinstance(db, Table):
con=db.con
else:
con=db
# create a new cursor to ensure it's not used for something else, interrupting the query
cur=con.cursor()
cur.execute(sql, parameters)
while (row:=cur.fetchone()) isnotNone:
yieldrow
classDatabase:
def__init__(self, db_file: str|Path, *, timeout=60., autocommit=False):
self.db_file=Path(db_file)
self.con=sqlite3.connect(self.db_file, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES, timeout=timeout, autocommit=autocommit)
_add_connection_features(self.con)
self.cur=self.con.cursor()
defclose(self):
""" This might be needed for long-running programs. """
self.con.close()
def__enter__(self):
returnself
def__exit__(self, exc_type, exc_value, traceback):
self.close()
@property
deftables(self) ->list[str]:
withself.con:
return [name[0].lower() fornameinself.cur.execute(""" select name from sqlite_schema where type = 'table' """).fetchall()]
defcreate_table(self, name: str, columns: Mapping[str, str] |Iterable[str|tuple[str, str]], primary_keys: Iterable[str]):
cs=cols_joined_str(columns)
primary_keys_str=cols_joined_str(primary_keys)
withself.con:
self.cur.execute(f""" create table \"{name}\" ( {cs}, primary key ({primary_keys_str}) ) """)
returnself.table(name)
@cache
deftable(self, name: str):
returnTable(self, name)
defcreate_sql(self) ->list[str]:
return [r[0] forrinself.cur.execute(f""" select sql from sqlite_schema where sql is not null """).fetchall()]
defsynchronize_definition_file(self, db_definition_file: Path|str):
# the database file is not expected to be reconstructed often if at all, this code is mostly to document the intent of matching the saved table definitions in git
db_definition_file=Path(db_definition_file)
tables=self.tables
ifdb_definition_file.exists():
withopen(db_definition_file) asf:
forlineinf:
m=re.match("create table \"?(.*?)\"? ?\\(", line, re.I)
ifm:
# otherwise could be e.g. a trigger or index
t=m.group(1)
iftnotintables:
self.cur.execute(line)
withopen(db_definition_file, "w") asf:
forsqlinself.create_sql():
print(sql, file=f)
classTableNotFound(Exception):
pass
classExtraData(Exception):
pass
RowType=Mapping[str, Any] |Sequence|sqlite3.Row
classTable:
# not worrying about SQL injection here
def__init__(self, db: Database, name: str):
self.db=db
self.con=db.con
self.cur=db.con.cursor()
self.name=name
self.altered_table=True
self.columns# evaluate for existence check
# _add_connection_features(self.con) # already done by db __init__
def_cache_columns_and_types(self):
ifself.altered_table:
withself.con:
cols_and_types=self.cur.execute(""" select name, type, hidden from pragma_table_xinfo(?) """, (self.name, )).fetchall()
ifnotcols_and_types:
raiseTableNotFound(self.name)
# hidden == 0 are ordinary columns
# 1 for hidden -- only these do not appear when using "select * from ..." thus they are the only ones excluded from "star columns"
# 2/3 for dynamic/stored generated columns
self._columns_and_types=tuple((c[0], c[1]) forcincols_and_typesifc[2] ==0)
self._star_columns_and_types=tuple((c[0], c[1]) forcincols_and_typesifc[2] !=1)
self._all_columns_and_types=tuple((c[0], c[1]) forcincols_and_types)
self.altered_table=False
@property
defcolumns(self) ->tuple[str, ...]:
""" Does not include hidden and generated columns """
self._cache_columns_and_types()
returntuple(c[0] forcinself._columns_and_types)
@property
defcolumn_types(self) ->tuple[str, ...]:
""" Does not include hidden and generated columns """
self._cache_columns_and_types()
returntuple(c[1] forcinself._columns_and_types)
@property
defcolumns_and_types(self) ->tuple[tuple[str, str], ...]:
""" Does not include hidden and generated columns """
self._cache_columns_and_types()
returnself._columns_and_types
@property
defstar_columns(self) ->tuple[str, ...]:
""" Only those columns which appear when using "select * from ...", which are ordinary and generated columns but not hidden columns"""
self._cache_columns_and_types()
returntuple(c[0] forcinself._star_columns_and_types)
@property
defstar_column_types(self) ->tuple[str, ...]:
""" Only those columns which appear when using "select * from ...", which are ordinary and generated columns but not hidden columns"""
self._cache_columns_and_types()
returntuple(c[1] forcinself._star_columns_and_types)
@property
defstar_columns_and_types(self) ->tuple[tuple[str, str], ...]:
""" Only those columns which appear when using "select * from ...", which are ordinary and generated columns but not hidden columns"""
self._cache_columns_and_types()
returnself._star_columns_and_types
@property
defall_columns(self) ->tuple[str, ...]:
self._cache_columns_and_types()
returntuple(c[0] forcinself._all_columns_and_types)
@property
defall_column_types(self) ->tuple[str, ...]:
self._cache_columns_and_types()
returntuple(c[1] forcinself._all_columns_and_types)
@property
defall_columns_and_types(self) ->tuple[tuple[str, str], ...]:
self._cache_columns_and_types()
returnself._all_columns_and_types
defadd_columns(self, columns: Mapping[str, str] |Iterable[str|tuple[str, str]]):
""" Adds columns, unless they are already in the table. Returns `True` if any new columns were added, `False` otherwise. """
added_any=False
existing_cols= [c.lower() forcinself.columns]
forc, tincols_names_types(columns).items():
ifc.lower() notinexisting_cols:
added_any=True
withself.con:
ift:
self.cur.execute(f""" alter table "{self.name}" add column {col_str((c, t))} """)
else:
self.cur.execute(f""" alter table "{self.name}" add column {col_str(c)} """)
ifadded_any:
self.altered_table=True
returnadded_any
@property
@cache# primary keys cannot be changed except by recreating the table
defprimary_keys(self) ->tuple[str]:
withself.con:
cols=tuple(name[0].lower() fornameinself.cur.execute(""" select name from pragma_table_info(?) where pk > 0 """, (self.name, )).fetchall())
ifnotcols:
raiseTableNotFound(self.name)
returncols
def_parse_row(self, row: RowType, *, add_missing_columns: bool, add_column_types: bool, ignore_extra_data: bool):
ifisinstance(row, Mapping) orisinstance(row, sqlite3.Row):
lower_columns: list[str] |None=None
keys=row.keys()
ifadd_missing_columns:
ifadd_column_types:
cols= {
c: type(row[c]).__name__
forcinrow.keys()
}
else:
cols= [cforcinkeys]
self.altered_table=self.add_columns(cols)
elifnotignore_extra_data:
lower_columns= [c.lower() forcinself.columns]
extra_keys= [cforcinkeysifc.lower() notinlower_columns]
ifextra_keys:
raiseExtraData(extra_keys)
iflower_columnsisNone:
lower_columns= [c.lower() forcinself.columns]
# `in row` is keys for `Mapping` but values for `sqlite3.Row`
# need to use the case of the keys as they are in `row` for retrieving them below
operation_cols= [cforcinkeysifc.lower() inlower_columns]
params= [row[c] forcinoperation_cols]
else:
lr=len(row)
lc=len(self.columns)
ifnotignore_extra_dataandlr>lc:
raiseExtraData(row[lc:])
operation_cols=self.columns[:lr]
params=list(row[:lc])
returnoperation_cols, params
definsert(self, row: RowType, *, add_missing_columns=False, add_column_types=True, ignore_extra_data=False, upsert=False):
""" If `add_missing_columns`, will add keys of a `row` that is a `Mapping` as new columns if one with the same name doesn't exist (SQLite columns are case-insensitive), and if `add_column_types`, will add declared column types using `type(v).__name__`. Else, if `ignore_extra_data`, ignores the additional keys, otherwise raise an exception.
If `row` is a `Sequence` with length at most the number of columns, always succeeds. Otherwise, either ignores or raises an exception based on `ignore_extra_data`. Cannot add new columns this way because a name is not provided.
Note: `sqlite3.Row` is treated as a `Mapping`, not a `Sequence`. It is designed such that it could be treated as either in many ways. """
operation_cols, params=self._parse_row(row, add_missing_columns=add_missing_columns, add_column_types=add_column_types, ignore_extra_data=ignore_extra_data)
self._insert(operation_cols, params, upsert=upsert)
def_insert(self, operation_cols: Iterable[str], params: list, *, upsert: bool):
sql=f""" insert into {self.name} ({cols_joined_str(operation_cols)}) values({",".join("?"*len(params))}) """
ifupsert:
sql+=f""" on conflict do update set ({cols_joined_str(operation_cols)}) = ({",".join("?"*len(params))}) """
params=params+params
withself.con:
self.cur.execute(sql, params)
defupsert(self, row: RowType, *, upsert=True, **kwargs,):
""" See `insert`. `upsert` argument is just to absorb accidentally including this argument, always passed as `True` to `insert`. """
returnself.insert(row, upsert=True, **kwargs)
defbulk_insert(self, rows: Iterable[RowType], *, add_missing_columns=False, add_column_types=True, ignore_extra_data=False, upsert=False):
""" Translating from Python data to the database is slow. This method uses a temporary table to do that part, before performing the transfer to the target table inside of SQLite which is much faster, reducing time spent with the database locked.
NOTE: It is possible specify different sets of columns for the rows. However, if one row specifies one or more columns that a second row does *not* specify, and the second row results in an upsert, then the missing values in the second row *will be updated to null instead of being ignored*. (Presumably, most of the time, all rows will have the same set of columns and this won't be an issue.) """
self.cur.execute(""" drop table if exists bulk_insert_temp_table """)
# precompute all the necessary columns
parse_results= [self._parse_row(r, add_missing_columns=add_missing_columns, add_column_types=add_column_types, ignore_extra_data=ignore_extra_data) forrinrows]
iflen(parse_results) ==0:
return0# otherwise syntax error with no columns
all_operation_columns: set[str] =set()
foroperation_cols, _inparse_results:
forcinoperation_cols:
all_operation_columns.add(c)
self.cur.execute(f""" create temp table bulk_insert_temp_table({cols_joined_str(all_operation_columns)}) """)
temp_table=Table(self.db, "bulk_insert_temp_table")
count=0
foroperation_cols, paramsinparse_results:
# upsert is not applicable with no primary key/uniqueness constraints on the temp table, and it will be applied later
temp_table._insert(operation_cols, params, upsert=False)
count+=1
operation_cols_str=cols_joined_str(all_operation_columns)
sql=f"""\
insert into {self.name}
({operation_cols_str})
select {operation_cols_str}
from {temp_table.name}
"""
ifupsert:
sql+=f"""
where true
on conflict do update
set ({operation_cols_str}) = ({",".join("excluded.\""+c+"\""forcintemp_table.columns)})
"""
withself.con:
self.cur.execute(sql)
returncount
defbulk_upsert(self, rows: Iterable[RowType], *, upsert=True, **kwargs):
returnself.bulk_insert(rows, upsert=True, **kwargs)
defimport_csv(self, csv_file: Path|str, *, add_missing_columns: bool=False, ignore_extra_data=False, upsert=False):
""" Cannot add types to columns this way, as CSV reader would of course always produce string values. Returns count of entries added. """
withopen(csv_file, newline="", encoding="utf-8-sig") asf: # encoding handles byte order mark
reader=csv.DictReader(f)
returnself.bulk_insert(reader, add_missing_columns=add_missing_columns, ignore_extra_data=ignore_extra_data, upsert=upsert, add_column_types=False)
defupdate(self, row: RowType, where: str, where_params=[], *, add_missing_columns: bool=False, add_column_types=True, ignore_extra_data=False):
""" See `insert`. """
operation_cols, params=self._parse_row(row, add_missing_columns=add_missing_columns, add_column_types=add_column_types, ignore_extra_data=ignore_extra_data)
sql=f""" update {self.name} set ({cols_joined_str(operation_cols)}) = ({",".join("?"*len(params))}) where {where} """
params+=where_params
withself.con:
self.cur.execute(sql, params)
defselect(self, columns: Iterable[str] |None=None, where: str="true", where_params=[], *, as_types: Mapping[str, str] = {}) ->list[Row]:
""" Don't forget to `sqlite3.register_converter` if you use `as_types`! Some converters have already been registered for common Python built-in types. """
ifcolumnsisNone:
columns=self.columns
else:
columns= [c.lower() forcincolumns]
as_types= {
k.lower(): v
fork, vinas_types.items()
}
col_str=",".join(f"\"{c}\" as '{c} [{as_types[c]}]'"ifcinas_typeselsef'"{c}"'forcincolumns)
withself.con:
sql=f""" select {col_str} from {self.name} where {where} """
returnself.cur.execute(sql, where_params).fetchall()
defdelete(self, where: str="true", where_params=[], ):
withself.con:
sql=f""" delete from "{self.name}" where {where} """
self.cur.execute(sql, where_params)
def__iter__(self):
returniter(self.select())
DATABASE_IN_MEMORY=":memory:"
if__name__=="__main__":
test_db=Database(DATABASE_IN_MEMORY)
t=test_db.create_table("t", [("a", "int")], ["a"])
assertt.columns== ("a",), t.columns
assertt.primary_keys== ("a",), t.primary_keys
try:
t.insert({"a": 1, "b": 2})
exceptExtraData:
pass
else:
assertFalse
t.insert({"a": 1, "b": 2}, ignore_extra_data=True)
try:
t.insert([3, 4])
exceptExtraData:
pass
else:
assertFalse
t.insert([3, 4], ignore_extra_data=True)
rows=list(dict(**r) forrint)
assertrows== [{"a": 1}, {"a": 3}], rows
t.insert({"a": 5, "b": 6}, add_missing_columns=True, add_column_types=False)
assertt.columns== ("a", "b"), t.columns
rows=list(dict(**r) forrint)
assertrows== [{"a": 1, "b": None}, {"a": 3, "b": None}, {"a": 5, "b": 6}], rows
t.upsert({"a": 1, "b": {"hello": "world"}})
rows=list(dict(**r) forrint)
assertrows== [{"a": 1, "b": '{"hello": "world"}'}, {"a": 3, "b": None}, {"a": 5, "b": 6}], rows
t.update((7, ["asdf"]), "a=1")
rows=list(dict(**r) forrint)
assertrows== [{"a": 7, "b": '["asdf"]'}, {"a": 3, "b": None}, {"a": 5, "b": 6}], rows
# new column should get list type
t.insert({"a": 8, "c": []}, add_missing_columns=True)
selected= [dict(**r) forrint.select(where="a=8")]
assertselected== [{"a": 8, "b": None, "c": []}], selected
selected= [dict(**r) forrint.select(where="a=8", as_types={"c": "str"})]
assertselected== [{"a": 8, "b": None, "c": "[]"}], selected
withopen("test.csv", "w", newline="") asf:
w=csv.writer(f)
w.writerow(["a", "c", "d"])
w.writerow([9, '["hello", "world"]', "hello"])
w.writerow([7, '["bye", "world"]'])
t.import_csv("test.csv", upsert=True, add_missing_columns=True)
os.remove("test.csv")
selected= [dict(**r) forrint.select(where="a=9", as_types={"c": "list"})]
assertselected== [{"a": 9, "b": None, "c": ["hello", "world"], "d": "hello"}], selected
selected= [dict(**r) forrint.select(where="a=7", as_types={"c": "list"})]
# column b should be retained through upsert
assertselected== [{"a": 7, "b": '["asdf"]', "c": ["bye", "world"], "d": None}], selected
test_db.con.close()
print("tests passed")