-
Notifications
You must be signed in to change notification settings - Fork 150
/
db.py
3134 lines (2629 loc) · 156 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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import itertools
import json
import logging
import re
import time
from collections import defaultdict
from copy import copy
from os import path
import migrate.versioning.api
import migrate.versioning.schema
import sqlalchemy.event
import sqlalchemy.types
from aiohttp import ClientSession
from sqlalchemy import JSON, BigInteger, Boolean, Column, Integer, MetaData, String, Table, Text, create_engine, func, join, select
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.sql.expression import null
from sqlalchemy.sql.functions import max as sql_max
from auslib.blobs.base import createBlob, merge_dicts
from auslib.errors import PermissionDeniedError, ReadOnlyError, SignoffRequiredError
from auslib.global_state import cache
from auslib.util.rulematching import (
matchBoolean,
matchBuildID,
matchChannel,
matchCsv,
matchLocale,
matchMemory,
matchRegex,
matchSimpleExpression,
matchVersion,
)
from auslib.util.timestamp import getMillisecondTimestamp
from auslib.util.versions import get_version_class
def rows_to_dicts(rows):
"""Converts SQL Alchemy result rows to dicts.
You might want this if you want to mutate objects (SQLAlchemy rows
are immutable), or if you want to serialize them to JSON
(SQLAlchemy rows get confused if you try to serialize them).
"""
# In Python 3, map returns an iterable instead a list.
return [dict(row) for row in rows]
class AlreadySetupError(Exception):
def __str__(self):
return "Can't connect to new database, still connected to previous one"
class TransactionError(SQLAlchemyError):
"""Raised when a transaction fails for any reason."""
class OutdatedDataError(SQLAlchemyError):
"""Raised when an update or delete fails because of outdated data."""
class MismatchedDataVersionError(SQLAlchemyError):
"""Raised when the data version of a scheduled change and its associated conditions
row do not match after an insert or update."""
class WrongNumberOfRowsError(SQLAlchemyError):
"""Raised when an update or delete fails because the clause matches more than one row."""
class UpdateMergeError(SQLAlchemyError):
pass
class ChangeScheduledError(SQLAlchemyError):
"""Raised when a Scheduled Change cannot be created, modified, or deleted
for data consistency reasons."""
class JSONColumn(sqlalchemy.types.TypeDecorator):
"""JSONColumns are used for types that are deserialized JSON (usually
dicts) in memory, but need to be serialized to text before storage.
JSONColumn handles the conversion both ways, serialized just before
storage, and deserialized just after retrieval."""
impl = Text
cache_ok = True
def process_bind_param(self, value, dialect):
if value:
value = json.dumps(value)
return value
def process_result_value(self, value, dialect):
if value:
value = json.loads(value)
return value
class CompatibleBooleanColumn(sqlalchemy.types.TypeDecorator):
"""A Boolean column that is compatible with all of our supported
database engines (mysql, sqlite). SQLAlchemy's built-in Boolean
does not work because it creates a CHECK constraint that makes
it impossible to downgrade a database with sqlalchemy-migrate."""
impl = Integer
cache_ok = True
def process_bind_param(self, value, dialect):
if value is not None:
if not isinstance(value, bool):
raise TypeError("{} is invalid type ({}), must be bool".format(value, type(value)))
if value is True:
value = 1
else:
value = 0
return value
def process_result_value(self, value, dialect):
# Boolean columns may be nullable, we need to be sure to preserve nulls
# in case consumers treat them differently than False.
if value is not None:
value = bool(value)
return value
def BlobColumn(impl=Text):
"""BlobColumns are used to store Release Blobs, which are ultimately dicts.
Release Blobs must be serialized before storage, and deserialized upon
retrieval. This type handles both conversions. Some database engines
(eg: mysql) may require a different underlying type than Text. The
desired type may be passed in as an argument."""
class cls(sqlalchemy.types.TypeDecorator):
cache_ok = True
def process_bind_param(self, value, dialect):
if value:
value = value.getJSON()
return value
def process_result_value(self, value, dialect):
if value:
value = createBlob(value)
return value
cls.impl = impl
return cls
def verify_signoffs(potential_required_signoffs, signoffs):
"""Determines whether or not something is signed off given:
* A list of potential required signoffs
* A list of signoffs that have been made
The real number of signoffs required is found by looking through the
potential required signoffs and finding the highest number required for each
role. If there are not enough signoffs provided for any of the groups,
a SignoffRequiredError is raised."""
signoffs_given = defaultdict(int)
required_signoffs = {}
if not potential_required_signoffs:
return
if not signoffs:
raise SignoffRequiredError("No Signoffs given")
for signoff in signoffs:
signoffs_given[signoff["role"]] += 1
for rs in potential_required_signoffs:
required_signoffs[rs["role"]] = max(required_signoffs.get(rs["role"], 0), rs["signoffs_required"])
for role, signoffs_required in required_signoffs.items():
if signoffs_given[role] < signoffs_required:
raise SignoffRequiredError("Not enough signoffs for role '{}'".format(role))
class AUSTransaction(object):
"""Manages a single transaction. Requires a connection object.
:param conn: connection object to perform the transaction on
:type conn: sqlalchemy.engine.base.Connection
"""
def __init__(self, engine):
self.engine = engine
self.conn = self.engine.connect()
self.trans = self.conn.begin()
self.log = logging.getLogger(self.__class__.__name__)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
try:
# If something that executed in the context raised an Exception,
# rollback and re-raise it.
if exc_type:
self.log.debug("exc is:", exc_info=True)
self.rollback()
e = exc_type(exc_value)
e.__traceback__ = exc_traceback
raise e
# self.commit will issue a rollback if it raises
self.commit()
finally:
# Always make sure the connection is closed, bug 740360
self.close()
def close(self):
# For some reason, sometimes the connection appears to close itself...
if not self.conn.closed:
self.conn.close()
def execute(self, statement):
try:
self.log.debug("Attempting to execute %s" % statement)
return self.conn.execute(statement)
except Exception as exc:
self.log.debug("Caught exception")
# We want to raise our own Exception, so that errors are easily
# caught by consumers. The dance below lets us do that without
# losing the original Traceback, which will be much more
# informative than one starting from this point.
self.rollback()
raise TransactionError() from exc
def commit(self):
try:
self.trans.commit()
except Exception as exc:
self.rollback()
raise TransactionError() from exc
def rollback(self):
self.trans.rollback()
class AUSTable(object):
"""Base class for all AUS Tables. By default, all tables have a history
table created for them, too, which mirrors their own structure and adds
a record of who made a change, and when the change happened.
:param history: Whether or not to create a history table for this table.
When True, a History object will be created for this
table, and all changes will be logged to it. Defaults
to True.
:type history: bool
:param versioned: Whether or not this table is versioned. When True,
an additional 'data_version' column will be added
to the Table, and its version increased with every
update. This is useful for detecting colliding
updates.
:type versioned: bool
:param scheduled_changes: Whether or not this table should allow changes
to be scheduled. When True, two additional tables
will be created: a $name_scheduled_changes, which
will contain data needed to schedule changes to
$name, and $name_scheduled_changes_history, which
tracks the history of a scheduled change.
:type scheduled_changes: bool
"""
def __init__(
self,
db,
dialect,
historyClass=None,
historyKwargs={},
versioned=True,
scheduled_changes=False,
scheduled_changes_kwargs={},
):
self.db = db
self.t = self.table
# Enable versioning, if required
if versioned:
self.t.append_column(Column("data_version", Integer, nullable=False))
self.versioned = versioned
# Mirror the columns as attributes for easy access
self.primary_key = []
for col in self.table.columns:
setattr(self, col.name, col)
if col.primary_key:
self.primary_key.append(col)
# Set-up a history table to do logging in, if required
if historyClass:
self.history = historyClass(db, dialect, self.t.metadata, self, **historyKwargs)
else:
self.history = None
# Set-up a scheduled changes table if required
if scheduled_changes:
self.scheduled_changes = ScheduledChangeTable(db, dialect, self.t.metadata, self, **scheduled_changes_kwargs)
else:
self.scheduled_changes = None
self.log = logging.getLogger(self.__class__.__name__)
# Can't do this in the constructor, because the engine is always
# unset when we're instantiated
def getEngine(self):
return self.t.metadata.bind
def _returnRowOrRaise(self, where, columns=None, transaction=None):
"""Return the row matching the where clause supplied. If no rows match or multiple rows match,
a WrongNumberOfRowsError will be raised."""
rows = self.select(where=where, columns=columns, transaction=transaction)
if len(rows) == 0:
raise WrongNumberOfRowsError("where clause matched no rows")
if len(rows) > 1:
raise WrongNumberOfRowsError("where clause matches multiple rows (primary keys: %s)" % rows)
return rows[0]
def _selectStatement(self, columns=None, where=None, order_by=None, limit=None, offset=None, distinct=False):
"""Create a SELECT statement on this table.
:param columns: Column objects to select. Defaults to None, meaning select all columns
:type columns: A sequence of sqlalchemy.schema.Column objects or column names as strings
:param order_by: Columns to sort the rows by. Defaults to None, meaning no ORDER BY clause
:type order_by: A sequence of sqlalchemy.schema.Column objects
:param limit: Limit results to this many. Defaults to None, meaning no limit
:type limit: int
:param distinct: Whether or not to return only distinct rows. Default: False.
:type distinct: bool
:rtype: sqlalchemy.sql.expression.Select
"""
if columns:
table_columns = [(self.t.c[col] if isinstance(col, str) else col) for col in columns]
query = select(table_columns, order_by=order_by, limit=limit, offset=offset, distinct=distinct)
else:
query = self.t.select(order_by=order_by, limit=limit, offset=offset, distinct=distinct)
if where:
for cond in where:
query = query.where(cond)
return query
def select(self, where=None, transaction=None, **kwargs):
"""Perform a SELECT statement on this table.
See AUSTable._selectStatement for possible arguments.
:param where: A list of SQLAlchemy clauses, or a key/value pair of columns and values.
:type where: list of clauses or key/value pairs.
:param transaction: A transaction object to add the update statement (and history changes) to.
If provided, you must commit the transaction yourself. If None, they will
be added to a locally-scoped transaction and committed.
:rtype: sqlalchemy.engine.base.ResultProxy
"""
# If "where" is key/value pairs, we need to convert it to SQLAlchemy
# clauses before proceeding.
if hasattr(where, "keys"):
where = [getattr(self, k) == v for k, v in where.items()]
query = self._selectStatement(where=where, **kwargs)
if transaction:
result = transaction.execute(query).fetchall()
else:
with AUSTransaction(self.getEngine()) as trans:
result = trans.execute(query).fetchall()
return rows_to_dicts(result)
def _insertStatement(self, **columns):
"""Create an INSERT statement for this table
:param columns: Data to insert
:type colmuns: dict
:rtype: sqlalchemy.sql.express.Insert
"""
table_columns = {k: columns[k] for k in columns.keys() if k in self.table.c}
unconsumed_columns = {k: columns[k] for k in columns.keys() if k not in table_columns}
return self.t.insert(values=table_columns), unconsumed_columns
def _sharedPrepareInsert(self, trans, changed_by, **columns):
"""Prepare an INSERT statement for commit. If this table has versioning enabled,
data_version will be set to 1. If this table has history enabled, two rows
will be created in that table: one representing the current state (NULL),
and one representing the new state.
:rtype: sqlalchemy.engine.base.ResultProxy
"""
data = columns.copy()
if self.versioned:
data["data_version"] = 1
query, unconsumed_columns = self._insertStatement(**data)
ret = trans.execute(query)
return data, ret
def _prepareInsert(self, trans, changed_by, **columns):
data, ret = self._sharedPrepareInsert(trans, changed_by, **columns)
if self.history:
self.history.forInsert(ret.inserted_primary_key, data, changed_by, trans)
return ret
async def _asyncPrepareInsert(self, trans, changed_by, **columns):
data, ret = self._sharedPrepareInsert(trans, changed_by, **columns)
if self.history:
await self.history.forInsert(ret.inserted_primary_key, data, changed_by, trans)
return ret
def insert(self, changed_by=None, transaction=None, dryrun=False, **columns):
"""Perform an INSERT statement on this table. See AUSTable._insertStatement for
a description of columns.
:param changed_by: The username of the person inserting the row. Required when
history is enabled. Unused otherwise. No authorization checks are done
at this level.
:type changed_by: str
:param transaction: A transaction object to add the insert statement (and history changes) to.
If provided, you must commit the transaction yourself. If None, they will
be added to a locally-scoped transaction and committed.
:param dryrun: If true, this insert statement will not actually be run.
:type dryrun: bool
:rtype: sqlalchemy.engine.base.ResultProxy
"""
if self.history and not changed_by:
raise ValueError("changed_by must be passed for Tables that have history")
if dryrun:
self.log.debug("In dryrun mode, not doing anything...")
return
if transaction:
return self._prepareInsert(transaction, changed_by, **columns)
else:
with AUSTransaction(self.getEngine()) as trans:
return self._prepareInsert(trans, changed_by, **columns)
async def async_insert(self, changed_by=None, transaction=None, dryrun=False, **columns):
"""Perform an INSERT statement on this table. See AUSTable._insertStatement for
a description of columns.
:param changed_by: The username of the person inserting the row. Required when
history is enabled. Unused otherwise. No authorization checks are done
at this level.
:type changed_by: str
:param transaction: A transaction object to add the insert statement (and history changes) to.
If provided, you must commit the transaction yourself. If None, they will
be added to a locally-scoped transaction and committed.
:param dryrun: If true, this insert statement will not actually be run.
:type dryrun: bool
:rtype: sqlalchemy.engine.base.ResultProxy
"""
if self.history and not changed_by:
raise ValueError("changed_by must be passed for Tables that have history")
if dryrun:
self.log.debug("In dryrun mode, not doing anything...")
return
if transaction:
return await self._asyncPrepareInsert(transaction, changed_by, **columns)
else:
with AUSTransaction(self.getEngine()) as trans:
return await self._asyncPrepareInsert(trans, changed_by, **columns)
def _deleteStatement(self, where):
"""Create a DELETE statement for this table.
:param where: Conditions to apply on this select.
:type where: A sequence of sqlalchemy.sql.expression.ClauseElement objects
:rtype: sqlalchemy.sql.expression.Delete
"""
query = self.t.delete()
if where:
for cond in where:
query = query.where(cond)
return query
def _sharedPrepareDelete(self, trans, where, changed_by, old_data_version):
"""Prepare a DELETE statement for commit. If this table has history enabled,
a row will be created in that table representing the new state of the
row being deleted (NULL). If versioning is enabled and old_data_version
doesn't match the current version of the row to be deleted, an OutdatedDataError
will be raised.
:rtype: sqlalchemy.engine.base.ResultProxy
"""
row = self._returnRowOrRaise(where=where, columns=self.primary_key, transaction=trans)
if self.versioned:
where = copy(where)
where.append(self.data_version == old_data_version)
query = self._deleteStatement(where)
ret = trans.execute(query)
if ret.rowcount != 1:
raise OutdatedDataError("Failed to delete row, old_data_version doesn't match current data_version")
if self.scheduled_changes:
# If this table has active scheduled changes we cannot allow it to be deleted
sc_where = [self.scheduled_changes.complete == False] # noqa
for pk in self.primary_key:
sc_where.append(getattr(self.scheduled_changes, "base_%s" % pk.name) == row[pk.name])
if self.scheduled_changes.select(where=sc_where, transaction=trans):
raise ChangeScheduledError("Cannot delete rows that have changes scheduled.")
return row, ret
def _prepareDelete(self, trans, where, changed_by, old_data_version):
row, ret = self._sharedPrepareDelete(trans, where, changed_by, old_data_version)
if self.history:
self.history.forDelete(row, changed_by, trans)
return ret
async def _asyncPrepareDelete(self, trans, where, changed_by, old_data_version):
row, ret = self._sharedPrepareDelete(trans, where, changed_by, old_data_version)
if self.history:
await self.history.forDelete(row, changed_by, trans)
return ret
def delete(self, where, changed_by=None, old_data_version=None, transaction=None, dryrun=False):
"""Perform a DELETE statement on this table. See AUSTable._deleteStatement for
a description of `where`. To simplify versioning, this method can only
delete a single row per invocation. If the where clause given would delete
zero or multiple rows, a WrongNumberOfRowsError is raised.
:param where: A list of SQLAlchemy clauses, or a key/value pair of columns and values.
:type where: list of clauses or key/value pairs.
:param changed_by: The username of the person deleting the row(s). Required when
history is enabled. Unused otherwise. No authorization checks are done
at this level.
:type changed_by: str
:param old_data_version: Previous version of the row to be deleted. If this version doesn't
match the current version of the row, an OutdatedDataError will be
raised and the delete will fail. Required when versioning is enabled.
:type old_data_version: int
:param transaction: A transaction object to add the delete statement (and history changes) to.
If provided, you must commit the transaction yourself. If None, they will
be added to a locally-scoped transaction and committed.
:param dryrun: If true, this insert statement will not actually be run.
:type dryrun: bool
:rtype: sqlalchemy.engine.base.ResultProxy
"""
# If "where" is key/value pairs, we need to convert it to SQLAlchemy
# clauses before proceeding.
if hasattr(where, "keys"):
where = [getattr(self, k) == v for k, v in where.items()]
if self.history and not changed_by:
raise ValueError("changed_by must be passed for Tables that have history")
if self.versioned and not old_data_version:
raise ValueError("old_data_version must be passed for Tables that are versioned")
if dryrun:
self.log.debug("In dryrun mode, not doing anything...")
return
if transaction:
return self._prepareDelete(transaction, where, changed_by, old_data_version)
else:
with AUSTransaction(self.getEngine()) as trans:
return self._prepareDelete(trans, where, changed_by, old_data_version)
async def async_delete(self, where, changed_by=None, old_data_version=None, transaction=None, dryrun=False):
"""Perform a DELETE statement on this table. See AUSTable._deleteStatement for
a description of `where`. To simplify versioning, this method can only
delete a single row per invocation. If the where clause given would delete
zero or multiple rows, a WrongNumberOfRowsError is raised.
:param where: A list of SQLAlchemy clauses, or a key/value pair of columns and values.
:type where: list of clauses or key/value pairs.
:param changed_by: The username of the person deleting the row(s). Required when
history is enabled. Unused otherwise. No authorization checks are done
at this level.
:type changed_by: str
:param old_data_version: Previous version of the row to be deleted. If this version doesn't
match the current version of the row, an OutdatedDataError will be
raised and the delete will fail. Required when versioning is enabled.
:type old_data_version: int
:param transaction: A transaction object to add the delete statement (and history changes) to.
If provided, you must commit the transaction yourself. If None, they will
be added to a locally-scoped transaction and committed.
:param dryrun: If true, this insert statement will not actually be run.
:type dryrun: bool
:rtype: sqlalchemy.engine.base.ResultProxy
"""
# If "where" is key/value pairs, we need to convert it to SQLAlchemy
# clauses before proceeding.
if hasattr(where, "keys"):
where = [getattr(self, k) == v for k, v in where.items()]
if self.history and not changed_by:
raise ValueError("changed_by must be passed for Tables that have history")
if self.versioned and not old_data_version:
raise ValueError("old_data_version must be passed for Tables that are versioned")
if dryrun:
self.log.debug("In dryrun mode, not doing anything...")
return
if transaction:
return await self._asyncPrepareDelete(transaction, where, changed_by, old_data_version)
else:
with AUSTransaction(self.getEngine()) as trans:
return await self._asyncPrepareDelete(trans, where, changed_by, old_data_version)
def _updateStatement(self, where, what):
"""Create an UPDATE statement for this table
:param where: Conditions to apply to this UPDATE.
:type where: A sequence of sqlalchemy.sql.expression.ClauseElement objects.
:param what: Data to update
:type what: dict
:rtype: sqlalchemy.sql.expression.Update
"""
table_what = {k: what[k] for k in what.keys() if k in self.table.c}
unconsumed_columns = {k: what[k] for k in what.keys() if k not in table_what}
query = self.t.update(values=table_what)
if where:
for cond in where:
query = query.where(cond)
return query, unconsumed_columns
def _sharedPrepareUpdate(self, trans, where, what, changed_by, old_data_version):
"""Prepare an UPDATE statement for commit. If this table has versioning enabled,
data_version will be increased by 1. If this table has history enabled, a
row will be added to that table represent the new state of the data.
:rtype: sqlalchemy.engine.base.ResultProxy
"""
# To do merge detection for tables with scheduled changes we need a
# copy of the original row, and what will be changed. To record
# history, we need a copy of the entire new row.
orig_row = self._returnRowOrRaise(where=where, transaction=trans)
new_row = orig_row.copy()
if self.versioned:
where = copy(where)
where.append(self.data_version == old_data_version)
new_row["data_version"] += 1
what["data_version"] = new_row["data_version"]
# Copy the new data into the row
for col in what:
new_row[col] = what[col]
query, unconsumed_columns = self._updateStatement(where, new_row)
ret = trans.execute(query)
# It's important that OutdatedDataError is raised as early as possible
# because callers may be able to handle it gracefully (and continue
# with their update). If we raise this _after_ adding history or merging
# with Scheduled Changes, we may end up altering the history or
# scheduled changes more than once if the caller ends up re-calling
# AUSTable.update() after handling the OutdatedDataError.
if ret.rowcount != 1:
raise OutdatedDataError("Failed to update row, old_data_version doesn't match current data_version")
if self.scheduled_changes:
self.scheduled_changes.mergeUpdate(orig_row, what, changed_by, trans)
return new_row, ret
def _prepareUpdate(self, trans, where, what, changed_by, old_data_version):
new_row, ret = self._sharedPrepareUpdate(trans, where, what, changed_by, old_data_version)
if self.history:
self.history.forUpdate(new_row, changed_by, trans)
return ret
async def _asyncPrepareUpdate(self, trans, where, what, changed_by, old_data_version):
new_row, ret = self._sharedPrepareUpdate(trans, where, what, changed_by, old_data_version)
if self.history:
await self.history.forUpdate(new_row, changed_by, trans)
return ret
def update(self, where, what, changed_by=None, old_data_version=None, transaction=None, dryrun=False):
"""Perform an UPDATE statement on this table. See AUSTable._updateStatement for
a description of `where` and `what`. This method can only update a single row
per invocation. If the where clause given would update zero or multiple rows, a
WrongNumberOfRowsError is raised.
:param where: A list of SQLAlchemy clauses, or a key/value pair of columns and values.
:type where: list of clauses or key/value pairs.
:param what: Key/value pairs containing new values for the given columns.
:type what: key/value pairs
:param changed_by: The username of the person inserting the row. Required when
history is enabled. Unused otherwise. No authorization checks are done
at this level.
:type changed_by: str
:param old_data_version: Previous version of the row to be deleted. If this version doesn't
match the current version of the row, an OutdatedDataError will be
raised and the delete will fail. Required when versioning is enabled.
:type old_data_version: int
:param transaction: A transaction object to add the update statement (and history changes) to.
If provided, you must commit the transaction yourself. If None, they will
be added to a locally-scoped transaction and committed.
:param dryrun: If true, this insert statement will not actually be run.
:type dryrun: bool
:rtype: sqlalchemy.engine.base.ResultProxy
"""
# If "where" is key/value pairs, we need to convert it to SQLAlchemy
# clauses before proceeding.
if hasattr(where, "keys"):
where = [getattr(self, k) == v for k, v in where.items()]
if self.history and not changed_by:
raise ValueError("changed_by must be passed for Tables that have history")
if self.versioned and not old_data_version:
raise ValueError("update: old_data_version must be passed for Tables that are versioned")
if dryrun:
self.log.debug("In dryrun mode, not doing anything...")
return
if transaction:
return self._prepareUpdate(transaction, where, what, changed_by, old_data_version)
else:
with AUSTransaction(self.getEngine()) as trans:
return self._prepareUpdate(trans, where, what, changed_by, old_data_version)
async def async_update(self, where, what, changed_by=None, old_data_version=None, transaction=None, dryrun=False):
"""Perform an UPDATE statement on this table. See AUSTable._updateStatement for
a description of `where` and `what`. This method can only update a single row
per invocation. If the where clause given would update zero or multiple rows, a
WrongNumberOfRowsError is raised.
:param where: A list of SQLAlchemy clauses, or a key/value pair of columns and values.
:type where: list of clauses or key/value pairs.
:param what: Key/value pairs containing new values for the given columns.
:type what: key/value pairs
:param changed_by: The username of the person inserting the row. Required when
history is enabled. Unused otherwise. No authorization checks are done
at this level.
:type changed_by: str
:param old_data_version: Previous version of the row to be deleted. If this version doesn't
match the current version of the row, an OutdatedDataError will be
raised and the delete will fail. Required when versioning is enabled.
:type old_data_version: int
:param transaction: A transaction object to add the update statement (and history changes) to.
If provided, you must commit the transaction yourself. If None, they will
be added to a locally-scoped transaction and committed.
:param dryrun: If true, this insert statement will not actually be run.
:type dryrun: bool
:rtype: sqlalchemy.engine.base.ResultProxy
"""
# If "where" is key/value pairs, we need to convert it to SQLAlchemy
# clauses before proceeding.
if hasattr(where, "keys"):
where = [getattr(self, k) == v for k, v in where.items()]
if self.history and not changed_by:
raise ValueError("changed_by must be passed for Tables that have history")
if self.versioned and not old_data_version:
raise ValueError("update: old_data_version must be passed for Tables that are versioned")
if dryrun:
self.log.debug("In dryrun mode, not doing anything...")
return
if transaction:
return await self._asyncPrepareUpdate(transaction, where, what, changed_by, old_data_version)
else:
with AUSTransaction(self.getEngine()) as trans:
return await self._asyncPrepareUpdate(trans, where, what, changed_by, old_data_version)
def count(self, column="*", where=None, transaction=None):
count_statement = select(columns=[func.count(column)], from_obj=self.t)
if where:
for cond in where:
count_statement = count_statement.where(cond)
if transaction:
row_count = transaction.execute(count_statement).scalar()
else:
with AUSTransaction(self.getEngine()) as trans:
row_count = trans.execute(count_statement).scalar()
return row_count
def getRecentChanges(self, limit=10, transaction=None):
return self.history.select(transaction=transaction, limit=limit, order_by=self.history.timestamp.desc())
class GCSHistory:
def __init__(self, db, dialect, metadata, baseTable, buckets, identifier_columns, data_column):
self.buckets = buckets
self.identifier_columns = identifier_columns
self.data_column = data_column
def _getBucket(self, identifier):
for substring, bucket in self.buckets.items():
if substring in identifier:
return bucket
else:
raise KeyError("Couldn't find bucket to place {} history in.".format(identifier))
def forInsert(self, insertedKeys, columns, changed_by, trans):
timestamp = getMillisecondTimestamp()
identifier = "-".join([columns.get(i) for i in self.identifier_columns])
for data_version, ts, data in ((None, timestamp - 1, ""), (columns.get("data_version"), timestamp, json.dumps(columns[self.data_column]))):
bname = "{}/{}-{}-{}.json".format(identifier, data_version, ts, changed_by)
start = time.time()
logging.info("Beginning GCS upload", extra={"file": bname})
bucket = self._getBucket(identifier)(use_gcloud_aio=False)
blob = bucket.blob(bname)
blob.upload_from_string(data, content_type="application/json")
duration = time.time() - start
logging.info("Completed GCS upload", extra={"file": bname, "duration": duration})
def forDelete(self, rowData, changed_by, trans):
identifier = "-".join([rowData.get(i) for i in self.identifier_columns])
bname = "{}/{}-{}-{}.json".format(identifier, rowData.get("data_version"), getMillisecondTimestamp(), changed_by)
start = time.time()
logging.info("Beginning GCS upload", extra={"file": bname})
bucket = self._getBucket(identifier)(use_gcloud_aio=False)
blob = bucket.blob(bname)
blob.upload_from_string("", content_type="application/json")
duration = time.time() - start
logging.info("Completed GCS upload", extra={"file": bname, "duration": duration})
def forUpdate(self, rowData, changed_by, trans):
identifier = "-".join([rowData.get(i) for i in self.identifier_columns])
bname = "{}/{}-{}-{}.json".format(identifier, rowData.get("data_version"), getMillisecondTimestamp(), changed_by)
start = time.time()
logging.info("Beginning GCS upload", extra={"file": bname})
bucket = self._getBucket(identifier)(use_gcloud_aio=False)
blob = bucket.blob(bname)
blob.upload_from_string(json.dumps(rowData[self.data_column]), content_type="application/json")
duration = time.time() - start
logging.info("Completed GCS upload", extra={"file": bname, "duration": duration})
def getChange(self, change_id=None, column_values=None, data_version=None, transaction=None):
if not set(self.identifier_columns).issubset(column_values.keys()) or not data_version:
raise ValueError("Cannot find GCS changes without {} and data_version".format(self.identifier_columns))
identifier = "-".join([column_values[i] for i in self.identifier_columns])
bucket = self._getBucket(identifier)(use_gcloud_aio=False)
blobs = [b for b in bucket.list_blobs(prefix="{}/{}".format(identifier, data_version))]
if len(blobs) != 1:
raise ValueError("Found {} blobs instead of 1".format(len(blobs)))
return {tuple(self.identifier_columns): identifier, "data_version": data_version, self.data_column: json.loads(blobs[0].download_as_string())}
class GCSHistoryAsync:
def __init__(self, db, dialect, metadata, baseTable, buckets, identifier_columns, data_column):
self.db = db
self.buckets = buckets
self.identifier_columns = identifier_columns
self.data_column = data_column
def _getBucket(self, identifier):
for substring, bucket in self.buckets.items():
if substring in identifier:
return bucket
else:
raise KeyError("Couldn't find bucket to place {} history in.".format(identifier))
async def forInsert(self, insertedKeys, columns, changed_by, trans):
timestamp = getMillisecondTimestamp()
identifier = "-".join([columns.get(i) for i in self.identifier_columns])
for data_version, ts, data in ((None, timestamp - 1, ""), (columns.get("data_version"), timestamp, json.dumps(columns[self.data_column]))):
bname = "{}/{}-{}-{}.json".format(identifier, data_version, ts, changed_by)
start = time.time()
logging.info("Beginning GCS upload", extra={"file": bname})
# Using a separate session for each request is not ideal, but it's
# the only thing that seems to work. Ideally, we'd share one session
# for the entire application, but we can't for two reasons:
# 1) gcloud-aio won't close the sessions, which results in a lot of
# errors (https://github.com/talkiq/gcloud-aio/issues/33)
# 2) When bhearsum tried this it resulted in hangs that he suspected
# were caused by connection re-use.
async with ClientSession() as session:
bucket = self._getBucket(identifier)(session=session)
blob = bucket.new_blob(bname)
await blob.upload(data, session=session)
duration = time.time() - start
logging.info("Completed GCS upload", extra={"file": bname, "duration": duration})
async def forDelete(self, rowData, changed_by, trans):
identifier = "-".join([rowData.get(i) for i in self.identifier_columns])
bname = "{}/{}-{}-{}.json".format(identifier, rowData.get("data_version"), getMillisecondTimestamp(), changed_by)
start = time.time()
logging.info("Beginning GCS upload", extra={"file": bname})
async with ClientSession() as session:
bucket = self._getBucket(identifier)(session=session)
blob = bucket.new_blob(bname)
await blob.upload("", session=session)
duration = time.time() - start
logging.info("Completed GCS upload", extra={"file": bname, "duration": duration})
async def forUpdate(self, rowData, changed_by, trans):
identifier = "-".join([rowData.get(i) for i in self.identifier_columns])
bname = "{}/{}-{}-{}.json".format(identifier, rowData.get("data_version"), getMillisecondTimestamp(), changed_by)
start = time.time()
logging.info("Beginning GCS upload", extra={"file": bname})
async with ClientSession() as session:
bucket = self._getBucket(identifier)(session=session)
blob = bucket.new_blob(bname)
await blob.upload(json.dumps(rowData[self.data_column]), session=session)
duration = time.time() - start
logging.info("Completed GCS upload", extra={"file": bname, "duration": duration})
class HistoryTable(AUSTable):
"""Represents a history table that may be attached to another AUSTable.
History tables mirror the structure of their `baseTable`, with the exception
that nullable and primary_key attributes are always overwritten to be
True and False respectively. Additionally, History tables have a unique
change_id for each row, and record the username making a change, and the
timestamp of each change. The methods forInsert, forDelete, and forUpdate
will generate appropriate INSERTs to the History table given appropriate
inputs, and are documented below. History tables are never versioned,
and cannot have history of their own."""
def __init__(self, db, dialect, metadata, baseTable):
self.baseTable = baseTable
self.table = Table(
"%s_history" % baseTable.t.name,
metadata,
Column("change_id", Integer, primary_key=True, autoincrement=True),
Column("changed_by", String(100), nullable=False),
)
# Timestamps are stored as an integer, but actually contain
# precision down to the millisecond, achieved through
# multiplication.
# SQLAlchemy's SQLite dialect doesn't support fully support BigInteger.
# The Column will work, but it ends up being a NullType Column which
# breaks our upgrade unit tests. Because of this, we make sure to use
# a plain Integer column for SQLite. In MySQL, an Integer is
# Integer(11), which is too small for our needs.
if dialect == "sqlite":
self.table.append_column(Column("timestamp", Integer, nullable=False))
else:
self.table.append_column(Column("timestamp", BigInteger, nullable=False))
self.base_primary_key = [pk.name for pk in baseTable.primary_key]
for col in baseTable.t.columns:
newcol = col.copy()
if col.primary_key:
newcol.primary_key = False
else:
newcol.nullable = True
# Setting unique to None because SQLAlchemy marks column attribute as None
# unless they have been explicitely set to True or False.
newcol.unique = None
self.table.append_column(newcol)
AUSTable.__init__(self, db, dialect, historyClass=None, versioned=False)
def getPointInTime(self, timestamp, transaction=None):
# The inner query here gets one change id for every unique object in
# the base table. Filtering by timestamp < provided timestamp means
# we won't get any results most recent than the requested timestamp.
# Grouping by the primary key and selecting the max change_id means
# we'll get the most recent change_id (after applying the timestamp
# filter) for every unique object.
# The outer query simply retrieves the actual row data for each
# change_id that the inner query found
# Black wants to format this all on one line, which is more difficult
# to read.
# fmt: off
q = (select(self.table.columns)
.where(self.change_id.in_(
select([sql_max(self.change_id)])
.where(self.timestamp <= timestamp)
.group_by(*self.base_primary_key)
)
))
# fmt: on
if transaction:
result = transaction.execute(q).fetchall()
else:
with AUSTransaction(self.getEngine()) as trans:
result = trans.execute(q).fetchall()
rows = []
# Filter out any rows who have no non-primary key data, because this
# means the row has been deleted.
non_primary_key_columns = [col.name for col in self.baseTable.t.columns if not col.primary_key]
for row in result:
if any([row[col] for col in non_primary_key_columns]):
rows.append(row)
return rows_to_dicts(rows)
def forInsert(self, insertedKeys, columns, changed_by, trans):
"""Inserts cause two rows in the History table to be created. The first
one records the primary key data and NULLs for other row data. This
represents that the row did not exist prior to the insert. The
timestamp for this row is 1 millisecond behind the real timestamp to
reflect this. The second row records the full data of the row at the
time of insert."""
primary_key_data = {}
for i in range(0, len(self.base_primary_key)):
name = self.base_primary_key[i]
primary_key_data[name] = insertedKeys[i]
# Make sure the primary keys are included in the second row as well
columns[name] = insertedKeys[i]
ts = getMillisecondTimestamp()
query, _ = self._insertStatement(changed_by=changed_by, timestamp=ts - 1, **primary_key_data)