forked from mozilla-releng/balrog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.py
2720 lines (2280 loc) · 134 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
from collections import defaultdict
from copy import copy
import itertools
from os import path
import pprint
import re
import simplejson as json
import sys
import time
from sqlalchemy import Table, Column, Integer, Text, String, MetaData, \
create_engine, select, BigInteger, Boolean, join
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.sql.expression import null
import sqlalchemy.types
import migrate.versioning.schema
import migrate.versioning.api
import dictdiffer
import dictdiffer.merge
from auslib.global_state import cache
from auslib.blobs.base import createBlob
from auslib.util.comparison import string_compare, version_compare, int_compare
from auslib.util.timestamp import getMillisecondTimestamp
import logging
def rowsToDicts(fn):
"""Decorator that converts the result of any function returning a dict-like
object to an actual dict. Eg, converts read-only row objects to writable
dicts."""
def convertRows(*args, **kwargs):
ret = []
for row in fn(*args, **kwargs):
d = {}
for key in row.keys():
d[key] = row[key]
ret.append(d)
return ret
return convertRows
class AlreadySetupError(Exception):
def __str__(self):
return "Can't connect to new database, still connected to previous one"
class PermissionDeniedError(Exception):
pass
class SignoffRequiredError(Exception):
"""Raised when someone attempts to directly modify an object that requires
signoff."""
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 ReadOnlyError(SQLAlchemyError):
"""Raised when a release marked as read-only is attempted to be changed."""
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
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
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
retrevial. 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):
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.iteritems():
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):
try:
# If something that executed in the context raised an Exception,
# rollback and re-raise it.
if exc[0]:
self.log.debug("exc is:", exc_info=True)
self.rollback()
raise exc[0], exc[1], exc[2]
# Also need to check for exceptions during commit!
try:
self.commit()
except:
self.rollback()
raise
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:
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.
klass, e, tb = sys.exc_info()
self.rollback()
e = TransactionError(e.args)
raise TransactionError, e, tb
def commit(self):
try:
self.trans.commit()
except:
klass, e, tb = sys.exc_info()
self.rollback()
e = TransactionError(e.args)
raise TransactionError, e, tb
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
@param onInsert: A callback that will be called whenever an insert is
made to the table. It must accept the following 4
parameters:
* The table object the query is being performed on
* The type of query being performed (eg: INSERT)
* The name of the user making the change
* The query object that will be execeuted
If the callback raises an exception the change will
be aborted.
@type onInsert: callable
@param onDelete: See onInsert
@type onDelete: callable
@param onUpdate: See onInsert
@type onUpdate: callable
"""
def __init__(self, db, dialect, history=True, versioned=True, scheduled_changes=False,
scheduled_changes_kwargs={}, onInsert=None, onUpdate=None, onDelete=None):
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
self.onInsert = onInsert
self.onUpdate = onUpdate
self.onDelete = onDelete
# Mirror the columns as attributes for easy access
self.primary_key = []
for col in self.table.get_children():
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 history:
self.history = History(db, dialect, self.t.metadata, self)
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:
query = select(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
@rowsToDicts
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.iteritems()]
query = self._selectStatement(where=where, **kwargs)
if transaction:
return transaction.execute(query).fetchall()
else:
with AUSTransaction(self.getEngine()) as trans:
return trans.execute(query).fetchall()
def _insertStatement(self, **columns):
"""Create an INSERT statement for this table
@param columns: Data to insert
@type colmuns: dict
@rtype: sqlalchemy.sql.express.Insert
"""
return self.t.insert(values=columns)
def _prepareInsert(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 = self._insertStatement(**data)
if self.onInsert:
self.onInsert(self, "INSERT", changed_by, query, trans)
ret = trans.execute(query)
if self.history:
for q in self.history.forInsert(ret.inserted_primary_key, data, changed_by):
trans.execute(q)
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)
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 _prepareDelete(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)
if self.onDelete:
self.onDelete(self, "DELETE", changed_by, query, trans)
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.history:
trans.execute(self.history.forDelete(row, changed_by))
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 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.iteritems()]
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)
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
"""
query = self.t.update(values=what)
if where:
for cond in where:
query = query.where(cond)
return query
def _prepareUpdate(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 = self._updateStatement(where, new_row)
if self.onUpdate:
self.onUpdate(self, "UPDATE", changed_by, query, trans)
ret = trans.execute(query)
if self.history:
trans.execute(self.history.forUpdate(new_row, changed_by))
if self.scheduled_changes:
self.scheduled_changes.mergeUpdate(orig_row, what, changed_by, trans)
if ret.rowcount != 1:
raise OutdatedDataError("Failed to update row, old_data_version doesn't match current data_version")
return ret
def update(self, where, what, changed_by=None, old_data_version=None, transaction=None, dryrun=False):
"""Perform an UPDATE statement on this stable. 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.iteritems()]
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)
def getRecentChanges(self, limit=10, transaction=None):
return self.history.select(transaction=transaction,
limit=limit,
order_by=self.history.timestamp.desc())
class History(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.get_children():
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, history=False, versioned=False)
def forInsert(self, insertedKeys, columns, changed_by):
"""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 = {}
queries = []
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()
queries.append(self._insertStatement(changed_by=changed_by, timestamp=ts - 1, **primary_key_data))
queries.append(self._insertStatement(changed_by=changed_by, timestamp=ts, **columns))
return queries
def forDelete(self, rowData, changed_by):
"""Deletes cause a single row to be created, which only contains the
primary key data. This represents that the row no longer exists."""
row = {}
for k in rowData:
row[str(k)] = rowData[k]
# Tack on history table information to the row
row['changed_by'] = changed_by
row['timestamp'] = getMillisecondTimestamp()
return self._insertStatement(**row)
def forUpdate(self, rowData, changed_by):
"""Updates cause a single row to be created, which contains the full,
new data of the row at the time of the update."""
row = {}
for k in rowData:
row[str(k)] = rowData[k]
row['changed_by'] = changed_by
row['timestamp'] = getMillisecondTimestamp()
return self._insertStatement(**row)
def getChange(self, change_id=None, column_values=None, data_version=None, transaction=None):
""" Returns the unique change that matches the give change_id or
combination of data_version and values for the specified columns.
column_values is a dict that contains the column names that are
versioned and their values.
Ignores non primary key attributes specified in column_values."""
# if change_id is not None, we use it to get the change, ignoring
# data_version and column_values
by_change_id = False if change_id is None else True
# column_names lists all primary keys as string keys with the column
# objects as values
column_names = {col.name: col for col in self.table.columns if col.name in self.base_primary_key}
if not by_change_id:
# we check if the entire primary key is present in column_values,
# since there might be multiple rows that match an incomplete
# primary key
for col in column_names.keys():
if col not in column_values.keys():
raise ValueError("Entire primary key not present")
# data_version can only be queried for versioned tables
if not self.baseTable.versioned:
raise ValueError("data_version queried for non-versioned table")
where = [self.data_version == data_version]
for col in column_names.keys():
where.append(column_names[col] == column_values[col])
changes = self.select(where=where,
transaction=transaction)
else:
changes = self.select(where=[self.change_id == change_id], transaction=transaction)
found = len(changes)
if found > 1 or found == 0:
self.log.debug("Found %s changes, should have been 1", found)
return None
return changes[0]
def getPrevChange(self, change_id, row_primary_keys, transaction=None):
""" Returns the most recent change to a given row in the base table """
where = [self.change_id < change_id]
for i in range(0, len(self.base_primary_key)):
self_prim = getattr(self, self.base_primary_key[i])
where.append((self_prim == row_primary_keys[i]))
changes = self.select(where=where, transaction=transaction, limit=1, order_by=self.change_id.desc())
length = len(changes)
if(length == 0):
self.log.debug("No previous changes found")
return None
return changes[0]
def _stripNullColumns(self, change):
# We know a bunch of columns are going to be empty...easier to strip them out
# than to be super verbose (also should let this test continue to work even
# if the schema changes).
for key in change.keys():
if change[key] is None:
del change[key]
return change
def _stripHistoryColumns(self, change):
""" Will strip history specific columns as well as data_version from the given change """
del change['change_id']
del change['changed_by']
del change['timestamp']
del change['data_version']
return change
def _isNull(self, change, row_primary_keys):
# Define a row that's empty except for the primary keys
# This is what the NULL rows for inserts and deletes will look like.
null_row = dict()
for i in range(0, len(self.base_primary_key)):
null_row[self.base_primary_key[i]] = row_primary_keys[i]
return self._stripNullColumns(change) == null_row
def _isDelete(self, cur_base_state, row_primary_keys):
return self._isNull(cur_base_state.copy(), row_primary_keys)
def _isInsert(self, prev_base_state, row_primary_keys):
return self._isNull(prev_base_state.copy(), row_primary_keys)
def _isUpdate(self, cur_base_state, prev_base_state, row_primary_keys):
return (not self._isNull(cur_base_state.copy(), row_primary_keys)) and (not self._isNull(prev_base_state.copy(), row_primary_keys))
def rollbackChange(self, change_id, changed_by, transaction=None):
""" Rollback the change given by the change_id,
Will handle all cases: insert, delete, update """
change = self.getChange(change_id=change_id, transaction=transaction)
# Get the values of the primary keys for the given row
row_primary_keys = [0] * len(self.base_primary_key)
for i in range(0, len(self.base_primary_key)):
row_primary_keys[i] = change[self.base_primary_key[i]]
# Strip the History Specific Columns from the cahgnes
prev_base_state = self._stripHistoryColumns(self.getPrevChange(change_id, row_primary_keys, transaction))
cur_base_state = self._stripHistoryColumns(change.copy())
# Define a row that's empty except for the primary keys
# This is what the NULL rows for inserts and deletes will look like.
null_row = dict()
for i in range(0, len(self.base_primary_key)):
null_row[self.base_primary_key[i]] = row_primary_keys[i]
# If the row has all NULLS, then the operation we're rolling back is a DELETE
# We need to do an insert, with the data from the previous change
if self._isDelete(cur_base_state, row_primary_keys):
self.log.debug("reverting a DELETE")
self.baseTable.insert(changed_by=changed_by, transaction=transaction, **prev_base_state)
# If the previous change is NULL, then the operation is an INSERT
# We will need to do a delete.
elif self._isInsert(prev_base_state, row_primary_keys):
self.log.debug("reverting an INSERT")
where = []
for i in range(0, len(self.base_primary_key)):
self_prim = getattr(self.baseTable, self.base_primary_key[i])
where.append((self_prim == row_primary_keys[i]))
self.baseTable.delete(changed_by=changed_by, transaction=transaction, where=where, old_data_version=change['data_version'])
elif self._isUpdate(cur_base_state, prev_base_state, row_primary_keys):
# If this operation is an UPDATE
# We will need to do an update to the previous change's state
self.log.debug("reverting an UPDATE")
where = []
for i in range(0, len(self.base_primary_key)):
self_prim = getattr(self.baseTable, self.base_primary_key[i])
where.append((self_prim == row_primary_keys[i]))
what = prev_base_state
old_data_version = change['data_version']
self.baseTable.update(changed_by=changed_by, where=where, what=what, old_data_version=old_data_version, transaction=transaction)
else:
self.log.debug("ERROR, change doesn't correspond to any known operation")
class ConditionsTable(AUSTable):
# Scheduled changes may only have a single type of condition, but some
# conditions require mulitple arguments. This data structure defines
# each type of condition, and groups their args together for easier
# processing.
condition_groups = {
"time": ("when",),
"uptake": ("telemetry_product", "telemetry_channel", "telemetry_uptake"),
}
def __init__(self, db, dialect, metadata, baseName, conditions, history=True):
if not conditions:
raise ValueError("No conditions enabled, cannot initialize conditions for for {}".format(baseName))
if set(conditions) - set(self.condition_groups):
raise ValueError("Unknown conditions in: {}".format(conditions))
self.enabled_condition_groups = {k: v for k, v in self.condition_groups.iteritems() if k in conditions}
self.table = Table("{}_conditions".format(baseName), metadata,
Column("sc_id", Integer, primary_key=True),
)
if "uptake" in conditions:
self.table.append_column(Column("telemetry_product", String(15)))
self.table.append_column(Column("telemetry_channel", String(75)))
self.table.append_column(Column("telemetry_uptake", Integer))
if "time" in conditions:
if dialect == "sqlite":
self.table.append_column(Column("when", Integer))
else:
self.table.append_column(Column("when", BigInteger))
super(ConditionsTable, self).__init__(db, dialect, history=history, versioned=True)
def validate(self, conditions):
conditions = {k: v for k, v in conditions.iteritems() if conditions[k]}
if not conditions:
raise ValueError("No conditions found")
for c in conditions:
for condition, args in self.condition_groups.iteritems():
if c in args:
if c in itertools.chain(*self.enabled_condition_groups.values()):
break
else:
raise ValueError("{} condition is disabled".format(condition))
else:
raise ValueError("Invalid condition: %s", c)
for group in self.enabled_condition_groups.values():
if set(group) == set(conditions.keys()):
break
else:
raise ValueError("Invalid combination of conditions: {}".format(conditions.keys()))
if "when" in conditions:
try:
time.gmtime(conditions["when"] / 1000)
except:
raise ValueError("Cannot parse 'when' as a unix timestamp.")
if conditions["when"] < getMillisecondTimestamp():
raise ValueError("Cannot schedule changes in the past")
class ScheduledChangeTable(AUSTable):
"""A Table that stores the necessary information to schedule changes
to the baseTable provided. A ScheduledChangeTable ends up mirroring the
columns of its base, and adding the necessary ones to provide the schedule.
By default, ScheduledChangeTables enable History on themselves."""
def __init__(self, db, dialect, metadata, baseTable, conditions=("time", "uptake"), history=True):
table_name = "{}_scheduled_changes".format(baseTable.t.name)
self.baseTable = baseTable
self.table = Table(table_name, metadata,
Column("sc_id", Integer, primary_key=True, autoincrement=True),
Column("scheduled_by", String(100), nullable=False),
Column("complete", Boolean, default=False),
Column("change_type", String(50), nullable=False),
)
self.conditions = ConditionsTable(db, dialect, metadata, table_name, conditions, history=history)
# Signoffs are configurable at runtime, which means that we always need
# a Signoffs table, even if it may not be used immediately.
self.signoffs = SignoffsTable(db, metadata, dialect, table_name)
# The primary key column(s) are used in construct "where" clauses for
# existing rows.
self.base_primary_key = []
# A ScheduledChangesTable requires all of the columns from its base
# table, with a few tweaks:
for col in baseTable.t.get_children():
if col.primary_key:
self.base_primary_key.append(col.name)
newcol = col.copy()
# 1) Columns are prefixed with "base_", to make them easy to
# identify and avoid conflicts.
# Renaming a column requires to change both the key and the name
# See https://github.com/zzzeek/sqlalchemy/blob/rel_0_7/lib/sqlalchemy/schema.py#L781
# for background.
newcol.key = newcol.name = "base_%s" % col.name
# 2) Primary Key Integer Autoincrement columns from the baseTable become normal nullable
# columns in ScheduledChanges because we can schedule changes that insert into baseTable
# and the DB will handle inserting the correct value. However, nulls aren't allowed when
# we schedule updates or deletes -this is enforced in self.validate().
# For Primary Key columns that aren't Integer or Autoincrement but are nullable, we preserve
# this non-nullability because we need a value to insert into the baseTable when the
# scheduled change gets executed.
# Non-Primary Key columns from the baseTable become nullable and non-unique in ScheduledChanges
# because they aren't part of the ScheduledChanges business logic and become simple data storage.
if col.primary_key:
newcol.primary_key = False
# Only integer columns can be AUTOINCREMENT. The isinstance statement guards
# against false positives from SQLAlchemy.
if col.autoincrement and isinstance(col.type, Integer):
newcol.nullable = True
else:
newcol.unique = None
newcol.nullable = True
self.table.append_column(newcol)
super(ScheduledChangeTable, self).__init__(db, dialect, history=history, versioned=True)
def _prefixColumns(self, columns):
"""Helper function which takes key/value pairs of columns for this
scheduled changes table - which could contain some unprefixed base
table columns - and returns key/values pairs of the same columns
with the base table ones prefixed."""
ret = {}
base_columns = [c.name for c in self.baseTable.t.get_children()]
for k, v in columns.iteritems():
if k in base_columns:
ret["base_%s" % k] = v
else:
ret[k] = v