-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathdb_table.py
More file actions
594 lines (467 loc) · 16.5 KB
/
db_table.py
File metadata and controls
594 lines (467 loc) · 16.5 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
585
586
587
588
589
590
591
592
593
594
"""Contains methods that generate a database table structure
similar to what is presented in my
[tutorial](https://github.com/spacecowboy/AndroidTutorialContentProvider)
"""
# I make heavy use of string format
_C_T = \
"""CREATE TABLE {table_name}
({columns}
{constraints})"""
_F_K = "FOREIGN KEY ({column_name}) REFERENCES \
{foreign_table}({foreign_column}) {cascade_case}"
_C_TR = \
"""CREATE {0._temp} TRIGGER {0._ifnotexists} {0.name}
{0._when} {0._action}
BEGIN
{body}
END"""
class Column(object):
"""Used to build a column definition. Example usage:
>>> Column('age').real.not_null.default(12)
age REAL NOT NULL DEFAULT 12
>>> Column('_id').integer.primary_key
_id INTEGER PRIMARY KEY
"""
def __init__(self, name):
self.name = name
self.type = "TEXT"
self.constraint = ""
@property
def upper_name(self):
'''return uppercase of name'''
return self.name.upper()
def __repr__(self):
return " ".join([self.name, self.type, self.constraint]).strip()
def set_type(self, typestring):
'''Set the type of this column'''
self.type = typestring.strip()
return self
@property
def text(self):
return self.set_type("TEXT")
@property
def integer(self):
return self.set_type("INTEGER")
@property
def real(self):
return self.set_type("REAL")
@property
def timestamp(self):
return self.set_type("TIMESTAMP")
def set_constraint(self, *constraints):
'''Set the constraint on the column'''
self.constraint = " ".join(constraints).strip()
return self
@property
def not_null(self):
return self.set_constraint(self.constraint, "NOT NULL")
@property
def primary_key(self):
return self.set_constraint(self.constraint, "PRIMARY KEY")
def default(self, val):
return self.set_constraint(self.constraint,
"DEFAULT {}".format(val))
@property
def default_current_timestamp(self):
'''Use with timestamp type to default to now.
Stored as YYYY-MM-DD HH:MM:SS'''
return self.set_constraint(self.constraint,
"DEFAULT CURRENT_TIMESTAMP")
class Unique(object):
"""Unique constraint on a table
Example:
>>> Unique('name')
UNIQUE (name)
>>> Unique('artist', 'album')
UNIQUE (artist, album)
>>> Unique('hash').on_conflict_replace
UNIQUE (hash) ON CONFLICT REPLACE
>>> Unique('hash').on_conflict_rollback
UNIQUE (hash) ON CONFLICT ROLLBACK
"""
def __init__(self, *colnames):
self.colnames = colnames
self.conflict_clause = ""
def __repr__(self):
return "UNIQUE ({}) {}".format(", ".join(self.colnames),
self.conflict_clause)\
.strip()
def _conflict(self, case):
self.conflict_clause = "ON CONFLICT {}".format(case)
return self
@property
def on_conflict_replace(self):
return self._conflict("REPLACE")
@property
def on_conflict_rollback(self):
return self._conflict("ROLLBACK")
@property
def on_conflict_abort(self):
return self._conflict("ABORT")
@property
def on_conflict_fail(self):
return self._conflict("FAIL")
@property
def on_conflict_ignore(self):
return self._conflict("IGNORE")
class ForeignKey(object):
"""Foreign key constraint
Example:
>>> ForeignKey('listid').references('list', '_id').on_delete_cascade
FOREIGN KEY (listid) REFERENCES list(_id) ON DELETE CASCADE
"""
def __init__(self, column_name):
self.column_name = column_name
self.foreign_table = ""
self.foreign_col = ""
self.cascade_case = ""
def __repr__(self):
return _F_K.format(column_name=self.column_name,
foreign_table=self.foreign_table,
foreign_column=self.foreign_col,
cascade_case=self.cascade_case)
def references(self, table_name, col_name="_id"):
self.foreign_table = table_name
self.foreign_col = col_name
return self
@property
def on_delete_cascade(self):
self.cascade_case = "ON DELETE CASCADE"
return self
@property
def on_delete_set_null(self):
self.cascade_case = "ON DELETE SET NULL"
return self
@property
def on_delete_set_default(self):
self.cascade_case = "ON DELETE SET DEFAULT"
return self
class Check(object):
"""Check constraint on a table
Example:
>>> Check("name = 'bob'")
CHECK (name = 'bob')
>>> Check('name', ' > 0')
CHECK (name > 0)
>>> Check('name1', '<=', 'name2')
CHECK (name1 <= name2)
>>> Check(' bob ', ' < ', 36)
CHECK (bob < 36)
"""
def __init__(self, *args):
if len(args) < 1:
raise ValueError("Must specify at least one argument!")
self.args = args
def __repr__(self):
return "CHECK ({})".format(" "\
.join([str(x).strip() for x in self.args]))
class Table(object):
"""An SQL table which consists of columns
and constraints. It is prepopualted with an _id column
which is the primary key.
Example usage:
>>> Table('People')
CREATE TABLE People
(_id INTEGER PRIMARY KEY
<BLANKLINE>
)
>>> Table('People').add_cols(Column('name').text.not_null.default("''"), \
Column('age').integer.not_null.default(18))
CREATE TABLE People
(_id INTEGER PRIMARY KEY,
name TEXT NOT NULL DEFAULT '',
age INTEGER NOT NULL DEFAULT 18
<BLANKLINE>
)
>>> Table('Albums').add_cols(Column('albumname').text.not_null.default("''"), \
Column('artistname').text.not_null)\
.add_constraints(ForeignKey('artistname').references('artist', 'name')\
.on_delete_cascade,\
Unique('albumname').on_conflict_replace)
CREATE TABLE Albums
(_id INTEGER PRIMARY KEY,
albumname TEXT NOT NULL DEFAULT '',
artistname TEXT NOT NULL,
<BLANKLINE>
FOREIGN KEY (artistname) REFERENCES artist(name) ON DELETE CASCADE,
UNIQUE (albumname) ON CONFLICT REPLACE)
"""
def __init__(self, name):
self.name = name
self._columns = [Column('_id').integer.primary_key]
self._constraints = []
self.fts3_cols = None
def __repr__(self):
constraints = ",\n ".join(map(str, self._constraints))
columns = ",\n ".join(map(str, self._columns))
if len(constraints) > 0:
# Add a comma at the end
columns += ","
return _C_T.format(table_name = self.name,
columns = columns,
constraints = constraints)
def add_cols(self, *columns):
self._columns.extend(columns)
return self
def add_constraints(self, *constraints):
self._constraints.extend(constraints)
return self
def list_column_names(self, sep=",", withid=False, prefix="",
exclude=None):
"""Use to get a single string of column names. By default, it
will exclude the _id column. Give an empty list to include
_id. If you want to exclude as many columns as you like.
Examples:
>>> living = Table('LivePerson').add_cols(\
Column('firstname').text.not_null.default("''"),\
Column('lastname').text.not_null.default("''"),\
Column('bio').text.not_null.default("''"))
>>> living.list_column_names()
'firstname,lastname,bio'
>>> living.list_column_names(exclude=[])
'_id,firstname,lastname,bio'
>>> living.list_column_names(exclude=['_id'])
'firstname,lastname,bio'
>>> living.list_column_names(exclude=['lastname', 'bio'])
'_id,firstname'
>>> living.list_column_names(withid=True, prefix='old.')
'old._id,old.firstname,old.lastname,old.bio'
"""
cols = self._columns
if exclude is None:
exclude = ["_id"]
if not withid:
cols = []
for c in self._columns:
if c.name not in exclude:
cols.append(c)
return sep.join([prefix + c.name for c in cols])
class Trigger(object):
"""Create an sql trigger
Examples:
>>> Trigger('tr_archive').temp.if_not_exists.before.delete_on('notes')\
.do_sql('INSERT INTO archive (noteid,notetext) VALUES (old._id,old.text)')
CREATE TEMP TRIGGER IF NOT EXISTS tr_archive
BEFORE DELETE ON notes
BEGIN
INSERT INTO archive (noteid,notetext) VALUES (old._id,old.text);
END
"""
def __init__(self, name):
self.name = name
self._temp = ""
self._ifnotexists = ""
self._action = None
self._when = None
self._body = []
@property
def java_string(self):
sql = str(self)
return '"\n+"'.join(sql.split('\n'))
def __repr__(self):
if self._when is None:
raise ValueError('You must specify a trigger time, like:\
Trigger("bob").after, .before or .instead_of')
if self._action is None:
raise ValueError('You must specify a trigger action, like:\
Trigger("bob").update_on("sometable)')
if len(self._body) < 1:
raise ValueError('You must specify a trigger body, like:\
Trigger("bob").do("SQL")')
return _C_TR.format(self,
body="\n".join(self._body))
@property
def temp(self):
self._temp = "TEMP"
return self
@property
def is_temp(self):
return len(self._temp) > 0
@property
def if_not_exists(self):
self._ifnotexists = "IF NOT EXISTS"
return self
@property
def before(self):
self._when = "BEFORE"
return self
@property
def after(self):
self._when = "AFTER"
return self
@property
def instead_of(self):
self._when = "INSTEAD OF"
return self
def delete_on(self, tablename):
self._action = "DELETE ON {}".format(tablename)
return self
def insert_on(self, tablename):
self._action = "INSERT ON {}".format(tablename)
return self
def update_on(self, tablename, *cols):
of_cols = ""
if cols is not None and len(cols) > 0:
of_cols = "OF {}".format(",".join(cols))
self._action = "UPDATE {} ON {}".format(of_cols,
tablename)
return self
def do_sql(self, sqlstatement):
end = ""
if not sqlstatement.strip().endswith(";"):
end = ";"
self._body.append(sqlstatement.strip() + end)
return self
class TableFTS3(object):
'''Create a virtual table using fts3, and triggers to keep it up
to date.
Example:
>>> TableFTS3("tasks").use_cols("title", "note")
CREATE VIRTUAL TABLE tasks_fts3 USING FTS3 (_id, title, note);
<BLANKLINE>
CREATE TRIGGER tr_tasks_fts3_ins
AFTER INSERT ON tasks
BEGIN
INSERT INTO tasks_fts3(_id, title, note) VALUES (new._id, new.title, new.note);
END
<BLANKLINE>
CREATE TRIGGER tr_tasks_fts3_del
AFTER DELETE ON tasks
BEGIN
DELETE FROM tasks_fts3 WHERE _id IS old._id;
END
<BLANKLINE>
CREATE TRIGGER tr_tasks_fts3_up
AFTER UPDATE OF title,note ON tasks
BEGIN
UPDATE tasks_fts3 SET title = new.title, note = new.note WHERE _id IS new._id;
END
'''
def __init__(self, tablename):
'''Argument is the table which fts3 should search in'''
self.tablename = tablename
self.name = tablename + "_fts3"
self.cols = []
def use_cols(self, *cols):
self.cols.extend(cols)
return self
def _cols(self, prefix="", suffix=""):
cols = self.cols
if '_id' not in cols:
cols = ['_id'] + cols
cols = ["{}{}{}".format(prefix, col, suffix)\
for col in cols]
return ", ".join(cols)
@property
def table_stmt(self):
if len(self.cols) < 1:
raise ValueError('Need some columns!')
stmt = "CREATE VIRTUAL TABLE {} USING FTS3 ({});"
return stmt.format(self.name,
self._cols())
@property
def trigger_stmts(self):
return [str(t) for t in self.triggers]
@property
def triggers(self):
if len(self.cols) < 1:
raise ValueError('Need some columns!')
triggers = []
# Insert trigger
tr_ins = Trigger("tr_" + self.name + "_ins").after.insert_on(self.tablename)
tr_ins.do_sql("INSERT INTO {}\
({}) VALUES ({})".format(self.name,
self._cols(),
self._cols(prefix="new.")))
triggers.append(tr_ins)
# Delete trigger
tr_del = Trigger("tr_" + self.name + "_del").after.delete_on(self.tablename)
tr_del.do_sql("DELETE FROM {} WHERE _id IS old._id".format(self.name))
triggers.append(tr_del)
# Update trigger
tr_up = Trigger("tr_" +
self.name +
"_up").after.update_on(self.tablename,
*self.cols)
s = "UPDATE {} SET {} WHERE _id IS new._id"
setters = ["{0} = new.{0}".format(col) for col in self.cols]
tr_up.do_sql(s.format(self.name,
", ".join(setters)))
triggers.append(tr_up)
return triggers
def __repr__(self):
return "\n\n".join([self.table_stmt] + self.trigger_stmts)
class View(object):
"""
Example usage:
>>> View('music_view').temp.if_not_exists.as_sql('SELECT * FROM artists, \
songs WHERE artists.name = songs.artistname')
CREATE TEMP VIEW IF NOT EXISTS music_view AS SELECT * FROM artists, \
songs WHERE artists.name = songs.artistname;
"""
def __init__(self, name):
self._temp = ""
self._if_not_exists = ""
self._stmt = None
self.name = str(name).strip()
if self.name is None or len(self.name) < 1:
raise ValueError('Must give a valid name!')
@property
def temp(self):
self._temp = "TEMP"
return self
@property
def is_temp(self):
return len(self._temp) > 0
@property
def if_not_exists(self):
self._if_not_exists = "IF NOT EXISTS"
return self
def as_sql(self, select_stmt):
self._stmt = str(select_stmt).strip()
if not self._stmt.endswith(";"):
self._stmt += ";"
return self
@property
def java_string(self):
sql = str(self)
return '"\n+"'.join(sql.split('\n'))
def __repr__(self):
return "CREATE {} VIEW {} {} AS {}".format(self._temp,
self._if_not_exists,
self.name,
self._stmt)
def select_join(tab_cols, on_cols):
"""
Example usage:
>>> t1 = ('Artist', 'name age'.split(' '))
>>> t2 = ('Album', 'name year'.split(' '))
>>> t3 = ('Song', 'name duration'.split(' '))
>>> on1 = (('Artist', 'name'), ('Album', 'artist'))
>>> on2 = (('Artist', 'name'), ('Song', 'artist'))
>>> select_join([t1, t2, t3], [on1, on2])
'SELECT t1._id AS _id, t1.name AS Artist_name, t1.age AS Artist_age, t2.name AS Album_name, t2.year AS Album_year, t3.name AS Song_name, t3.duration AS Song_duration FROM Album AS t2, Song AS t3, Artist AS t1 WHERE t1.name = t2.artist AND t1.name = t3.artist;'
"""
alias = {}
# Always include the idea of the first table
fields = ["t1._id AS _id"]
i = 0
for table, cols in tab_cols:
i += 1
tx = "t{}".format(i)
alias[table] = tx
fields.extend(["{0}.{1} \
AS {2}_{1}".format(tx, col, table) for col in cols])
on = []
for (t1, t1col), (t2, t2col) in on_cols:
on.append("{}.{} = {}.{}".format(alias[t1],
t1col,
alias[t2],
t2col))
tables = []
for k, v in alias.items():
tables.append("{} AS {}".format(k, v))
return 'SELECT {} \
FROM {} WHERE {};'.format(', '.join(fields),
', '.join(tables),
" AND ".join(on))