-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_repack.py
More file actions
2166 lines (1949 loc) · 71.2 KB
/
test_repack.py
File metadata and controls
2166 lines (1949 loc) · 71.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
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 dataclasses
from textwrap import dedent
from unittest import mock
import pytest
from psycopack import (
BackfillBatch,
CompositePrimaryKey,
DeferrableUniqueConstraint,
FailureDueToLockTimeout,
InheritedTable,
InvalidIndexes,
InvalidPrimaryKeyTypeForConversion,
InvalidStageForReset,
NoCreateAndUsagePrivilegeOnSchema,
NoReferencesPrivilege,
NoReferringTableOwnership,
NotTableOwner,
PrimaryKeyNotFound,
Psycopack,
ReferringForeignKeyInDifferentSchema,
TableDoesNotExist,
TableHasTriggers,
TableIsEmpty,
UnsupportedPrimaryKey,
_const,
_cur,
_introspect,
_psycopg,
_tracker,
)
from tests import factories
@dataclasses.dataclass
class _TableInfo:
oid: int
indexes: list[_introspect.Index]
referring_fks: list[_introspect.ReferringForeignKey]
constraints: list[_introspect.Constraint]
pk_seq: str
pk_seq_val: int | None
def _collect_table_info(
table: str,
connection: _psycopg.Connection,
schema: str = "public",
) -> _TableInfo:
with _cur.get_cursor(connection, logged=True) as cur:
introspector = _introspect.Introspector(
conn=connection,
cur=cur,
schema=schema,
)
oid = introspector.get_table_oid(table=table)
assert oid is not None
indexes = introspector.get_index_def(table=table)
referring_fks = introspector.get_referring_fks(table=table)
constraints = introspector.get_constraints(
table=table, types=["c", "f", "n", "p", "u", "t", "x"]
)
pk_seq = introspector.get_pk_sequence_name(table=table)
if pk_seq:
pk_seq_val = introspector.get_pk_sequence_value(seq=pk_seq)
else:
pk_seq_val = None
return _TableInfo(
oid=oid,
indexes=indexes,
referring_fks=referring_fks,
constraints=constraints,
pk_seq=pk_seq,
pk_seq_val=pk_seq_val,
)
@dataclasses.dataclass
class _TriggerInfo:
trigger_exists: bool
repacked_trigger_exists: bool
def _get_trigger_info(repack: Psycopack, cur: _cur.Cursor) -> _TriggerInfo:
cur.execute(f"SELECT 1 FROM pg_trigger WHERE tgname = '{repack.trigger}'")
trigger_exists = cur.fetchone() is not None
cur.execute(f"SELECT 1 FROM pg_trigger WHERE tgname = '{repack.repacked_trigger}'")
repacked_trigger_exists = cur.fetchone() is not None
return _TriggerInfo(
trigger_exists=trigger_exists, repacked_trigger_exists=repacked_trigger_exists
)
@dataclasses.dataclass
class _FunctionInfo:
function_exists: bool
repacked_function_exists: bool
def _get_function_info(repack: Psycopack, cur: _cur.Cursor) -> _FunctionInfo:
cur.execute(f"SELECT 1 FROM pg_proc WHERE proname = '{repack.function}'")
function_exists = cur.fetchone() is not None
cur.execute(f"SELECT 1 FROM pg_proc WHERE proname = '{repack.repacked_function}'")
repacked_function_exists = cur.fetchone() is not None
return _FunctionInfo(
function_exists=function_exists,
repacked_function_exists=repacked_function_exists,
)
@dataclasses.dataclass
class _SequenceInfo:
sequence_exists: bool
def _get_sequence_info(repack: Psycopack, cur: _cur.Cursor) -> _SequenceInfo:
cur.execute(f"SELECT 1 FROM pg_sequences WHERE sequencename = '{repack.id_seq}'")
sequence_exists = cur.fetchone() is not None
return _SequenceInfo(sequence_exists=sequence_exists)
def _assert_repack(
table_before: _TableInfo,
table_after: _TableInfo,
repack: Psycopack,
cur: _cur.Cursor,
) -> None:
# They aren't the same tables (thus different oids), but everything else is
# the same.
assert table_before.oid != table_after.oid
assert table_before.indexes == table_after.indexes
assert table_before.referring_fks == table_after.referring_fks
assert table_before.constraints == table_after.constraints
assert table_before.pk_seq == table_after.pk_seq
if table_before.pk_seq_val is None or table_before.pk_seq_val > 0:
assert table_before.pk_seq_val == table_after.pk_seq_val
else:
assert table_after.pk_seq_val == 2**31
# All functions and triggers are removed.
trigger_info = _get_trigger_info(repack, cur)
assert trigger_info.trigger_exists is False
assert trigger_info.repacked_trigger_exists is False
function_info = _get_function_info(repack, cur)
assert function_info.function_exists is False
assert function_info.repacked_function_exists is False
# The tracker table itself will also be deleted after the clean up process.
assert repack.introspector.get_table_oid(table=repack.tracker.tracker_table) is None
# The row in the Registry will also be removed after the process is done.
cur.execute(
f"SELECT 1 FROM {repack.schema}.{_const.PSYCOPACK_REGISTRY} "
f"WHERE original_table = '{repack.table}';"
)
assert cur.fetchone() is None
def _assert_reset(repack: Psycopack, cur: _cur.Cursor) -> None:
assert _get_trigger_info(repack, cur).trigger_exists is False
assert _get_function_info(repack, cur).function_exists is False
assert _get_sequence_info(repack, cur).sequence_exists is False
assert repack.introspector.get_table_oid(table=repack.copy_table) is None
assert repack.introspector.get_table_oid(table=repack.tracker.tracker_table) is None
@pytest.mark.parametrize(
"pk_type",
("bigint", "bigserial", "integer", "serial", "smallint", "smallserial"),
)
def test_repack_full(connection: _psycopg.Connection, pk_type: str) -> None:
with _cur.get_cursor(connection, logged=True) as cur:
factories.create_table_for_repacking(
connection=connection,
cur=cur,
table_name="to_repack",
rows=100,
pk_type=pk_type,
)
table_before = _collect_table_info(table="to_repack", connection=connection)
repack = Psycopack(
table="to_repack",
batch_size=1,
conn=connection,
cur=cur,
)
repack.full()
table_after = _collect_table_info(table="to_repack", connection=connection)
_assert_repack(
table_before=table_before,
table_after=table_after,
repack=repack,
cur=cur,
)
@pytest.mark.parametrize(
"pk_type,identity_type,convert_pk_to_bigint,expected_seq_max_val",
(
("integer generated always as identity", "a", False, 2147483647),
("integer generated by default as identity", "d", False, 2147483647),
("integer generated always as identity", "a", True, 9223372036854775807),
("integer generated by default as identity", "d", True, 9223372036854775807),
),
)
def test_repack_full_with_identity_pk(
connection: _psycopg.Connection,
pk_type: str,
identity_type: str,
convert_pk_to_bigint: bool,
expected_seq_max_val: int,
) -> None:
with _cur.get_cursor(connection, logged=True) as cur:
factories.create_table_for_repacking(
connection=connection,
cur=cur,
table_name="to_repack",
rows=100,
pk_type=pk_type,
)
table_before = _collect_table_info(table="to_repack", connection=connection)
repack = Psycopack(
table="to_repack",
batch_size=1,
conn=connection,
cur=cur,
convert_pk_to_bigint=convert_pk_to_bigint,
)
repack.full()
table_after = _collect_table_info(table="to_repack", connection=connection)
_assert_repack(
table_before=table_before,
table_after=table_after,
repack=repack,
cur=cur,
)
pk_info = repack.introspector.get_primary_key_info(table="to_repack")
assert pk_info is not None
assert pk_info.identity_type == identity_type
cur.execute(
f"""
SELECT
1
FROM
pg_sequences
WHERE
sequencename = split_part(pg_get_serial_sequence('to_repack', 'id'), '.', 2)
AND max_value = {expected_seq_max_val};
"""
)
assert cur.fetchone()
def test_repack_full_with_identity_pk_with_psycopg_cursor(
connection: _psycopg.Connection,
) -> None:
pk_type = "integer generated by default as identity"
identity_type = "d"
with _cur.get_cursor(connection) as cur: # logged=False is the default
factories.create_table_for_repacking(
connection=connection,
cur=cur,
table_name="to_repack",
rows=100,
pk_type=pk_type,
)
table_before = _collect_table_info(table="to_repack", connection=connection)
repack = Psycopack(
table="to_repack",
batch_size=1,
conn=connection,
cur=cur,
)
repack.full()
table_after = _collect_table_info(table="to_repack", connection=connection)
_assert_repack(
table_before=table_before,
table_after=table_after,
repack=repack,
cur=cur,
)
pk_info = repack.introspector.get_primary_key_info(table="to_repack")
assert pk_info is not None
assert pk_info.identity_type == identity_type
def test_when_table_does_not_exist(connection: _psycopg.Connection) -> None:
with _cur.get_cursor(connection, logged=True) as cur:
with pytest.raises(TableDoesNotExist):
Psycopack(
table="to_repack",
batch_size=1,
conn=connection,
cur=cur,
).full()
def test_when_table_is_empty(connection: _psycopg.Connection) -> None:
with _cur.get_cursor(connection, logged=True) as cur:
cur.execute("CREATE TABLE empty_table (id SERIAL PRIMARY KEY);")
with pytest.raises(TableIsEmpty):
Psycopack(
table="empty_table",
batch_size=1,
conn=connection,
cur=cur,
).full()
def test_when_table_is_empty_with_allow_empty(
connection: _psycopg.Connection,
) -> None:
with _cur.get_cursor(connection, logged=True) as cur:
cur.execute("CREATE TABLE empty_table (id SERIAL PRIMARY KEY);")
# doesn't raise TableIsEmpty
Psycopack(
table="empty_table",
batch_size=1,
conn=connection,
cur=cur,
allow_empty=True,
).full()
def test_repack_full_after_pre_validate_called(connection: _psycopg.Connection) -> None:
"""
full() should be able to be called no matter where the repacking process
left out from.
In this case, it will just proceed from the pre_validation step.
"""
with _cur.get_cursor(connection, logged=True) as cur:
factories.create_table_for_repacking(
connection=connection,
cur=cur,
table_name="to_repack",
rows=100,
)
table_before = _collect_table_info(table="to_repack", connection=connection)
repack = Psycopack(
table="to_repack",
batch_size=1,
conn=connection,
cur=cur,
)
repack.pre_validate()
repack.full()
table_after = _collect_table_info(table="to_repack", connection=connection)
_assert_repack(
table_before=table_before,
table_after=table_after,
repack=repack,
cur=cur,
)
def test_repack_full_after_setup_called(connection: _psycopg.Connection) -> None:
"""
full() should be able to be called no matter where the repacking process
left out from.
In this case, it will remove the copy table, function, and trigger that
already exist due to the setup_repacking() method being called beforehand.
"""
with _cur.get_cursor(connection, logged=True) as cur:
factories.create_table_for_repacking(
connection=connection,
cur=cur,
table_name="to_repack",
rows=100,
)
table_before = _collect_table_info(table="to_repack", connection=connection)
repack = Psycopack(
table="to_repack",
batch_size=1,
conn=connection,
cur=cur,
)
repack.pre_validate()
repack.setup_repacking()
# Setup finished. Next stage is backfill.
assert repack.tracker.get_current_stage() == _tracker.Stage.BACKFILL
repack.full()
table_after = _collect_table_info(table="to_repack", connection=connection)
_assert_repack(
table_before=table_before,
table_after=table_after,
repack=repack,
cur=cur,
)
def test_repack_full_after_backfill(connection: _psycopg.Connection) -> None:
"""
full() should be able to be called no matter where the repacking process
left out from.
In this case, it will drop the backfill log table and all related tables
to repack and repack again from scratch.
"""
with _cur.get_cursor(connection, logged=True) as cur:
factories.create_table_for_repacking(
connection=connection,
cur=cur,
table_name="to_repack",
rows=100,
)
table_before = _collect_table_info(table="to_repack", connection=connection)
repack = Psycopack(
table="to_repack",
batch_size=1,
conn=connection,
cur=cur,
)
repack.pre_validate()
repack.setup_repacking()
repack.backfill()
# Backfill finished. Next stage is sync_schemas.
assert repack.tracker.get_current_stage() == _tracker.Stage.SYNC_SCHEMAS
repack.full()
table_after = _collect_table_info(table="to_repack", connection=connection)
_assert_repack(
table_before=table_before,
table_after=table_after,
repack=repack,
cur=cur,
)
def test_repack_full_after_sync_schemas_called(connection: _psycopg.Connection) -> None:
"""
full() should be able to be called no matter where the repacking process
left out from.
In this case, it will remove the foreign keys from referring tables that
were created by the setup_repacking() method.
"""
with _cur.get_cursor(connection, logged=True) as cur:
factories.create_table_for_repacking(
connection=connection,
cur=cur,
table_name="to_repack",
rows=100,
)
table_before = _collect_table_info(table="to_repack", connection=connection)
repack = Psycopack(
table="to_repack",
batch_size=1,
conn=connection,
cur=cur,
)
repack.pre_validate()
repack.setup_repacking()
repack.backfill()
repack.sync_schemas()
# Sync schemas finished. Next stage is swap.
assert repack.tracker.get_current_stage() == _tracker.Stage.SWAP
repack.full()
table_after = _collect_table_info(table="to_repack", connection=connection)
_assert_repack(
table_before=table_before,
table_after=table_after,
repack=repack,
cur=cur,
)
def test_repack_full_after_swap_called(connection: _psycopg.Connection) -> None:
"""
full() should be able to be called no matter where the repacking process
left out from.
In this case, it will pick up from the swap operation, which swaps the copy
table for the original and creates a new trigger to keep the original table
updated with new inserts into the copy.
"""
with _cur.get_cursor(connection, logged=True) as cur:
factories.create_table_for_repacking(
connection=connection,
cur=cur,
table_name="to_repack",
rows=100,
)
table_before = _collect_table_info(table="to_repack", connection=connection)
repack = Psycopack(
table="to_repack",
batch_size=1,
conn=connection,
cur=cur,
)
repack.pre_validate()
repack.setup_repacking()
repack.backfill()
repack.sync_schemas()
repack.swap()
# Swap finished. Next stage is clean up.
assert repack.tracker.get_current_stage() == _tracker.Stage.CLEAN_UP
repack.full()
table_after = _collect_table_info(table="to_repack", connection=connection)
_assert_repack(
table_before=table_before,
table_after=table_after,
repack=repack,
cur=cur,
)
def test_clean_up_finishes_the_repacking(connection: _psycopg.Connection) -> None:
"""
The last step on the full() method is to perform a clean_up(). That means
that the repacking should be finished up as soon as clean_up() returns.
"""
with _cur.get_cursor(connection, logged=True) as cur:
factories.create_table_for_repacking(
connection=connection,
cur=cur,
table_name="to_repack",
rows=100,
)
table_before = _collect_table_info(table="to_repack", connection=connection)
repack = Psycopack(
table="to_repack",
batch_size=1,
conn=connection,
cur=cur,
)
repack.pre_validate()
repack.setup_repacking()
repack.backfill()
repack.sync_schemas()
repack.swap()
repack.clean_up()
table_after = _collect_table_info(table="to_repack", connection=connection)
_assert_repack(
table_before=table_before,
table_after=table_after,
repack=repack,
cur=cur,
)
def test_sync_schemas_is_reentrant_and_idempotent(
connection: _psycopg.Connection,
) -> None:
with _cur.get_cursor(connection, logged=True) as cur:
factories.create_table_for_repacking(
connection=connection,
cur=cur,
table_name="to_repack",
rows=100,
)
table_before = _collect_table_info(table="to_repack", connection=connection)
repack = Psycopack(
table="to_repack",
batch_size=1,
conn=connection,
cur=cur,
)
repack.pre_validate()
repack.setup_repacking()
repack.backfill()
# Add an invalid index to verify it will be cleaned up.
cur.execute(
f"CREATE INDEX btree_idx_psycopack ON {repack.copy_table} (var_with_btree);"
)
cur.execute("""
UPDATE
pg_index
SET
indisvalid = false
WHERE
indexrelid = 'btree_idx_psycopack'::regclass;
""")
invalid_indexes = [
index
for index in repack.introspector.get_index_def(table=repack.copy_table)
if not index.is_valid
]
assert len(invalid_indexes) == 1
assert invalid_indexes[0].name == "btree_idx_psycopack"
with mock.patch.object(repack, "_create_unique_constraints") as mocked:
# An expection on _create_unique_constraints means that all indexes
# would've been created already. So the second run should pick up
# those indexes instead of recreating them.
mocked.side_effect = Exception("BANG")
with pytest.raises(Exception, match="BANG"):
repack.sync_schemas()
with mock.patch.object(repack, "_create_check_and_fk_constraints") as mocked:
# An expection on _create_check_and_fk_constraints means that all
# unique constraints would've been created already. So the second
# run should pick up those constraints instead of recreating them.
mocked.side_effect = Exception("BAANG")
with pytest.raises(Exception, match="BAANG"):
repack.sync_schemas()
with mock.patch.object(repack.command, "validate_constraint") as mocked:
# An exception on validate_constraint means that one of the check
# constraints wouldn't be validated and the process would fail
# right there. This would leave a NOT VALID constraint behind. This
# should be able to be fixed next time sync_schema() runs.
mocked.side_effect = Exception("BAAANG")
with pytest.raises(Exception, match="BAAANG"):
repack.sync_schemas()
with mock.patch.object(repack, "_create_referring_fks") as mocked:
# An expection on _create_referring_fks means that all check and fk
# constraints would've been created already. So the second run
# should pick up those constraints instead of recreating them.
mocked.side_effect = Exception("BAAAANG")
with pytest.raises(Exception, match="BAAAANG"):
repack.sync_schemas()
with mock.patch.object(repack.command, "validate_constraint") as mocked:
# An exception on validate_constraint means that one of the
# referring fks wouldn't be validated and the process would fail
# right there. This would leave a NOT VALID fk constraint behind.
# This should be able to be fixed next time sync_schema() runs.
mocked.side_effect = Exception("BAAAAANG")
with pytest.raises(Exception, match="BAAAAANG"):
repack.sync_schemas()
repack.sync_schemas()
repack.full()
table_after = _collect_table_info(table="to_repack", connection=connection)
_assert_repack(
table_before=table_before,
table_after=table_after,
repack=repack,
cur=cur,
)
# No invalid indexes left behind in the process.
assert not any(
[
index
for index in repack.introspector.get_index_def(table="to_repack")
if not index.is_valid
]
)
def test_when_tracker_removed_after_sync_schemas(
connection: _psycopg.Connection,
) -> None:
with _cur.get_cursor(connection, logged=True) as cur:
factories.create_table_for_repacking(
connection=connection,
cur=cur,
table_name="to_repack",
rows=100,
)
table_before = _collect_table_info(table="to_repack", connection=connection)
repack = Psycopack(
table="to_repack",
batch_size=1,
conn=connection,
cur=cur,
)
repack.pre_validate()
repack.setup_repacking()
repack.backfill()
repack.sync_schemas()
assert repack.tracker.get_current_stage() == _tracker.Stage.SWAP
# Deleting the tracker table will remove the ability to pick up the
# repacking process where it left. But nonetheless, it should resume
# happily from scratch.
repack.command.drop_table_if_exists(table=repack.tracker.tracker_table)
repack.full()
table_after = _collect_table_info(table="to_repack", connection=connection)
_assert_repack(
table_before=table_before,
table_after=table_after,
repack=repack,
cur=cur,
)
def test_when_tracker_table_current_row_is_deleted(
connection: _psycopg.Connection,
) -> None:
"""
A sane error must be returned and the repacking process must be stopped if
the tracker table has been manipulated.
In this case, the row containing the current stage has been deleted
manually.
"""
with _cur.get_cursor(connection, logged=True) as cur:
factories.create_table_for_repacking(
connection=connection,
cur=cur,
table_name="to_repack",
rows=100,
)
repack = Psycopack(
table="to_repack",
batch_size=1,
conn=connection,
cur=cur,
)
repack.pre_validate()
repack.setup_repacking()
assert repack.tracker.get_current_stage() == _tracker.Stage.BACKFILL
cur.execute(
f"DELETE FROM {repack.tracker.tracker_table} WHERE stage = 'BACKFILL';"
)
with pytest.raises(_tracker.CannotFindUnfinishedStage):
repack.full()
def test_when_rogue_row_inserted_in_tracker_table(
connection: _psycopg.Connection,
) -> None:
"""
A sane error must be returned and the repacking process must be stopped if
the tracker table has been manipulated.
In this case, a new row that shouldn't be there has been inserted into the
table manually.
"""
with _cur.get_cursor(connection, logged=True) as cur:
factories.create_table_for_repacking(
connection=connection,
cur=cur,
table_name="to_repack",
rows=100,
)
repack = Psycopack(
table="to_repack",
batch_size=1,
conn=connection,
cur=cur,
)
repack.pre_validate()
repack.setup_repacking()
assert repack.tracker.get_current_stage() == _tracker.Stage.BACKFILL
cur.execute(
_psycopg.sql.SQL(
"""
INSERT INTO
{table} (stage, step, started_at, finished_at)
VALUES
({stage}, {step}, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);
"""
)
.format(
table=_psycopg.sql.Identifier(repack.tracker.tracker_table),
stage=_psycopg.sql.Literal("A stage that doesn't exist"),
step=_psycopg.sql.Literal(42),
)
.as_string(connection)
)
with pytest.raises(_tracker.InvalidRowInTrackerTable):
repack.full()
def test_table_to_repack_deleted_after_pre_validation(
connection: _psycopg.Connection,
) -> None:
with _cur.get_cursor(connection, logged=True) as cur:
factories.create_table_for_repacking(
connection=connection,
cur=cur,
table_name="to_repack",
rows=100,
)
repack = Psycopack(
table="to_repack",
batch_size=1,
conn=connection,
cur=cur,
)
repack.pre_validate()
assert repack.tracker.get_current_stage() == _tracker.Stage.SETUP
cur.execute("DROP TABLE to_repack CASCADE;")
with pytest.raises(_tracker.TableDoesNotExist):
repack.full()
def test_trigger_deleted_after_setup(connection: _psycopg.Connection) -> None:
with _cur.get_cursor(connection, logged=True) as cur:
factories.create_table_for_repacking(
connection=connection,
cur=cur,
table_name="to_repack",
rows=100,
)
repack = Psycopack(
table="to_repack",
batch_size=1,
conn=connection,
cur=cur,
)
repack.pre_validate()
repack.setup_repacking()
assert repack.tracker.get_current_stage() == _tracker.Stage.BACKFILL
repack.command.drop_trigger_if_exists(
table=repack.table, trigger=repack.trigger
)
with pytest.raises(_tracker.TriggerDoesNotExist):
repack.full()
def test_cannot_repeat_finished_stage(connection: _psycopg.Connection) -> None:
with _cur.get_cursor(connection, logged=True) as cur:
factories.create_table_for_repacking(
connection=connection,
cur=cur,
table_name="to_repack",
rows=100,
)
table_before = _collect_table_info(table="to_repack", connection=connection)
repack = Psycopack(
table="to_repack",
batch_size=1,
conn=connection,
cur=cur,
)
repack.pre_validate()
with pytest.raises(_tracker.StageAlreadyFinished):
repack.pre_validate()
repack.setup_repacking()
with pytest.raises(_tracker.StageAlreadyFinished):
repack.setup_repacking()
repack.backfill()
with pytest.raises(_tracker.StageAlreadyFinished):
repack.backfill()
repack.sync_schemas()
with pytest.raises(_tracker.StageAlreadyFinished):
repack.sync_schemas()
repack.swap()
with pytest.raises(_tracker.StageAlreadyFinished):
repack.swap()
repack.clean_up()
with pytest.raises(_tracker.InvalidPsycopackSetup):
# The clean up process above already deleted all repacking
# relations, including the tracker table. So trying to call it
# again indicates trying to start repacking from scratch straight
# from the clean up stage, which is invalid.
repack.clean_up()
table_after = _collect_table_info(table="to_repack", connection=connection)
_assert_repack(
table_before=table_before,
table_after=table_after,
repack=repack,
cur=cur,
)
def test_cannot_skip_order_of_stages(connection: _psycopg.Connection) -> None:
with _cur.get_cursor(connection, logged=True) as cur:
factories.create_table_for_repacking(
connection=connection,
cur=cur,
table_name="to_repack",
rows=100,
)
table_before = _collect_table_info(table="to_repack", connection=connection)
repack = Psycopack(
table="to_repack",
batch_size=1,
conn=connection,
cur=cur,
)
with pytest.raises(_tracker.InvalidPsycopackSetup):
# Can't initialise a repacking without going through pre-validation
# first.
repack.setup_repacking()
repack.pre_validate()
with pytest.raises(_tracker.InvalidPsycopackStep):
# Can't go to backfill without setting up first.
repack.backfill()
repack.setup_repacking()
with pytest.raises(_tracker.InvalidPsycopackStep):
# Can't go to sync schemas without backfilling first
repack.sync_schemas()
repack.backfill()
with pytest.raises(_tracker.InvalidPsycopackStep):
# Can't go to swap without syncing schemas first.
repack.swap()
repack.sync_schemas()
with pytest.raises(_tracker.InvalidPsycopackStep):
# Can't go to clean up without swapping first.
repack.clean_up()
repack.swap()
repack.clean_up()
table_after = _collect_table_info(table="to_repack", connection=connection)
_assert_repack(
table_before=table_before,
table_after=table_after,
repack=repack,
cur=cur,
)
@pytest.mark.parametrize("ommit_sequence", (True, False))
def test_revert_swap_after_swap_called(
connection: _psycopg.Connection, ommit_sequence: bool
) -> None:
"""
The revert_swap() routine can only be called immediatelly after swap().
This routine should leave the repacking status exactly the same way it was
before swap() was called.
"""
with _cur.get_cursor(connection, logged=True) as cur:
factories.create_table_for_repacking(
connection=connection,
cur=cur,
table_name="to_repack",
rows=100,
pk_type="integer",
ommit_sequence=ommit_sequence,
)
table_before = _collect_table_info(table="to_repack", connection=connection)
repack = Psycopack(
table="to_repack",
batch_size=1,
conn=connection,
cur=cur,
)
repack.pre_validate()
repack.setup_repacking()
repack.backfill()
repack.sync_schemas()
repack.swap()
# After the swap, repacking is ready for the clean-up stage.
assert repack.tracker.get_current_stage() == _tracker.Stage.CLEAN_UP
table_after_swap = _collect_table_info(table="to_repack", connection=connection)
assert table_before.oid != table_after_swap.oid
repack.revert_swap()
table_after_revert = _collect_table_info(
table="to_repack", connection=connection
)
assert table_before.oid == table_after_revert.oid
# After the revert swap, repacking is ready for the swap stage.
assert repack.tracker.get_current_stage() == _tracker.Stage.SWAP
# We can run swap again now, without any errors.
repack.swap()
# Finally finish the repacking process.
repack.full()
table_after = _collect_table_info(table="to_repack", connection=connection)
_assert_repack(
table_before=table_before,
table_after=table_after,
repack=repack,
cur=cur,
)
def test_revert_swap_before_swap_called(connection: _psycopg.Connection) -> None:
"""
The revert_swap() routine can only be called immediatelly after swap().
This test tries to call revert_swap() _before_ swap() has been called,
which is wrong.
"""
with _cur.get_cursor(connection, logged=True) as cur:
factories.create_table_for_repacking(
connection=connection,
cur=cur,
table_name="to_repack",
rows=100,