-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.py
782 lines (581 loc) · 20.4 KB
/
db.py
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
"""
Defines a DB class that connects to a specified mysql instance and manages the atplanta database.
Example usage:
db = DB(host='localhost')
# Add an entry.
db += db.employee(name = "John")
# Get an entry.
employees_named_john = db.employee(name = "John")
employee_named_john = db.employee(name = "John")[0]
# Delete all entries matching a query.
db -= db.employee(name = "John")
# Same as above.
results = db.employee(name = "John")
db -= results
# Delete particular entry.
db -= db.employee(name = "John")[0]
# Same as above.
employee = db.employee(name = "John")[0]
db -= employee
# Change employee name.
db.employee(name = "John")[0].name = "Jack"
# Set employee name to NULL.
del db.employee(name = "John")[0].name
Making a connection will delete tables not specified in the schema, and insert any missing tables.
Currently, table format is not verified on connection, only that they exist.
Debugging information:
debug statements are categorized, specify the category to debug as follows:
DB(debug = {"tables", "rows"})
The current debug categories are supported:
tables - Print table related housekeeping.
execute - Print all executed SQL statements.
all - Display all of the above.
Password hashing is provided by this library, and is implemented as a set hook on
password fields.
Thus, password matching can be verified as follows.
import db
dbi = DB()
john = dbi.user(name = "John")[0]
if dbi.hash_pass(password) == john.password:
... do stuff on matching password ...
Setting a password requires no call to hash_pass, and in fact doing so will cause issues:
dbi = DB()
dbi.user(name = "John")[0].password = "Foo bar"
"""
import pymysql.cursors
import hashlib
import base64
def _map(fn, xs):
for x in xs:
yield fn(x)
class _SQL():
def _provide_debug(self, categories):
self.__debug_categories = categories
return self
def _debug(self, category, *message):
"""Print the given debug message for the given category."""
# Only print this message if we are asking for this debug category.
if 'all' in self.__debug_categories or category in self.__debug_categories:
print("DB:", *message)
def _sql(self, sql, values = None, callback = None):
"""Execute the given SQL statement."""
# Retrieve table list.
with self.__connection.cursor() as cursor:
if values is not None:
self._debug("execute", "Executing statement:", sql, *values)
cursor.execute(sql, values)
else:
self._debug("execute", "Executing statement:", sql)
cursor.execute(sql)
if callback is not None:
return callback(cursor)
def _provide_connection(self, sql_connection):
self.__connection = sql_connection
return self
def _provide(self, other):
self.__connection = other.__connection
self.__debug_categories = other.__debug_categories
return self
def _lstr(generator, seperator = ", "):
first = True
s = ""
for val in generator:
if not first:
s += seperator
first = False
s += val
return s
class _Numeric():
def __init__(self, fixed, float):
self.__fixed = fixed
self.__float = float
def __str__(self):
return "NUMERIC(" + str(self.__fixed) + ", " + str(self.__float) + ")"
def validate(self, value):
return True
def transform(self, value):
return float(value)
def format(self, value):
return str(value)
class _Int():
def __init__(self):
pass
def __str__(self):
return "INT"
def validate(self, value):
return True
def transform(self, value):
return int(value)
def format(self, value):
return str(value)
class _Varchar():
def __init__(self, length):
self.__length = length
def __str__(self):
return "VARCHAR(" + str(self.__length) + ")"
def validate(self, value):
return isinstance(value, str) and len(value) <= self.__length
def transform(self, value):
return value
def format(self, value):
return "'" + value + "'"
class _Char():
def __init__(self, length):
self.__length = length
def __str__(self):
return "CHAR(" + str(self.__length) + ")"
def validate(self, value):
return isinstance(value, str) and len(value) == self.__length
def transform(self, value):
return value
def format(self, value):
return "'" + value + "'"
class _Boolean():
def __str__(self):
return "BOOLEAN"
def validate(self, value):
return isinstance(value, bool)
def transform(self, value):
return bool(value)
def format(self, value):
if value:
return 'true'
return 'false'
class _Date():
def __str__(self):
return "DATETIME"
def validate(self, value):
return True
def transform(self, value):
return str(value)
def format(self, value):
return "'" + value + "'"
class _Enum():
def __init__(self, *values):
self.__values = values
def __str__(self):
return 'ENUM(' + _lstr('"' + v + '"' for v in self.__values) + ')'
def validate(self, value):
return value in self.__values
def transform(self, value):
return str(value)
def format(self, value):
return "'" + value + "'"
def hash_pass(password):
s = hashlib.sha256()
s.update(password.encode('utf-8'))
return str(base64.b64encode(s.digest()))[2:-1]
def _remove_visits(db, entry, value):
try:
db -= db.visits(property_id = entry.id)
except:
pass
return value
_TABLE_DESCRIPTIONS = {
'user': {
'email': {'type': _Varchar(100),
'traits': {'unique', 'primary'}},
'username': {'type': _Varchar(100),
'traits': {'unique'}},
'password': {'type': _Char(44),
'hook': {'set': lambda db, e, v: hash_pass(v)}},
'type': {'type': _Enum('admin', 'owner', 'visitor')}
},
'property': {
'id': {'type': _Int(),
'traits': {'unique', 'primary', 'auto_increment'},
'hook': {'set': _remove_visits}},
'name': {'type': _Varchar(100),
'traits': {'unique'},
'hook': {'set': _remove_visits}},
'address': {'type': _Varchar(100),
'hook': {'set': _remove_visits}},
'city': {'type': _Varchar(100),
'hook': {'set': _remove_visits}},
'zip': {'type': _Varchar(5),
'hook': {'set': _remove_visits}},
'size': {'type': _Numeric(8, 5),
'hook': {'set': _remove_visits}},
'is_commercial': {'type': _Boolean(),
'hook': {'set': _remove_visits}},
'is_public': {'type': _Boolean(),
'hook': {'set': _remove_visits}},
'owned_by': {'type': _Varchar(100),
'hook': {'set': _remove_visits},
'foreign': {'references': 'user(email)',
'delete': 'cascade',
'update': 'cascade'}},
'approved_by': {'type': _Varchar(100),
'traits': {'nullable'},
'hook': {'set': _remove_visits},
'foreign': {'references': 'user(email)',
'delete': 'set null',
'update': 'cascade'}},
'type': {'type': _Enum('farm', 'orchard', 'garden'),
'hook': {'set': _remove_visits}},
},
'item': {
'name': {'type': _Varchar(100),
'traits': {'unique', 'primary'}},
'approved_by': {'type': _Varchar(100),
'traits': {'nullable'},
'foreign': {'references': 'user(email)',
'delete': 'set null',
'update': 'cascade'}},
'category': {'type': _Enum('animal', 'fruit', 'nut', 'flower', 'vegetable')}
},
'has': {
'property_id': {'type': _Int(),
'traits': {'primary'},
'foreign': {'references': 'property(id)',
'delete': 'cascade',
'update': 'cascade'}},
'item_name': {'type': _Varchar(100),
'traits': {'primary'},
'foreign': {'references': 'item(name)',
'delete': 'cascade',
'update': 'cascade'}},
},
'visits': {
'date': {'type': _Varchar(100)},
'rating': {'type': _Numeric(5, 0)},
'property_id': {'type': _Int(),
'traits': {'primary'},
'foreign': {'references': 'property(id)',
'delete': 'cascade',
'update': 'cascade'}},
'user_email': {'type': _Varchar(100),
'traits': {'primary'},
'foreign': {'references': 'user(email)',
'delete': 'cascade',
'update': 'cascade'}},
}
}
# We create this manually as this encodes creation order of tables.
_TABLE_NAMES = [
'user',
'property',
'item',
'has',
'visits'
]
def _transform_hook(table, name, db, hook, entry = None, value = None, validate = True, pass_value = False):
"""
Given an item description, transform a mutation command using any hooks,
and then validate the result using the type validators.
"""
row = _TABLE_DESCRIPTIONS[table][name]
v = None
if 'hook' in row and hook in row['hook']:
if pass_value:
v = row['hook'][hook](db, entry, value)
else:
v = row['hook'][hook](db, entry)
#if validate:
#if not row['type'].validate(v):
#raise Exception("Failed to validate input data for form: " + table + '.' + name)
return v
return value
def _transform_field(table, name, value):
if value is not None:
return _TABLE_DESCRIPTIONS[table][name]['type'].transform(value)
return None
def _insert_clause(table, fields):
def conv(k, v):
if v is None:
return "NULL"
return _TABLE_DESCRIPTIONS[table][k]['type'].format(v)
f = []
for k, v in fields.items():
f.append((k, v))
f = sorted(f, key = lambda v: v[0])
return _lstr(
(conv(k, v)
for k, v
in f),
)
def _where_clause(table, fields):
def gen(k, v):
if v is None:
return k + " IS NULL"
return k + '=' + str(v)
def conv(k, v):
if v is None:
return None
return _TABLE_DESCRIPTIONS[table][k]['type'].format(v)
return _lstr(
(gen(k, v)
for k, v in
{k: conv(k, v)
for k, v
in fields.items()}.items()),
seperator = " AND "
)
class _Result(_SQL):
def __init__(self, db, name, value):
self.__name = name
self.__db = db
self.__value = value
def __delattr__(self, name):
if name not in _TABLE_DESCRIPTIONS[self.__name]:
pass
_transform_hook(self.__name, name, self.__db, 'set_null', self)
query = (
'UPDATE '
+ self.__name
+ ' SET '
+ name
+ ' = NULL WHERE '
+ _lstr(
(key + " = '" + value + "'"
for key, value
in self.__value.items()),
seperator = " AND "
)
)
self._sql(query)
def __setattr__(self, name, value):
if name[0] == '_':
super().__setattr__(name, value)
return
v = _transform_hook(
self.__name,
name,
self.__db,
'set', self, value,
pass_value = True
)
query = (
'UPDATE '
+ self.__name
+ ' SET '
+ name
+ ' = '
+ _insert_clause(self.__name, {name: value})
+ ' WHERE '
+ _where_clause(self.__name, self.__value)
)
self._sql(query)
self.__value[name] = value
def __getattr__(self, name):
if name not in _TABLE_DESCRIPTIONS[self.__name]:
pass
query = (
'SELECT '
+ name
+ ' FROM '
+ self.__name
+ ' WHERE '
+ _where_clause(self.__name, self.__value)
)
value = self._sql(query, callback = lambda c: c.fetchall())[0][name]
return _transform_field(
self.__name,
name,
_transform_hook(
self.__name,
name,
self.__db,
'get',
self,
value,
pass_value = True
)
)
class _Query(_SQL):
def __init__(self, db, name, key):
self.__db = db
self.__name = name
self.__key = key
self.__rows = None
def _append(self):
key = {k: _transform_hook(self.__name, k, self.__db, 'set', self, v, pass_value = True)
for k, v
in self.__key.items()}
query = (
"INSERT INTO "
+ self.__name
+ " ("
+ _lstr(sorted(key for key in self.__key.keys()))
+ " ) VALUES ("
+ _insert_clause(self.__name, key)
+ ")"
)
self._sql(query)
def __resolve(self):
if self.__rows is not None:
return
results = []
key = {k: _transform_hook(self.__name, k, self.__db, 'get', self, v, pass_value = True)
for k, v
in self.__key.items()}
if len(key) == 0:
query = (
'SELECT * FROM '
+ self.__name
)
else:
query = (
'SELECT * FROM '
+ self.__name
+ ' WHERE '
+ _where_clause(self.__name, key)
)
self.__rows = self._sql(query, callback = lambda c: c.fetchall())
print("Rows before transformation:", self.__rows)
self.__rows = [{k: _transform_field(self.__name, k, v)
for k, v
in r.items()}
for r in self.__rows]
print("Rows after transformation:", self.__rows)
def __getitem__(self, index):
self.__resolve()
return _Result(
self.__db,
self.__name,
self.__rows[index]
)._provide(self)
def __len__(self):
self.__resolve()
return len(self.__rows)
def _delete(self):
if len(self.__key) == 0:
self._sql('DELETE FROM ' + self.__name)
return
key = self.__key
def conv(v):
if v is None:
return 'IS NULL'
else:
return "= '" + str(v) + "'"
query = (
'DELETE FROM '
+ self.__name
+ ' WHERE '
+ _lstr(
(str(key) + ' '
+ conv(value)
for key, value in key.items()),
seperator = " AND "
)
)
self.__rows = self._sql(query, callback = lambda c: c.fetchall())
class _Table(_SQL):
def __init__(self, db, name):
"""Create a new table wrapper."""
self.__db = db
self.__name = name
def __call__(self, **key):
return _Query(
self.__db,
self.__name,
key
)._provide(self)
class DB(_SQL):
"""
A database manager.
"""
def __init_tables(self):
"""Make sure table layout is legal."""
tables = self._sql(
"SHOW TABLES",
callback = lambda c: [t['Tables_in_atplanta'] for t in c.fetchall()]
)
# Print tables we found.
for table in tables:
self._debug("table", "Discovered table:", table)
# Remove every extra table.
for table in tables:
if table not in _TABLE_NAMES:
self._sql("DROP TABLE " + table)
self._debug("table", "Removed extraneous table:", table)
# Create missing tables.
for needed_table in _TABLE_NAMES:
if needed_table not in tables:
# Table creation header.
statement = "CREATE TABLE " + needed_table + " ("
# Primary key tracker.
primaries = []
# Add fields to table creation.
first = True
auto_increment = False
for field, properties in _TABLE_DESCRIPTIONS[needed_table].items():
if not first:
statement += ", "
first = False
# Add field name
statement += field + " "
# Add field type.
statement += str(properties['type'])
# Check if nullable.
if "traits" in properties and ("nullable" not in properties["traits"]):
statement += " NOT NULL"
# Check if unique.
if "traits" in properties and ("unique" in properties["traits"]):
statement += " UNIQUE"
# Check if primary key.
if "traits" in properties and ("primary" in properties["traits"]):
primaries.append(field)
if "traits" in properties and ("auto_increment" in properties["traits"]):
statement += " AUTO_INCREMENT"
auto_increment = True
# Check if foreign key.
if "foreign" in properties:
fprops = properties['foreign']
statement += ", FOREIGN KEY (" + field + ") REFERENCES " + fprops["references"]
if 'update' in fprops:
statement += " ON UPDATE " + fprops["update"].upper()
if 'delete' in fprops:
statement += " ON DELETE " + fprops["delete"].upper()
# Add primary keys to statement.
if len(primaries) != 0:
if not first:
statement += ","
statement += ' PRIMARY KEY(' + _lstr(primaries) + ')'
statement += ") ENGINE = InnoDB"
self._sql(statement)
if auto_increment:
self._sql("ALTER TABLE " + needed_table + " AUTO_INCREMENT=00000")
self._debug("table", "Created missing table:", needed_table)
def __init__(self,
host = 'localhost',
user = 'root',
password = 'password',
database = 'atplanta',
debug = set()):
"""Connect to the Atplanta database, and initliaze a DB class around it."""
# Set debug flag.
self._provide_debug(debug)
# Our local DB connection.
self._provide_connection(
pymysql.connect(
host = host,
user = user,
password = password,
db = database,
charset = 'utf8mb4',
cursorclass = pymysql.cursors.DictCursor,
autocommit = True
)
)
# Ensure table layout is legal.
self.__init_tables()
def __iadd__(self, entry):
if not isinstance(entry, _Query):
raise Exception("Can only insert query into the database.")
entry._append()
return self
def __isub__(self, entry):
if isinstance(entry, _Query) or isinstance(entry, _Row):
entry._delete()
return self
raise Exception("Tried to delete from database with invalid type.")
def __getattr__(self, name):
"""Returns the named table."""
# Don't hijack access to attributes that are not part of the schema.
if name.lower() not in _TABLE_NAMES:
pass
return _Table(
self,
name
)._provide(self)