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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
|
%global _empty_manifest_terminate_build 0
Name: python-django-pg-zero-downtime-migrations
Version: 0.12
Release: 1
Summary: Django postgresql backend that apply migrations with respect to database locks
License: MIT
URL: https://github.com/tbicr/django-pg-zero-downtime-migrations
Source0: https://mirrors.nju.edu.cn/pypi/web/packages/81/2b/b12086f9cf57c77f4d5a644e1ac18750af69d9c0fd6365b6e96bf25b9142/django-pg-zero-downtime-migrations-0.12.tar.gz
BuildArch: noarch
Requires: python3-django
%description
[](https://pypi.org/project/django-pg-zero-downtime-migrations/)



[](https://raw.githubusercontent.com/tbicr/django-pg-zero-downtime-migrations/master/LICENSE)
[](https://pypistats.org/packages/django-pg-zero-downtime-migrations)
[](https://github.com/tbicr/django-pg-zero-downtime-migrations/commits/master)
[](https://github.com/tbicr/django-pg-zero-downtime-migrations/actions)
# django-pg-zero-downtime-migrations
Django postgresql backend that apply migrations with respect to database locks.
## Installation
pip install django-pg-zero-downtime-migrations
## Usage
To enable zero downtime migrations for postgres just setup django backend provided by this package and add most safe settings:
DATABASES = {
'default': {
'ENGINE': 'django_zero_downtime_migrations.backends.postgres',
#'ENGINE': 'django_zero_downtime_migrations.backends.postgis',
...
}
}
ZERO_DOWNTIME_MIGRATIONS_LOCK_TIMEOUT = '2s'
ZERO_DOWNTIME_MIGRATIONS_STATEMENT_TIMEOUT = '2s'
ZERO_DOWNTIME_MIGRATIONS_FLEXIBLE_STATEMENT_TIMEOUT = True
ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE = True
ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL = False
> _NOTE:_ this backend brings zero downtime improvements only for migrations (schema and `RunSQL` operations, but not for `RunPython` operation), for other purpose it works the same as standard django backend.
> _NOTE:_ this package is in beta, please check your migrations SQL before applying on production and submit issue for any question.
### Differences with standard django backend
This backend provides same result state (except `NOT NULL` constraint replacement for old postgres versions if appropriate option configured), but different way and with additional guarantees for avoiding stuck table locks.
This backend doesn't use transactions for migrations (except `RunPython` operation), because not all SQL fixes can be run in transaction and it allows to avoid deadlocks for complex migration. So when your migration will down in middle of transaction you need fix it manually (instead potential downtime). For that reason good practice to make migration modules small as possible.
### Deployment flow
There are requirements for zero downtime deployment:
1. We have one database;
1. We have several instances with application - application always should be available, even you restart one of instances;
1. We have balancer before instances;
1. Our application works fine before, on and after migration - old application works fine with old and new database schema version;
1. Our application works fine before, on and after instance updating - old and new application versions work fine with new database schema version.

Flow:
1. apply migrations
1. disconnect instance form balancer, restart it and back to balancer - repeat this operation one by one for all instances
If our deployment don't satisfy zero downtime deployment rules, then we split it to smaller deployments.

### Settings
#### ZERO_DOWNTIME_MIGRATIONS_LOCK_TIMEOUT
Apply [`lock_timeout`](https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-LOCK-TIMEOUT) for SQL statements that require `ACCESS EXCLUSIVE` lock, default `None`:
ZERO_DOWNTIME_MIGRATIONS_LOCK_TIMEOUT = '2s'
Allowed values:
- `None` - current postgres setting used
- other - timeout will be applied, `0` and equivalents mean that timeout will be disabled
#### ZERO_DOWNTIME_MIGRATIONS_STATEMENT_TIMEOUT
Apply [`statement_timeout`](https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-STATEMENT-TIMEOUT) for SQL statements that require `ACCESS EXCLUSIVE` lock, default `None`:
ZERO_DOWNTIME_MIGRATIONS_STATEMENT_TIMEOUT = '2s'
Allowed values:
- `None` - current postgres setting used
- other - timeout will be applied, `0` and equivalents mean that timeout will be disabled
#### ZERO_DOWNTIME_MIGRATIONS_FLEXIBLE_STATEMENT_TIMEOUT
Set [`statement_timeout`](https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-STATEMENT-TIMEOUT) to `0ms` for SQL statements that require `SHARE UPDATE EXCLUSIVE` lock that useful in case when `statement_timeout` enabled globally and you try run long-running operations like index creation or constraint validation, default `False`:
ZERO_DOWNTIME_MIGRATIONS_FLEXIBLE_STATEMENT_TIMEOUT = True
#### ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE
Enabled option doesn't allow run potential unsafe migration, default `False`:
ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE = True
#### ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL
Set policy for avoiding `NOT NULL` constraint creation long lock, default `None`:
ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL = 10 ** 7
Allowed values:
- `None` - standard django's behaviour (raise for `ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE = True`)
- `True` - always replace `NOT NULL` constraint with `CHECK (field IS NOT NULL)` (don't raise for `ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE = True`)
- `False` - always use `NOT NULL` constraint (don't raise for `ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE = True`)
- `int` value - use `CHECK (field IS NOT NULL)` instead `NOT NULL` constraint if table has more than `value` rows (approximate rows count used) otherwise use `NOT NULL` constraint (don't raise for `ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE = True`)
- `USE_PG_ATTRIBUTE_UPDATE_FOR_SUPERUSER` - use `pg_catalog.pg_attribute` update to mark column `NOT NULL` and provide same state as default django backend (don't raise for `ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE = True`).
> _NOTE:_ For postgres 12 and newest `NOT NULL` constraint creation has migration replacement that provide same state as default django backend, so this option deprecated and doesn't used this postgres version. If you use `CHECK NOT NULL` compatible constraint before you can migrate it to `NOT NULL` constraints with `manage.py migrate_isnotnull_check_constraints` management command (add `INSTALLED_APPS += ['django_zero_downtime_migrations']` to `settings.py` to use management command).
## How it works
### Postgres table level locks
Postgres has different locks on table level that can conflict with each other https://www.postgresql.org/docs/current/static/explicit-locking.html#LOCKING-TABLES:
| | `ACCESS SHARE` | `ROW SHARE` | `ROW EXCLUSIVE` | `SHARE UPDATE EXCLUSIVE` | `SHARE` | `SHARE ROW EXCLUSIVE` | `EXCLUSIVE` | `ACCESS EXCLUSIVE` |
| ------------------------ | :------------: | :---------: | :-------------: | :----------------------: | :-----: | :-------------------: | :---------: | :----------------: |
| `ACCESS SHARE` | | | | | | | | X |
| `ROW SHARE` | | | | | | | X | X |
| `ROW EXCLUSIVE` | | | | | X | X | X | X |
| `SHARE UPDATE EXCLUSIVE` | | | | X | X | X | X | X |
| `SHARE` | | | X | X | | X | X | X |
| `SHARE ROW EXCLUSIVE` | | | X | X | X | X | X | X |
| `EXCLUSIVE` | | X | X | X | X | X | X | X |
| `ACCESS EXCLUSIVE` | X | X | X | X | X | X | X | X |
### Migration and business logic locks
Lets split this lock to migration and business logic operations.
- Migration operations work synchronously in one thread and cover schema migrations (data migrations conflict with business logic operations same as business logic conflict concurrently).
- Business logic operations work concurrently.
#### Migration locks
| lock | operations |
| ------------------------ | ----------------------------------------------------------------------------------------------------- |
| `ACCESS EXCLUSIVE` | `CREATE SEQUENCE`, `DROP SEQUENCE`, `CREATE TABLE`, `DROP TABLE` \*, `ALTER TABLE` \*\*, `DROP INDEX` |
| `SHARE` | `CREATE INDEX` |
| `SHARE UPDATE EXCLUSIVE` | `CREATE INDEX CONCURRENTLY`, `DROP INDEX CONCURRENTLY`, `ALTER TABLE VALIDATE CONSTRAINT` \*\*\* |
\*: `CREATE SEQUENCE`, `DROP SEQUENCE`, `CREATE TABLE`, `DROP TABLE` shouldn't have conflicts, because your business logic shouldn't yet operate with created tables and shouldn't already operate with deleted tables.
\*\*: Not all `ALTER TABLE` operations take `ACCESS EXCLUSIVE` lock, but all current django's migrations take it https://github.com/django/django/blob/master/django/db/backends/base/schema.py, https://github.com/django/django/blob/master/django/db/backends/postgresql/schema.py and https://www.postgresql.org/docs/current/static/sql-altertable.html.
\*\*\*: Django doesn't have `VALIDATE CONSTRAINT` logic, but we will use it for some cases.
#### Business logic locks
| lock | operations | conflict with lock | conflict with operations |
| --------------- | ---------------------------- | --------------------------------------------------------------- | ------------------------------------------- |
| `ACCESS SHARE` | `SELECT` | `ACCESS EXCLUSIVE` | `ALTER TABLE`, `DROP INDEX` |
| `ROW SHARE` | `SELECT FOR UPDATE` | `ACCESS EXCLUSIVE`, `EXCLUSIVE` | `ALTER TABLE`, `DROP INDEX` |
| `ROW EXCLUSIVE` | `INSERT`, `UPDATE`, `DELETE` | `ACCESS EXCLUSIVE`, `EXCLUSIVE`, `SHARE ROW EXCLUSIVE`, `SHARE` | `ALTER TABLE`, `DROP INDEX`, `CREATE INDEX` |
So you can find that all django schema changes for exist table conflicts with business logic, but fortunately they are safe or has safe alternative in general.
### Postgres row level locks
As business logic mostly works with table rows it's also important to understand lock conflicts on row level https://www.postgresql.org/docs/current/static/explicit-locking.html#LOCKING-ROWS:
| lock | `FOR KEY SHARE` | `FOR SHARE` | `FOR NO KEY UPDATE` | `FOR UPDATE` |
| ------------------- | :-------------: | :---------: | :-----------------: | :----------: |
| `FOR KEY SHARE` | | | | X |
| `FOR SHARE` | | | X | X |
| `FOR NO KEY UPDATE` | | X | X | X |
| `FOR UPDATE` | X | X | X | X |
Main point there is if you have two transactions that update one row, then second transaction will wait until first will be completed. So for business logic and data migrations better to avoid updates for whole table and use batch operations instead.
> _NOTE:_ batch operations also can work faster because postgres can use more optimal execution plan with indexes for small data range.
### Transactions FIFO waiting

Found same diagram in interesting article http://pankrat.github.io/2015/django-migrations-without-downtimes/.
In this diagram we can extract several metrics:
1. operation time - time spent changing schema, in the case of long running operations on many rows tables like `CREATE INDEX` or `ALTER TABLE ADD COLUMN SET DEFAULT`, so you need a safe equivalent.
2. waiting time - your migration will wait until all transactions complete, so there is issue for long running operations/transactions like analytic, so you need avoid it or disable during migration.
3. queries per second + execution time and connections pool - if executing many queries, especially long running ones, they can consume all available database connections until the lock is released, so you need different optimizations there: run migrations when least busy, decrease query count and execution time, split data.
4. too many operations in one transaction - you have issues in all previous points for one operation so if you have many operations in one transaction then you have more likelihood to get this issue, so you need avoid too many simultaneous operations in a single transaction (or even not run it in a transaction at all but being careful when an operation fails).
### Dealing with timeouts
Postgres has two settings to dealing with `waiting time` and `operation time` presented in diagram: `lock_timeout` and `statement_timeout`.
`SET lock_timeout TO '2s'` allow you to avoid downtime when you have long running query/transaction before run migration (https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-LOCK-TIMEOUT).
`SET statement_timeout TO '2s'` allow you to avoid downtime when you have long running migration query (https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-STATEMENT-TIMEOUT).
### Deadlocks
There no downtime issues for deadlocks, but too many operations in one transaction can take most conflicted lock and release it only after transaction commit or rollback. So it's a good idea to avoid `ACCESS EXCLUSIVE` lock operations and long time operations in one transaction. Deadlocks also can make you migration stuck on production deployment when different tables will be locked, for example, for FOREIGN KEY that take `ACCESS EXCLUSIVE` lock for two tables.
### Rows and values storing
Postgres store values of different types different ways. If you try to convert one type to another and it stored different way then postgres will rewrite all values. Fortunately some types stored same way and postgres need to do nothing to change type, but in some cases postgres need to check that all values have same with new type limitations, for example string length.
### Multiversion Concurrency Control
Regarding documentation https://www.postgresql.org/docs/current/static/mvcc-intro.html data consistency in postgres is maintained by using a multiversion model. This means that each SQL statement sees a snapshot of data. It has advantage for adding and deleting columns without any indexes, constrains and defaults do not change exist data, new version of data will be created on `INSERT` and `UPDATE`, delete just mark you record expired. All garbage will be collected later by `VACUUM` or `AUTO VACUUM`.
### Django migrations hacks
Any schema changes can be processed with creation of new table and copy data to it, but it can take significant time.
| # | name | safe | safe alternative | description |
| --: | --------------------------------------------- | :--: | :---------------------------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 1 | `CREATE SEQUENCE` | X | | safe operation, because your business logic shouldn't operate with new sequence on migration time \* |
| 2 | `DROP SEQUENCE` | X | | safe operation, because your business logic shouldn't operate with this sequence on migration time \* |
| 3 | `CREATE TABLE` | X | | safe operation, because your business logic shouldn't operate with new table on migration time \* |
| 4 | `DROP TABLE` | X | | safe operation, because your business logic shouldn't operate with this table on migration time \* |
| 5 | `ALTER TABLE RENAME TO` | | add new table and copy data | **unsafe operation**, it's too hard write business logic that operate with two tables simultaneously, so propose `CREATE TABLE` and then copy all data to new table \* |
| 6 | `ALTER TABLE SET TABLESPACE` | | add new table and copy data | **unsafe operation**, but probably you don't need it at all or often \* |
| 7 | `ALTER TABLE ADD COLUMN` | X | | safe operation if without `SET NOT NULL`, `SET DEFAULT`, `PRIMARY KEY`, `UNIQUE` \* |
| 8 | `ALTER TABLE ADD COLUMN SET DEFAULT` | | add column and set default | **unsafe operation**, because you spend time in migration to populate all values in table, so propose `ALTER TABLE ADD COLUMN` and then populate column and then `SET DEFAULT` \* |
| 9 | `ALTER TABLE ADD COLUMN SET NOT NULL` | | +/- | **unsafe operation**, because doesn't work without `SET DEFAULT` or after migration old code can insert rows without new column and raise exception, so propose `ALTER TABLE ADD COLUMN` and then populate column and then `ALTER TABLE ALTER COLUMN SET NOT NULL` \* and \*\* |
| 10 | `ALTER TABLE ADD COLUMN PRIMARY KEY` | | add index and add constraint | **unsafe operation**, because you spend time in migration to `CREATE INDEX`, so propose `ALTER TABLE ADD COLUMN` and then `CREATE INDEX CONCURRENTLY` and then `ALTER TABLE ADD CONSTRAINT PRIMARY KEY USING INDEX` \*\*\* |
| 11 | `ALTER TABLE ADD COLUMN UNIQUE` | | add index and add constraint | **unsafe operation**, because you spend time in migration to `CREATE INDEX`, so propose `ALTER TABLE ADD COLUMN` and then `CREATE INDEX CONCURRENTLY` and then `ALTER TABLE ADD CONSTRAINT UNIQUE USING INDEX` \*\*\* |
| 12 | `ALTER TABLE ALTER COLUMN TYPE` | | +/- | **unsafe operation**, because you spend time in migration to check that all items in column valid or to change type, but some operations can be safe \*\*\*\* |
| 13 | `ALTER TABLE ALTER COLUMN SET NOT NULL` | | +/- | **unsafe operation**, because you spend time in migration to check that all items in column `NOT NULL` \*\* |
| 14 | `ALTER TABLE ALTER COLUMN DROP NOT NULL` | X | | safe operation |
| 15 | `ALTER TABLE ALTER COLUMN SET DEFAULT` | X | | safe operation |
| 16 | `ALTER TABLE ALTER COLUMN DROP DEFAULT` | X | | safe operation |
| 17 | `ALTER TABLE DROP COLUMN` | X | | safe operation, because your business logic shouldn't operate with this column on migration time, however better `ALTER TABLE ALTER COLUMN DROP NOT NULL`, `ALTER TABLE DROP CONSTRAINT` and `DROP INDEX` before \* and \*\*\*\*\* |
| 18 | `ALTER TABLE RENAME COLUMN` | | add new column and copy data | **unsafe operation**, it's too hard write business logic that operate with two columns simultaneously, so propose `ALTER TABLE CREATE COLUMN` and then copy all data to new column \* |
| 19 | `ALTER TABLE ADD CONSTRAINT CHECK` | | add as not valid and validate | **unsafe operation**, because you spend time in migration to check constraint |
| 20 | `ALTER TABLE DROP CONSTRAINT` (`CHECK`) | X | | safe operation |
| 21 | `ALTER TABLE ADD CONSTRAINT FOREIGN KEY` | | add as not valid and validate | **unsafe operation**, because you spend time in migration to check constraint, lock two tables |
| 22 | `ALTER TABLE DROP CONSTRAINT` (`FOREIGN KEY`) | X | | safe operation, lock two tables |
| 23 | `ALTER TABLE ADD CONSTRAINT PRIMARY KEY` | | add index and add constraint | **unsafe operation**, because you spend time in migration to create index \*\*\* |
| 24 | `ALTER TABLE DROP CONSTRAINT` (`PRIMARY KEY`) | X | | safe operation \*\*\* |
| 25 | `ALTER TABLE ADD CONSTRAINT UNIQUE` | | add index and add constraint | **unsafe operation**, because you spend time in migration to create index \*\*\* |
| 26 | `ALTER TABLE DROP CONSTRAINT` (`UNIQUE`) | X | | safe operation \*\*\* |
| 27 | `ALTER TABLE ADD CONSTRAINT EXCLUDE` | | add new table and copy data |
| 28 | `ALTER TABLE DROP CONSTRAINT (EXCLUDE)` | X | |
| 29 | `CREATE INDEX` | | `CREATE INDEX CONCURRENTLY` | **unsafe operation**, because you spend time in migration to create index |
| 30 | `DROP INDEX` | X | `DROP INDEX CONCURRENTLY` | safe operation \*\*\* |
| 31 | `CREATE INDEX CONCURRENTLY` | X | | safe operation |
| 32 | `DROP INDEX CONCURRENTLY` | X | | safe operation \*\*\* |
\*: main point with migration on production without downtime that your code should correctly work before and after migration, lets look this point closely in [Dealing with logic that should work before and after migration](#dealing-with-logic-that-should-work-before-and-after-migration) section.
\*\*: postgres will check that all items in column `NOT NULL` that take time, lets look this point closely in [Dealing with `NOT NULL` constraint](#dealing-with-not-null-constraint) section.
\*\*\*: postgres will have same behaviour when you skip `ALTER TABLE ADD CONSTRAINT UNIQUE USING INDEX` and still unclear difference with `CONCURRENTLY` except difference in locks, lets look this point closely in [Dealing with `UNIQUE` constraint](#dealing-with-unique-constraint).
\*\*\*\*: lets look this point closely in [Dealing with `ALTER TABLE ALTER COLUMN TYPE`](#dealing-with-alter-table-alter-column-type) section.
\*\*\*\*\*: if you check migration on CI with `python manage.py makemigrations --check` you can't drop column in code without migration creation, so in this case you can be useful _back migration flow_: apply code on all instances and then migrate database
#### Dealing with logic that should work before and after migration
##### Adding and removing models and columns
Migrations: `CREATE SEQUENCE`, `DROP SEQUENCE`, `CREATE TABLE`, `DROP TABLE`, `ALTER TABLE ADD COLUMN`, `ALTER TABLE DROP COLUMN`.
This migrations are pretty safe, because your logic doesn't work with this data before migration
##### Changes for working logic
Migrations: `ALTER TABLE RENAME TO`, `ALTER TABLE SET TABLESPACE`, `ALTER TABLE RENAME COLUMN`, `ALTER TABLE ADD CONSTRAINT EXCLUDE`.
For this migration too hard implement logic that will work correctly for all instances, so there are two ways to dealing with it:
1. create new table/column, copy exist data, drop old table/column
2. downtime
##### Create column with default
Migrations: `ALTER TABLE ADD COLUMN SET DEFAULT`.
Standard django's behaviour for creation column with default is populate all values with default. Django don't use database defaults permanently, so when you add new column with default django will create column with default and drop this default at once, eg. new default will come from django code. In this case you can have a gap when migration applied by not all instances has updated and at this moment new rows in table will be without default and probably you need update nullable values after that. So to avoid this case best way is avoid creation column with default and split column creation (with default for new rows) and data population to two migrations (with deployments).
#### Dealing with `NOT NULL` constraint
Postgres check that all column items `NOT NULL` when you applying `NOT NULL` constraint, for postgres 12 and newest it doesn't make this check if appropriate `CHECK CONSTRAINT` exists, but for older versions you can't defer this check as for `NOT VALID`. Fortunately we have some hacks and alternatives there for old postgres versions.
1. Run migrations when load minimal to avoid negative affect of locking.
2. `SET statement_timeout` and try to set `NOT NULL` constraint for small tables.
3. Use `CHECK (column IS NOT NULL)` constraint instead that support `NOT VALID` option with next `VALIDATE CONSTRAINT`, see article for details https://medium.com/doctolib-engineering/adding-a-not-null-constraint-on-pg-faster-with-minimal-locking-38b2c00c4d1c. There are additionally can be applied `NOT NULL` constraint via direct `pg_catalog.pg_attribute` `attnotnull` update, but it require superuser permissions.
#### Dealing with `UNIQUE` constraint
Postgres has two approaches for uniqueness: `CREATE UNIQUE INDEX` and `ALTER TABLE ADD CONSTRAINT UNIQUE` - both use unique index inside. Difference that we can find that we cannot apply `DROP INDEX CONCURRENTLY` for constraint. However it still unclear what difference for `DROP INDEX` and `DROP INDEX CONCURRENTLY` except difference in locks, but as we seen before both marked as safe - we don't spend time in `DROP INDEX`, just wait for lock. So as django use constraint for uniqueness we also have a hacks to use constraint safely.
#### Dealing with `ALTER TABLE ALTER COLUMN TYPE`
Next operations are safe:
1. `varchar(LESS)` to `varchar(MORE)` where LESS < MORE
2. `varchar(ANY)` to `text`
3. `numeric(LESS, SAME)` to `numeric(MORE, SAME)` where LESS < MORE and SAME == SAME
For other operations propose to create new column and copy data to it. Eg. some types can be also safe, but you should check yourself.
# django-pg-zero-downtime-migrations changelog
## 0.12
- added `serial` and `integer`, `bigserial` and `bigint`, `smallserial` and `smallint`, same types changes as safe migrations
- fixed `AutoField` type changing and concurrent insertions issue for `django<4.1`
- added sequence dropping and creation timeouts as they can be used with `CASCADE` keyword and affect other tables
- added django 4.1 support
- added python 3.11 support
- added postgres 15 support
- marked postgres 10 support deprecated
- drop django 2.2 support
- drop django 3.0 support
- drop django 3.1 support
- drop postgres 9.5 support
- drop postgres 9.6 support
- add github actions checks for pull requests
## 0.11
- fixed rename model with keeping `db_table` raises `ALTER_TABLE_RENAME` error #26
- added django 3.2 support
- added django 4.0 support
- added python 3.9 support
- added python 3.10 support
- added postgres 14 support
- marked django 2.2 support deprecated
- marked django 3.0 support deprecated
- marked django 3.1 support deprecated
- marked python 3.6 support deprecated
- marked python 3.7 support deprecated
- marked postgres 9.5 support deprecated
- marked postgres 9.6 support deprecated
- move to github actions for testing
## 0.10
- added django 3.1 support
- added postgres 13 support
- drop python 3.5 support
- updated test environment
## 0.9
- fixed decimal to float migration error
- fixed django 3.0.2+ tests
## 0.8
- added django 3.0 support
- added concurrently index creation and removal operations
- added exclude constraint support as unsafe operation
- drop postgres 9.4 support
- drop django 2.0 support
- drop django 2.1 support
- drop deprecated `django_zero_downtime_migrations_postgres_backend` module
## 0.7
- added python 3.8 support
- added postgres specific indexes support
- improved tests clearness
- fixed regexp escaping warning for management command
- fixed style check
- improved README
- marked python 3.5 support deprecated
- marked postgres 9.4 support deprecated
- marked django 2.0 support deprecated
- marked django 2.1 support deprecated
## 0.6
- marked `ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL` option deprecated for postgres 12+
- added management command for migration to real `NOT NULL` from `CHECK IS NOT NULL` constraint
- added integration tests for pg 12, pg 11 root, pg 11 compatible not null constraint, pg 11 standard not null constraint and pg 10, 9.6, 9.5, 9.4, postgis databases
- fixed compatible check not null constraint deletion and creation via pg_attribute bugs
- minimized side affect with deferred sql execution between operations in one migration module
- added postgres 12 safe `NOT NULL` constraint creation
- added safe `NOT NULL` constraint creation for extra permissions for `pg_catalog.pg_attribute` with `ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL=USE_PG_ATTRIBUTE_UPDATE_FOR_SUPERUSER` option enabled
- marked `AddField` with `null=False` parameter and compatible `CHECK IS NOT NULL` constraint option as unsafe operation and avoid `ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL` value in this case
- added version to package
- fixed pypi README images links
- improved README
## 0.5
- extracted zero-downtime-schema to mixin to allow use this logic with other backends
- moved module from `django_zero_downtime_migrations_postgres_backend` to `django_zero_downtime_migrations.backends.postgres`
- marked `django_zero_downtime_migrations_postgres_backend` module as deprecated
- added postgis backend support
- improved README
## 0.4
- changed defaults for `ZERO_DOWNTIME_MIGRATIONS_LOCK_TIMEOUT` and `ZERO_DOWNTIME_MIGRATIONS_STATEMENT_TIMEOUT` from `0ms` to `None` to get same with default django behavior that respect default postgres timeouts
- added updates to documentations with options defaults
- added updates to documentations with best options usage
- fixed adding nullable field with default had no error and warning issue
- added links to documentation with issue describing and safe alternatives usage for errors and warnings
- added updates to documentations with type casting workarounds
## 0.3
- added django 2.2 support with `Meta.indexes` and `Meta.constraints` attributes
- fixed python deprecation warnings for regexp
- removed unused `TimeoutException`
- improved README and PYPI description
## 0.2
- added option that allow disable `statement_timeout` for long operations like index creation on constraint validation when statement_timeout set globally
## 0.1.1
- added long description content type
## 0.1
- replaced default sql queries with more safe
- added options for `statement_timeout` and `lock_timeout`
- added option for `NOT NULL` constraint behaviour
- added option for unsafe operation restriction
%package -n python3-django-pg-zero-downtime-migrations
Summary: Django postgresql backend that apply migrations with respect to database locks
Provides: python-django-pg-zero-downtime-migrations
BuildRequires: python3-devel
BuildRequires: python3-setuptools
BuildRequires: python3-pip
%description -n python3-django-pg-zero-downtime-migrations
[](https://pypi.org/project/django-pg-zero-downtime-migrations/)



[](https://raw.githubusercontent.com/tbicr/django-pg-zero-downtime-migrations/master/LICENSE)
[](https://pypistats.org/packages/django-pg-zero-downtime-migrations)
[](https://github.com/tbicr/django-pg-zero-downtime-migrations/commits/master)
[](https://github.com/tbicr/django-pg-zero-downtime-migrations/actions)
# django-pg-zero-downtime-migrations
Django postgresql backend that apply migrations with respect to database locks.
## Installation
pip install django-pg-zero-downtime-migrations
## Usage
To enable zero downtime migrations for postgres just setup django backend provided by this package and add most safe settings:
DATABASES = {
'default': {
'ENGINE': 'django_zero_downtime_migrations.backends.postgres',
#'ENGINE': 'django_zero_downtime_migrations.backends.postgis',
...
}
}
ZERO_DOWNTIME_MIGRATIONS_LOCK_TIMEOUT = '2s'
ZERO_DOWNTIME_MIGRATIONS_STATEMENT_TIMEOUT = '2s'
ZERO_DOWNTIME_MIGRATIONS_FLEXIBLE_STATEMENT_TIMEOUT = True
ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE = True
ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL = False
> _NOTE:_ this backend brings zero downtime improvements only for migrations (schema and `RunSQL` operations, but not for `RunPython` operation), for other purpose it works the same as standard django backend.
> _NOTE:_ this package is in beta, please check your migrations SQL before applying on production and submit issue for any question.
### Differences with standard django backend
This backend provides same result state (except `NOT NULL` constraint replacement for old postgres versions if appropriate option configured), but different way and with additional guarantees for avoiding stuck table locks.
This backend doesn't use transactions for migrations (except `RunPython` operation), because not all SQL fixes can be run in transaction and it allows to avoid deadlocks for complex migration. So when your migration will down in middle of transaction you need fix it manually (instead potential downtime). For that reason good practice to make migration modules small as possible.
### Deployment flow
There are requirements for zero downtime deployment:
1. We have one database;
1. We have several instances with application - application always should be available, even you restart one of instances;
1. We have balancer before instances;
1. Our application works fine before, on and after migration - old application works fine with old and new database schema version;
1. Our application works fine before, on and after instance updating - old and new application versions work fine with new database schema version.

Flow:
1. apply migrations
1. disconnect instance form balancer, restart it and back to balancer - repeat this operation one by one for all instances
If our deployment don't satisfy zero downtime deployment rules, then we split it to smaller deployments.

### Settings
#### ZERO_DOWNTIME_MIGRATIONS_LOCK_TIMEOUT
Apply [`lock_timeout`](https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-LOCK-TIMEOUT) for SQL statements that require `ACCESS EXCLUSIVE` lock, default `None`:
ZERO_DOWNTIME_MIGRATIONS_LOCK_TIMEOUT = '2s'
Allowed values:
- `None` - current postgres setting used
- other - timeout will be applied, `0` and equivalents mean that timeout will be disabled
#### ZERO_DOWNTIME_MIGRATIONS_STATEMENT_TIMEOUT
Apply [`statement_timeout`](https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-STATEMENT-TIMEOUT) for SQL statements that require `ACCESS EXCLUSIVE` lock, default `None`:
ZERO_DOWNTIME_MIGRATIONS_STATEMENT_TIMEOUT = '2s'
Allowed values:
- `None` - current postgres setting used
- other - timeout will be applied, `0` and equivalents mean that timeout will be disabled
#### ZERO_DOWNTIME_MIGRATIONS_FLEXIBLE_STATEMENT_TIMEOUT
Set [`statement_timeout`](https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-STATEMENT-TIMEOUT) to `0ms` for SQL statements that require `SHARE UPDATE EXCLUSIVE` lock that useful in case when `statement_timeout` enabled globally and you try run long-running operations like index creation or constraint validation, default `False`:
ZERO_DOWNTIME_MIGRATIONS_FLEXIBLE_STATEMENT_TIMEOUT = True
#### ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE
Enabled option doesn't allow run potential unsafe migration, default `False`:
ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE = True
#### ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL
Set policy for avoiding `NOT NULL` constraint creation long lock, default `None`:
ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL = 10 ** 7
Allowed values:
- `None` - standard django's behaviour (raise for `ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE = True`)
- `True` - always replace `NOT NULL` constraint with `CHECK (field IS NOT NULL)` (don't raise for `ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE = True`)
- `False` - always use `NOT NULL` constraint (don't raise for `ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE = True`)
- `int` value - use `CHECK (field IS NOT NULL)` instead `NOT NULL` constraint if table has more than `value` rows (approximate rows count used) otherwise use `NOT NULL` constraint (don't raise for `ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE = True`)
- `USE_PG_ATTRIBUTE_UPDATE_FOR_SUPERUSER` - use `pg_catalog.pg_attribute` update to mark column `NOT NULL` and provide same state as default django backend (don't raise for `ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE = True`).
> _NOTE:_ For postgres 12 and newest `NOT NULL` constraint creation has migration replacement that provide same state as default django backend, so this option deprecated and doesn't used this postgres version. If you use `CHECK NOT NULL` compatible constraint before you can migrate it to `NOT NULL` constraints with `manage.py migrate_isnotnull_check_constraints` management command (add `INSTALLED_APPS += ['django_zero_downtime_migrations']` to `settings.py` to use management command).
## How it works
### Postgres table level locks
Postgres has different locks on table level that can conflict with each other https://www.postgresql.org/docs/current/static/explicit-locking.html#LOCKING-TABLES:
| | `ACCESS SHARE` | `ROW SHARE` | `ROW EXCLUSIVE` | `SHARE UPDATE EXCLUSIVE` | `SHARE` | `SHARE ROW EXCLUSIVE` | `EXCLUSIVE` | `ACCESS EXCLUSIVE` |
| ------------------------ | :------------: | :---------: | :-------------: | :----------------------: | :-----: | :-------------------: | :---------: | :----------------: |
| `ACCESS SHARE` | | | | | | | | X |
| `ROW SHARE` | | | | | | | X | X |
| `ROW EXCLUSIVE` | | | | | X | X | X | X |
| `SHARE UPDATE EXCLUSIVE` | | | | X | X | X | X | X |
| `SHARE` | | | X | X | | X | X | X |
| `SHARE ROW EXCLUSIVE` | | | X | X | X | X | X | X |
| `EXCLUSIVE` | | X | X | X | X | X | X | X |
| `ACCESS EXCLUSIVE` | X | X | X | X | X | X | X | X |
### Migration and business logic locks
Lets split this lock to migration and business logic operations.
- Migration operations work synchronously in one thread and cover schema migrations (data migrations conflict with business logic operations same as business logic conflict concurrently).
- Business logic operations work concurrently.
#### Migration locks
| lock | operations |
| ------------------------ | ----------------------------------------------------------------------------------------------------- |
| `ACCESS EXCLUSIVE` | `CREATE SEQUENCE`, `DROP SEQUENCE`, `CREATE TABLE`, `DROP TABLE` \*, `ALTER TABLE` \*\*, `DROP INDEX` |
| `SHARE` | `CREATE INDEX` |
| `SHARE UPDATE EXCLUSIVE` | `CREATE INDEX CONCURRENTLY`, `DROP INDEX CONCURRENTLY`, `ALTER TABLE VALIDATE CONSTRAINT` \*\*\* |
\*: `CREATE SEQUENCE`, `DROP SEQUENCE`, `CREATE TABLE`, `DROP TABLE` shouldn't have conflicts, because your business logic shouldn't yet operate with created tables and shouldn't already operate with deleted tables.
\*\*: Not all `ALTER TABLE` operations take `ACCESS EXCLUSIVE` lock, but all current django's migrations take it https://github.com/django/django/blob/master/django/db/backends/base/schema.py, https://github.com/django/django/blob/master/django/db/backends/postgresql/schema.py and https://www.postgresql.org/docs/current/static/sql-altertable.html.
\*\*\*: Django doesn't have `VALIDATE CONSTRAINT` logic, but we will use it for some cases.
#### Business logic locks
| lock | operations | conflict with lock | conflict with operations |
| --------------- | ---------------------------- | --------------------------------------------------------------- | ------------------------------------------- |
| `ACCESS SHARE` | `SELECT` | `ACCESS EXCLUSIVE` | `ALTER TABLE`, `DROP INDEX` |
| `ROW SHARE` | `SELECT FOR UPDATE` | `ACCESS EXCLUSIVE`, `EXCLUSIVE` | `ALTER TABLE`, `DROP INDEX` |
| `ROW EXCLUSIVE` | `INSERT`, `UPDATE`, `DELETE` | `ACCESS EXCLUSIVE`, `EXCLUSIVE`, `SHARE ROW EXCLUSIVE`, `SHARE` | `ALTER TABLE`, `DROP INDEX`, `CREATE INDEX` |
So you can find that all django schema changes for exist table conflicts with business logic, but fortunately they are safe or has safe alternative in general.
### Postgres row level locks
As business logic mostly works with table rows it's also important to understand lock conflicts on row level https://www.postgresql.org/docs/current/static/explicit-locking.html#LOCKING-ROWS:
| lock | `FOR KEY SHARE` | `FOR SHARE` | `FOR NO KEY UPDATE` | `FOR UPDATE` |
| ------------------- | :-------------: | :---------: | :-----------------: | :----------: |
| `FOR KEY SHARE` | | | | X |
| `FOR SHARE` | | | X | X |
| `FOR NO KEY UPDATE` | | X | X | X |
| `FOR UPDATE` | X | X | X | X |
Main point there is if you have two transactions that update one row, then second transaction will wait until first will be completed. So for business logic and data migrations better to avoid updates for whole table and use batch operations instead.
> _NOTE:_ batch operations also can work faster because postgres can use more optimal execution plan with indexes for small data range.
### Transactions FIFO waiting

Found same diagram in interesting article http://pankrat.github.io/2015/django-migrations-without-downtimes/.
In this diagram we can extract several metrics:
1. operation time - time spent changing schema, in the case of long running operations on many rows tables like `CREATE INDEX` or `ALTER TABLE ADD COLUMN SET DEFAULT`, so you need a safe equivalent.
2. waiting time - your migration will wait until all transactions complete, so there is issue for long running operations/transactions like analytic, so you need avoid it or disable during migration.
3. queries per second + execution time and connections pool - if executing many queries, especially long running ones, they can consume all available database connections until the lock is released, so you need different optimizations there: run migrations when least busy, decrease query count and execution time, split data.
4. too many operations in one transaction - you have issues in all previous points for one operation so if you have many operations in one transaction then you have more likelihood to get this issue, so you need avoid too many simultaneous operations in a single transaction (or even not run it in a transaction at all but being careful when an operation fails).
### Dealing with timeouts
Postgres has two settings to dealing with `waiting time` and `operation time` presented in diagram: `lock_timeout` and `statement_timeout`.
`SET lock_timeout TO '2s'` allow you to avoid downtime when you have long running query/transaction before run migration (https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-LOCK-TIMEOUT).
`SET statement_timeout TO '2s'` allow you to avoid downtime when you have long running migration query (https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-STATEMENT-TIMEOUT).
### Deadlocks
There no downtime issues for deadlocks, but too many operations in one transaction can take most conflicted lock and release it only after transaction commit or rollback. So it's a good idea to avoid `ACCESS EXCLUSIVE` lock operations and long time operations in one transaction. Deadlocks also can make you migration stuck on production deployment when different tables will be locked, for example, for FOREIGN KEY that take `ACCESS EXCLUSIVE` lock for two tables.
### Rows and values storing
Postgres store values of different types different ways. If you try to convert one type to another and it stored different way then postgres will rewrite all values. Fortunately some types stored same way and postgres need to do nothing to change type, but in some cases postgres need to check that all values have same with new type limitations, for example string length.
### Multiversion Concurrency Control
Regarding documentation https://www.postgresql.org/docs/current/static/mvcc-intro.html data consistency in postgres is maintained by using a multiversion model. This means that each SQL statement sees a snapshot of data. It has advantage for adding and deleting columns without any indexes, constrains and defaults do not change exist data, new version of data will be created on `INSERT` and `UPDATE`, delete just mark you record expired. All garbage will be collected later by `VACUUM` or `AUTO VACUUM`.
### Django migrations hacks
Any schema changes can be processed with creation of new table and copy data to it, but it can take significant time.
| # | name | safe | safe alternative | description |
| --: | --------------------------------------------- | :--: | :---------------------------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 1 | `CREATE SEQUENCE` | X | | safe operation, because your business logic shouldn't operate with new sequence on migration time \* |
| 2 | `DROP SEQUENCE` | X | | safe operation, because your business logic shouldn't operate with this sequence on migration time \* |
| 3 | `CREATE TABLE` | X | | safe operation, because your business logic shouldn't operate with new table on migration time \* |
| 4 | `DROP TABLE` | X | | safe operation, because your business logic shouldn't operate with this table on migration time \* |
| 5 | `ALTER TABLE RENAME TO` | | add new table and copy data | **unsafe operation**, it's too hard write business logic that operate with two tables simultaneously, so propose `CREATE TABLE` and then copy all data to new table \* |
| 6 | `ALTER TABLE SET TABLESPACE` | | add new table and copy data | **unsafe operation**, but probably you don't need it at all or often \* |
| 7 | `ALTER TABLE ADD COLUMN` | X | | safe operation if without `SET NOT NULL`, `SET DEFAULT`, `PRIMARY KEY`, `UNIQUE` \* |
| 8 | `ALTER TABLE ADD COLUMN SET DEFAULT` | | add column and set default | **unsafe operation**, because you spend time in migration to populate all values in table, so propose `ALTER TABLE ADD COLUMN` and then populate column and then `SET DEFAULT` \* |
| 9 | `ALTER TABLE ADD COLUMN SET NOT NULL` | | +/- | **unsafe operation**, because doesn't work without `SET DEFAULT` or after migration old code can insert rows without new column and raise exception, so propose `ALTER TABLE ADD COLUMN` and then populate column and then `ALTER TABLE ALTER COLUMN SET NOT NULL` \* and \*\* |
| 10 | `ALTER TABLE ADD COLUMN PRIMARY KEY` | | add index and add constraint | **unsafe operation**, because you spend time in migration to `CREATE INDEX`, so propose `ALTER TABLE ADD COLUMN` and then `CREATE INDEX CONCURRENTLY` and then `ALTER TABLE ADD CONSTRAINT PRIMARY KEY USING INDEX` \*\*\* |
| 11 | `ALTER TABLE ADD COLUMN UNIQUE` | | add index and add constraint | **unsafe operation**, because you spend time in migration to `CREATE INDEX`, so propose `ALTER TABLE ADD COLUMN` and then `CREATE INDEX CONCURRENTLY` and then `ALTER TABLE ADD CONSTRAINT UNIQUE USING INDEX` \*\*\* |
| 12 | `ALTER TABLE ALTER COLUMN TYPE` | | +/- | **unsafe operation**, because you spend time in migration to check that all items in column valid or to change type, but some operations can be safe \*\*\*\* |
| 13 | `ALTER TABLE ALTER COLUMN SET NOT NULL` | | +/- | **unsafe operation**, because you spend time in migration to check that all items in column `NOT NULL` \*\* |
| 14 | `ALTER TABLE ALTER COLUMN DROP NOT NULL` | X | | safe operation |
| 15 | `ALTER TABLE ALTER COLUMN SET DEFAULT` | X | | safe operation |
| 16 | `ALTER TABLE ALTER COLUMN DROP DEFAULT` | X | | safe operation |
| 17 | `ALTER TABLE DROP COLUMN` | X | | safe operation, because your business logic shouldn't operate with this column on migration time, however better `ALTER TABLE ALTER COLUMN DROP NOT NULL`, `ALTER TABLE DROP CONSTRAINT` and `DROP INDEX` before \* and \*\*\*\*\* |
| 18 | `ALTER TABLE RENAME COLUMN` | | add new column and copy data | **unsafe operation**, it's too hard write business logic that operate with two columns simultaneously, so propose `ALTER TABLE CREATE COLUMN` and then copy all data to new column \* |
| 19 | `ALTER TABLE ADD CONSTRAINT CHECK` | | add as not valid and validate | **unsafe operation**, because you spend time in migration to check constraint |
| 20 | `ALTER TABLE DROP CONSTRAINT` (`CHECK`) | X | | safe operation |
| 21 | `ALTER TABLE ADD CONSTRAINT FOREIGN KEY` | | add as not valid and validate | **unsafe operation**, because you spend time in migration to check constraint, lock two tables |
| 22 | `ALTER TABLE DROP CONSTRAINT` (`FOREIGN KEY`) | X | | safe operation, lock two tables |
| 23 | `ALTER TABLE ADD CONSTRAINT PRIMARY KEY` | | add index and add constraint | **unsafe operation**, because you spend time in migration to create index \*\*\* |
| 24 | `ALTER TABLE DROP CONSTRAINT` (`PRIMARY KEY`) | X | | safe operation \*\*\* |
| 25 | `ALTER TABLE ADD CONSTRAINT UNIQUE` | | add index and add constraint | **unsafe operation**, because you spend time in migration to create index \*\*\* |
| 26 | `ALTER TABLE DROP CONSTRAINT` (`UNIQUE`) | X | | safe operation \*\*\* |
| 27 | `ALTER TABLE ADD CONSTRAINT EXCLUDE` | | add new table and copy data |
| 28 | `ALTER TABLE DROP CONSTRAINT (EXCLUDE)` | X | |
| 29 | `CREATE INDEX` | | `CREATE INDEX CONCURRENTLY` | **unsafe operation**, because you spend time in migration to create index |
| 30 | `DROP INDEX` | X | `DROP INDEX CONCURRENTLY` | safe operation \*\*\* |
| 31 | `CREATE INDEX CONCURRENTLY` | X | | safe operation |
| 32 | `DROP INDEX CONCURRENTLY` | X | | safe operation \*\*\* |
\*: main point with migration on production without downtime that your code should correctly work before and after migration, lets look this point closely in [Dealing with logic that should work before and after migration](#dealing-with-logic-that-should-work-before-and-after-migration) section.
\*\*: postgres will check that all items in column `NOT NULL` that take time, lets look this point closely in [Dealing with `NOT NULL` constraint](#dealing-with-not-null-constraint) section.
\*\*\*: postgres will have same behaviour when you skip `ALTER TABLE ADD CONSTRAINT UNIQUE USING INDEX` and still unclear difference with `CONCURRENTLY` except difference in locks, lets look this point closely in [Dealing with `UNIQUE` constraint](#dealing-with-unique-constraint).
\*\*\*\*: lets look this point closely in [Dealing with `ALTER TABLE ALTER COLUMN TYPE`](#dealing-with-alter-table-alter-column-type) section.
\*\*\*\*\*: if you check migration on CI with `python manage.py makemigrations --check` you can't drop column in code without migration creation, so in this case you can be useful _back migration flow_: apply code on all instances and then migrate database
#### Dealing with logic that should work before and after migration
##### Adding and removing models and columns
Migrations: `CREATE SEQUENCE`, `DROP SEQUENCE`, `CREATE TABLE`, `DROP TABLE`, `ALTER TABLE ADD COLUMN`, `ALTER TABLE DROP COLUMN`.
This migrations are pretty safe, because your logic doesn't work with this data before migration
##### Changes for working logic
Migrations: `ALTER TABLE RENAME TO`, `ALTER TABLE SET TABLESPACE`, `ALTER TABLE RENAME COLUMN`, `ALTER TABLE ADD CONSTRAINT EXCLUDE`.
For this migration too hard implement logic that will work correctly for all instances, so there are two ways to dealing with it:
1. create new table/column, copy exist data, drop old table/column
2. downtime
##### Create column with default
Migrations: `ALTER TABLE ADD COLUMN SET DEFAULT`.
Standard django's behaviour for creation column with default is populate all values with default. Django don't use database defaults permanently, so when you add new column with default django will create column with default and drop this default at once, eg. new default will come from django code. In this case you can have a gap when migration applied by not all instances has updated and at this moment new rows in table will be without default and probably you need update nullable values after that. So to avoid this case best way is avoid creation column with default and split column creation (with default for new rows) and data population to two migrations (with deployments).
#### Dealing with `NOT NULL` constraint
Postgres check that all column items `NOT NULL` when you applying `NOT NULL` constraint, for postgres 12 and newest it doesn't make this check if appropriate `CHECK CONSTRAINT` exists, but for older versions you can't defer this check as for `NOT VALID`. Fortunately we have some hacks and alternatives there for old postgres versions.
1. Run migrations when load minimal to avoid negative affect of locking.
2. `SET statement_timeout` and try to set `NOT NULL` constraint for small tables.
3. Use `CHECK (column IS NOT NULL)` constraint instead that support `NOT VALID` option with next `VALIDATE CONSTRAINT`, see article for details https://medium.com/doctolib-engineering/adding-a-not-null-constraint-on-pg-faster-with-minimal-locking-38b2c00c4d1c. There are additionally can be applied `NOT NULL` constraint via direct `pg_catalog.pg_attribute` `attnotnull` update, but it require superuser permissions.
#### Dealing with `UNIQUE` constraint
Postgres has two approaches for uniqueness: `CREATE UNIQUE INDEX` and `ALTER TABLE ADD CONSTRAINT UNIQUE` - both use unique index inside. Difference that we can find that we cannot apply `DROP INDEX CONCURRENTLY` for constraint. However it still unclear what difference for `DROP INDEX` and `DROP INDEX CONCURRENTLY` except difference in locks, but as we seen before both marked as safe - we don't spend time in `DROP INDEX`, just wait for lock. So as django use constraint for uniqueness we also have a hacks to use constraint safely.
#### Dealing with `ALTER TABLE ALTER COLUMN TYPE`
Next operations are safe:
1. `varchar(LESS)` to `varchar(MORE)` where LESS < MORE
2. `varchar(ANY)` to `text`
3. `numeric(LESS, SAME)` to `numeric(MORE, SAME)` where LESS < MORE and SAME == SAME
For other operations propose to create new column and copy data to it. Eg. some types can be also safe, but you should check yourself.
# django-pg-zero-downtime-migrations changelog
## 0.12
- added `serial` and `integer`, `bigserial` and `bigint`, `smallserial` and `smallint`, same types changes as safe migrations
- fixed `AutoField` type changing and concurrent insertions issue for `django<4.1`
- added sequence dropping and creation timeouts as they can be used with `CASCADE` keyword and affect other tables
- added django 4.1 support
- added python 3.11 support
- added postgres 15 support
- marked postgres 10 support deprecated
- drop django 2.2 support
- drop django 3.0 support
- drop django 3.1 support
- drop postgres 9.5 support
- drop postgres 9.6 support
- add github actions checks for pull requests
## 0.11
- fixed rename model with keeping `db_table` raises `ALTER_TABLE_RENAME` error #26
- added django 3.2 support
- added django 4.0 support
- added python 3.9 support
- added python 3.10 support
- added postgres 14 support
- marked django 2.2 support deprecated
- marked django 3.0 support deprecated
- marked django 3.1 support deprecated
- marked python 3.6 support deprecated
- marked python 3.7 support deprecated
- marked postgres 9.5 support deprecated
- marked postgres 9.6 support deprecated
- move to github actions for testing
## 0.10
- added django 3.1 support
- added postgres 13 support
- drop python 3.5 support
- updated test environment
## 0.9
- fixed decimal to float migration error
- fixed django 3.0.2+ tests
## 0.8
- added django 3.0 support
- added concurrently index creation and removal operations
- added exclude constraint support as unsafe operation
- drop postgres 9.4 support
- drop django 2.0 support
- drop django 2.1 support
- drop deprecated `django_zero_downtime_migrations_postgres_backend` module
## 0.7
- added python 3.8 support
- added postgres specific indexes support
- improved tests clearness
- fixed regexp escaping warning for management command
- fixed style check
- improved README
- marked python 3.5 support deprecated
- marked postgres 9.4 support deprecated
- marked django 2.0 support deprecated
- marked django 2.1 support deprecated
## 0.6
- marked `ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL` option deprecated for postgres 12+
- added management command for migration to real `NOT NULL` from `CHECK IS NOT NULL` constraint
- added integration tests for pg 12, pg 11 root, pg 11 compatible not null constraint, pg 11 standard not null constraint and pg 10, 9.6, 9.5, 9.4, postgis databases
- fixed compatible check not null constraint deletion and creation via pg_attribute bugs
- minimized side affect with deferred sql execution between operations in one migration module
- added postgres 12 safe `NOT NULL` constraint creation
- added safe `NOT NULL` constraint creation for extra permissions for `pg_catalog.pg_attribute` with `ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL=USE_PG_ATTRIBUTE_UPDATE_FOR_SUPERUSER` option enabled
- marked `AddField` with `null=False` parameter and compatible `CHECK IS NOT NULL` constraint option as unsafe operation and avoid `ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL` value in this case
- added version to package
- fixed pypi README images links
- improved README
## 0.5
- extracted zero-downtime-schema to mixin to allow use this logic with other backends
- moved module from `django_zero_downtime_migrations_postgres_backend` to `django_zero_downtime_migrations.backends.postgres`
- marked `django_zero_downtime_migrations_postgres_backend` module as deprecated
- added postgis backend support
- improved README
## 0.4
- changed defaults for `ZERO_DOWNTIME_MIGRATIONS_LOCK_TIMEOUT` and `ZERO_DOWNTIME_MIGRATIONS_STATEMENT_TIMEOUT` from `0ms` to `None` to get same with default django behavior that respect default postgres timeouts
- added updates to documentations with options defaults
- added updates to documentations with best options usage
- fixed adding nullable field with default had no error and warning issue
- added links to documentation with issue describing and safe alternatives usage for errors and warnings
- added updates to documentations with type casting workarounds
## 0.3
- added django 2.2 support with `Meta.indexes` and `Meta.constraints` attributes
- fixed python deprecation warnings for regexp
- removed unused `TimeoutException`
- improved README and PYPI description
## 0.2
- added option that allow disable `statement_timeout` for long operations like index creation on constraint validation when statement_timeout set globally
## 0.1.1
- added long description content type
## 0.1
- replaced default sql queries with more safe
- added options for `statement_timeout` and `lock_timeout`
- added option for `NOT NULL` constraint behaviour
- added option for unsafe operation restriction
%package help
Summary: Development documents and examples for django-pg-zero-downtime-migrations
Provides: python3-django-pg-zero-downtime-migrations-doc
%description help
[](https://pypi.org/project/django-pg-zero-downtime-migrations/)



[](https://raw.githubusercontent.com/tbicr/django-pg-zero-downtime-migrations/master/LICENSE)
[](https://pypistats.org/packages/django-pg-zero-downtime-migrations)
[](https://github.com/tbicr/django-pg-zero-downtime-migrations/commits/master)
[](https://github.com/tbicr/django-pg-zero-downtime-migrations/actions)
# django-pg-zero-downtime-migrations
Django postgresql backend that apply migrations with respect to database locks.
## Installation
pip install django-pg-zero-downtime-migrations
## Usage
To enable zero downtime migrations for postgres just setup django backend provided by this package and add most safe settings:
DATABASES = {
'default': {
'ENGINE': 'django_zero_downtime_migrations.backends.postgres',
#'ENGINE': 'django_zero_downtime_migrations.backends.postgis',
...
}
}
ZERO_DOWNTIME_MIGRATIONS_LOCK_TIMEOUT = '2s'
ZERO_DOWNTIME_MIGRATIONS_STATEMENT_TIMEOUT = '2s'
ZERO_DOWNTIME_MIGRATIONS_FLEXIBLE_STATEMENT_TIMEOUT = True
ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE = True
ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL = False
> _NOTE:_ this backend brings zero downtime improvements only for migrations (schema and `RunSQL` operations, but not for `RunPython` operation), for other purpose it works the same as standard django backend.
> _NOTE:_ this package is in beta, please check your migrations SQL before applying on production and submit issue for any question.
### Differences with standard django backend
This backend provides same result state (except `NOT NULL` constraint replacement for old postgres versions if appropriate option configured), but different way and with additional guarantees for avoiding stuck table locks.
This backend doesn't use transactions for migrations (except `RunPython` operation), because not all SQL fixes can be run in transaction and it allows to avoid deadlocks for complex migration. So when your migration will down in middle of transaction you need fix it manually (instead potential downtime). For that reason good practice to make migration modules small as possible.
### Deployment flow
There are requirements for zero downtime deployment:
1. We have one database;
1. We have several instances with application - application always should be available, even you restart one of instances;
1. We have balancer before instances;
1. Our application works fine before, on and after migration - old application works fine with old and new database schema version;
1. Our application works fine before, on and after instance updating - old and new application versions work fine with new database schema version.

Flow:
1. apply migrations
1. disconnect instance form balancer, restart it and back to balancer - repeat this operation one by one for all instances
If our deployment don't satisfy zero downtime deployment rules, then we split it to smaller deployments.

### Settings
#### ZERO_DOWNTIME_MIGRATIONS_LOCK_TIMEOUT
Apply [`lock_timeout`](https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-LOCK-TIMEOUT) for SQL statements that require `ACCESS EXCLUSIVE` lock, default `None`:
ZERO_DOWNTIME_MIGRATIONS_LOCK_TIMEOUT = '2s'
Allowed values:
- `None` - current postgres setting used
- other - timeout will be applied, `0` and equivalents mean that timeout will be disabled
#### ZERO_DOWNTIME_MIGRATIONS_STATEMENT_TIMEOUT
Apply [`statement_timeout`](https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-STATEMENT-TIMEOUT) for SQL statements that require `ACCESS EXCLUSIVE` lock, default `None`:
ZERO_DOWNTIME_MIGRATIONS_STATEMENT_TIMEOUT = '2s'
Allowed values:
- `None` - current postgres setting used
- other - timeout will be applied, `0` and equivalents mean that timeout will be disabled
#### ZERO_DOWNTIME_MIGRATIONS_FLEXIBLE_STATEMENT_TIMEOUT
Set [`statement_timeout`](https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-STATEMENT-TIMEOUT) to `0ms` for SQL statements that require `SHARE UPDATE EXCLUSIVE` lock that useful in case when `statement_timeout` enabled globally and you try run long-running operations like index creation or constraint validation, default `False`:
ZERO_DOWNTIME_MIGRATIONS_FLEXIBLE_STATEMENT_TIMEOUT = True
#### ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE
Enabled option doesn't allow run potential unsafe migration, default `False`:
ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE = True
#### ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL
Set policy for avoiding `NOT NULL` constraint creation long lock, default `None`:
ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL = 10 ** 7
Allowed values:
- `None` - standard django's behaviour (raise for `ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE = True`)
- `True` - always replace `NOT NULL` constraint with `CHECK (field IS NOT NULL)` (don't raise for `ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE = True`)
- `False` - always use `NOT NULL` constraint (don't raise for `ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE = True`)
- `int` value - use `CHECK (field IS NOT NULL)` instead `NOT NULL` constraint if table has more than `value` rows (approximate rows count used) otherwise use `NOT NULL` constraint (don't raise for `ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE = True`)
- `USE_PG_ATTRIBUTE_UPDATE_FOR_SUPERUSER` - use `pg_catalog.pg_attribute` update to mark column `NOT NULL` and provide same state as default django backend (don't raise for `ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE = True`).
> _NOTE:_ For postgres 12 and newest `NOT NULL` constraint creation has migration replacement that provide same state as default django backend, so this option deprecated and doesn't used this postgres version. If you use `CHECK NOT NULL` compatible constraint before you can migrate it to `NOT NULL` constraints with `manage.py migrate_isnotnull_check_constraints` management command (add `INSTALLED_APPS += ['django_zero_downtime_migrations']` to `settings.py` to use management command).
## How it works
### Postgres table level locks
Postgres has different locks on table level that can conflict with each other https://www.postgresql.org/docs/current/static/explicit-locking.html#LOCKING-TABLES:
| | `ACCESS SHARE` | `ROW SHARE` | `ROW EXCLUSIVE` | `SHARE UPDATE EXCLUSIVE` | `SHARE` | `SHARE ROW EXCLUSIVE` | `EXCLUSIVE` | `ACCESS EXCLUSIVE` |
| ------------------------ | :------------: | :---------: | :-------------: | :----------------------: | :-----: | :-------------------: | :---------: | :----------------: |
| `ACCESS SHARE` | | | | | | | | X |
| `ROW SHARE` | | | | | | | X | X |
| `ROW EXCLUSIVE` | | | | | X | X | X | X |
| `SHARE UPDATE EXCLUSIVE` | | | | X | X | X | X | X |
| `SHARE` | | | X | X | | X | X | X |
| `SHARE ROW EXCLUSIVE` | | | X | X | X | X | X | X |
| `EXCLUSIVE` | | X | X | X | X | X | X | X |
| `ACCESS EXCLUSIVE` | X | X | X | X | X | X | X | X |
### Migration and business logic locks
Lets split this lock to migration and business logic operations.
- Migration operations work synchronously in one thread and cover schema migrations (data migrations conflict with business logic operations same as business logic conflict concurrently).
- Business logic operations work concurrently.
#### Migration locks
| lock | operations |
| ------------------------ | ----------------------------------------------------------------------------------------------------- |
| `ACCESS EXCLUSIVE` | `CREATE SEQUENCE`, `DROP SEQUENCE`, `CREATE TABLE`, `DROP TABLE` \*, `ALTER TABLE` \*\*, `DROP INDEX` |
| `SHARE` | `CREATE INDEX` |
| `SHARE UPDATE EXCLUSIVE` | `CREATE INDEX CONCURRENTLY`, `DROP INDEX CONCURRENTLY`, `ALTER TABLE VALIDATE CONSTRAINT` \*\*\* |
\*: `CREATE SEQUENCE`, `DROP SEQUENCE`, `CREATE TABLE`, `DROP TABLE` shouldn't have conflicts, because your business logic shouldn't yet operate with created tables and shouldn't already operate with deleted tables.
\*\*: Not all `ALTER TABLE` operations take `ACCESS EXCLUSIVE` lock, but all current django's migrations take it https://github.com/django/django/blob/master/django/db/backends/base/schema.py, https://github.com/django/django/blob/master/django/db/backends/postgresql/schema.py and https://www.postgresql.org/docs/current/static/sql-altertable.html.
\*\*\*: Django doesn't have `VALIDATE CONSTRAINT` logic, but we will use it for some cases.
#### Business logic locks
| lock | operations | conflict with lock | conflict with operations |
| --------------- | ---------------------------- | --------------------------------------------------------------- | ------------------------------------------- |
| `ACCESS SHARE` | `SELECT` | `ACCESS EXCLUSIVE` | `ALTER TABLE`, `DROP INDEX` |
| `ROW SHARE` | `SELECT FOR UPDATE` | `ACCESS EXCLUSIVE`, `EXCLUSIVE` | `ALTER TABLE`, `DROP INDEX` |
| `ROW EXCLUSIVE` | `INSERT`, `UPDATE`, `DELETE` | `ACCESS EXCLUSIVE`, `EXCLUSIVE`, `SHARE ROW EXCLUSIVE`, `SHARE` | `ALTER TABLE`, `DROP INDEX`, `CREATE INDEX` |
So you can find that all django schema changes for exist table conflicts with business logic, but fortunately they are safe or has safe alternative in general.
### Postgres row level locks
As business logic mostly works with table rows it's also important to understand lock conflicts on row level https://www.postgresql.org/docs/current/static/explicit-locking.html#LOCKING-ROWS:
| lock | `FOR KEY SHARE` | `FOR SHARE` | `FOR NO KEY UPDATE` | `FOR UPDATE` |
| ------------------- | :-------------: | :---------: | :-----------------: | :----------: |
| `FOR KEY SHARE` | | | | X |
| `FOR SHARE` | | | X | X |
| `FOR NO KEY UPDATE` | | X | X | X |
| `FOR UPDATE` | X | X | X | X |
Main point there is if you have two transactions that update one row, then second transaction will wait until first will be completed. So for business logic and data migrations better to avoid updates for whole table and use batch operations instead.
> _NOTE:_ batch operations also can work faster because postgres can use more optimal execution plan with indexes for small data range.
### Transactions FIFO waiting

Found same diagram in interesting article http://pankrat.github.io/2015/django-migrations-without-downtimes/.
In this diagram we can extract several metrics:
1. operation time - time spent changing schema, in the case of long running operations on many rows tables like `CREATE INDEX` or `ALTER TABLE ADD COLUMN SET DEFAULT`, so you need a safe equivalent.
2. waiting time - your migration will wait until all transactions complete, so there is issue for long running operations/transactions like analytic, so you need avoid it or disable during migration.
3. queries per second + execution time and connections pool - if executing many queries, especially long running ones, they can consume all available database connections until the lock is released, so you need different optimizations there: run migrations when least busy, decrease query count and execution time, split data.
4. too many operations in one transaction - you have issues in all previous points for one operation so if you have many operations in one transaction then you have more likelihood to get this issue, so you need avoid too many simultaneous operations in a single transaction (or even not run it in a transaction at all but being careful when an operation fails).
### Dealing with timeouts
Postgres has two settings to dealing with `waiting time` and `operation time` presented in diagram: `lock_timeout` and `statement_timeout`.
`SET lock_timeout TO '2s'` allow you to avoid downtime when you have long running query/transaction before run migration (https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-LOCK-TIMEOUT).
`SET statement_timeout TO '2s'` allow you to avoid downtime when you have long running migration query (https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-STATEMENT-TIMEOUT).
### Deadlocks
There no downtime issues for deadlocks, but too many operations in one transaction can take most conflicted lock and release it only after transaction commit or rollback. So it's a good idea to avoid `ACCESS EXCLUSIVE` lock operations and long time operations in one transaction. Deadlocks also can make you migration stuck on production deployment when different tables will be locked, for example, for FOREIGN KEY that take `ACCESS EXCLUSIVE` lock for two tables.
### Rows and values storing
Postgres store values of different types different ways. If you try to convert one type to another and it stored different way then postgres will rewrite all values. Fortunately some types stored same way and postgres need to do nothing to change type, but in some cases postgres need to check that all values have same with new type limitations, for example string length.
### Multiversion Concurrency Control
Regarding documentation https://www.postgresql.org/docs/current/static/mvcc-intro.html data consistency in postgres is maintained by using a multiversion model. This means that each SQL statement sees a snapshot of data. It has advantage for adding and deleting columns without any indexes, constrains and defaults do not change exist data, new version of data will be created on `INSERT` and `UPDATE`, delete just mark you record expired. All garbage will be collected later by `VACUUM` or `AUTO VACUUM`.
### Django migrations hacks
Any schema changes can be processed with creation of new table and copy data to it, but it can take significant time.
| # | name | safe | safe alternative | description |
| --: | --------------------------------------------- | :--: | :---------------------------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 1 | `CREATE SEQUENCE` | X | | safe operation, because your business logic shouldn't operate with new sequence on migration time \* |
| 2 | `DROP SEQUENCE` | X | | safe operation, because your business logic shouldn't operate with this sequence on migration time \* |
| 3 | `CREATE TABLE` | X | | safe operation, because your business logic shouldn't operate with new table on migration time \* |
| 4 | `DROP TABLE` | X | | safe operation, because your business logic shouldn't operate with this table on migration time \* |
| 5 | `ALTER TABLE RENAME TO` | | add new table and copy data | **unsafe operation**, it's too hard write business logic that operate with two tables simultaneously, so propose `CREATE TABLE` and then copy all data to new table \* |
| 6 | `ALTER TABLE SET TABLESPACE` | | add new table and copy data | **unsafe operation**, but probably you don't need it at all or often \* |
| 7 | `ALTER TABLE ADD COLUMN` | X | | safe operation if without `SET NOT NULL`, `SET DEFAULT`, `PRIMARY KEY`, `UNIQUE` \* |
| 8 | `ALTER TABLE ADD COLUMN SET DEFAULT` | | add column and set default | **unsafe operation**, because you spend time in migration to populate all values in table, so propose `ALTER TABLE ADD COLUMN` and then populate column and then `SET DEFAULT` \* |
| 9 | `ALTER TABLE ADD COLUMN SET NOT NULL` | | +/- | **unsafe operation**, because doesn't work without `SET DEFAULT` or after migration old code can insert rows without new column and raise exception, so propose `ALTER TABLE ADD COLUMN` and then populate column and then `ALTER TABLE ALTER COLUMN SET NOT NULL` \* and \*\* |
| 10 | `ALTER TABLE ADD COLUMN PRIMARY KEY` | | add index and add constraint | **unsafe operation**, because you spend time in migration to `CREATE INDEX`, so propose `ALTER TABLE ADD COLUMN` and then `CREATE INDEX CONCURRENTLY` and then `ALTER TABLE ADD CONSTRAINT PRIMARY KEY USING INDEX` \*\*\* |
| 11 | `ALTER TABLE ADD COLUMN UNIQUE` | | add index and add constraint | **unsafe operation**, because you spend time in migration to `CREATE INDEX`, so propose `ALTER TABLE ADD COLUMN` and then `CREATE INDEX CONCURRENTLY` and then `ALTER TABLE ADD CONSTRAINT UNIQUE USING INDEX` \*\*\* |
| 12 | `ALTER TABLE ALTER COLUMN TYPE` | | +/- | **unsafe operation**, because you spend time in migration to check that all items in column valid or to change type, but some operations can be safe \*\*\*\* |
| 13 | `ALTER TABLE ALTER COLUMN SET NOT NULL` | | +/- | **unsafe operation**, because you spend time in migration to check that all items in column `NOT NULL` \*\* |
| 14 | `ALTER TABLE ALTER COLUMN DROP NOT NULL` | X | | safe operation |
| 15 | `ALTER TABLE ALTER COLUMN SET DEFAULT` | X | | safe operation |
| 16 | `ALTER TABLE ALTER COLUMN DROP DEFAULT` | X | | safe operation |
| 17 | `ALTER TABLE DROP COLUMN` | X | | safe operation, because your business logic shouldn't operate with this column on migration time, however better `ALTER TABLE ALTER COLUMN DROP NOT NULL`, `ALTER TABLE DROP CONSTRAINT` and `DROP INDEX` before \* and \*\*\*\*\* |
| 18 | `ALTER TABLE RENAME COLUMN` | | add new column and copy data | **unsafe operation**, it's too hard write business logic that operate with two columns simultaneously, so propose `ALTER TABLE CREATE COLUMN` and then copy all data to new column \* |
| 19 | `ALTER TABLE ADD CONSTRAINT CHECK` | | add as not valid and validate | **unsafe operation**, because you spend time in migration to check constraint |
| 20 | `ALTER TABLE DROP CONSTRAINT` (`CHECK`) | X | | safe operation |
| 21 | `ALTER TABLE ADD CONSTRAINT FOREIGN KEY` | | add as not valid and validate | **unsafe operation**, because you spend time in migration to check constraint, lock two tables |
| 22 | `ALTER TABLE DROP CONSTRAINT` (`FOREIGN KEY`) | X | | safe operation, lock two tables |
| 23 | `ALTER TABLE ADD CONSTRAINT PRIMARY KEY` | | add index and add constraint | **unsafe operation**, because you spend time in migration to create index \*\*\* |
| 24 | `ALTER TABLE DROP CONSTRAINT` (`PRIMARY KEY`) | X | | safe operation \*\*\* |
| 25 | `ALTER TABLE ADD CONSTRAINT UNIQUE` | | add index and add constraint | **unsafe operation**, because you spend time in migration to create index \*\*\* |
| 26 | `ALTER TABLE DROP CONSTRAINT` (`UNIQUE`) | X | | safe operation \*\*\* |
| 27 | `ALTER TABLE ADD CONSTRAINT EXCLUDE` | | add new table and copy data |
| 28 | `ALTER TABLE DROP CONSTRAINT (EXCLUDE)` | X | |
| 29 | `CREATE INDEX` | | `CREATE INDEX CONCURRENTLY` | **unsafe operation**, because you spend time in migration to create index |
| 30 | `DROP INDEX` | X | `DROP INDEX CONCURRENTLY` | safe operation \*\*\* |
| 31 | `CREATE INDEX CONCURRENTLY` | X | | safe operation |
| 32 | `DROP INDEX CONCURRENTLY` | X | | safe operation \*\*\* |
\*: main point with migration on production without downtime that your code should correctly work before and after migration, lets look this point closely in [Dealing with logic that should work before and after migration](#dealing-with-logic-that-should-work-before-and-after-migration) section.
\*\*: postgres will check that all items in column `NOT NULL` that take time, lets look this point closely in [Dealing with `NOT NULL` constraint](#dealing-with-not-null-constraint) section.
\*\*\*: postgres will have same behaviour when you skip `ALTER TABLE ADD CONSTRAINT UNIQUE USING INDEX` and still unclear difference with `CONCURRENTLY` except difference in locks, lets look this point closely in [Dealing with `UNIQUE` constraint](#dealing-with-unique-constraint).
\*\*\*\*: lets look this point closely in [Dealing with `ALTER TABLE ALTER COLUMN TYPE`](#dealing-with-alter-table-alter-column-type) section.
\*\*\*\*\*: if you check migration on CI with `python manage.py makemigrations --check` you can't drop column in code without migration creation, so in this case you can be useful _back migration flow_: apply code on all instances and then migrate database
#### Dealing with logic that should work before and after migration
##### Adding and removing models and columns
Migrations: `CREATE SEQUENCE`, `DROP SEQUENCE`, `CREATE TABLE`, `DROP TABLE`, `ALTER TABLE ADD COLUMN`, `ALTER TABLE DROP COLUMN`.
This migrations are pretty safe, because your logic doesn't work with this data before migration
##### Changes for working logic
Migrations: `ALTER TABLE RENAME TO`, `ALTER TABLE SET TABLESPACE`, `ALTER TABLE RENAME COLUMN`, `ALTER TABLE ADD CONSTRAINT EXCLUDE`.
For this migration too hard implement logic that will work correctly for all instances, so there are two ways to dealing with it:
1. create new table/column, copy exist data, drop old table/column
2. downtime
##### Create column with default
Migrations: `ALTER TABLE ADD COLUMN SET DEFAULT`.
Standard django's behaviour for creation column with default is populate all values with default. Django don't use database defaults permanently, so when you add new column with default django will create column with default and drop this default at once, eg. new default will come from django code. In this case you can have a gap when migration applied by not all instances has updated and at this moment new rows in table will be without default and probably you need update nullable values after that. So to avoid this case best way is avoid creation column with default and split column creation (with default for new rows) and data population to two migrations (with deployments).
#### Dealing with `NOT NULL` constraint
Postgres check that all column items `NOT NULL` when you applying `NOT NULL` constraint, for postgres 12 and newest it doesn't make this check if appropriate `CHECK CONSTRAINT` exists, but for older versions you can't defer this check as for `NOT VALID`. Fortunately we have some hacks and alternatives there for old postgres versions.
1. Run migrations when load minimal to avoid negative affect of locking.
2. `SET statement_timeout` and try to set `NOT NULL` constraint for small tables.
3. Use `CHECK (column IS NOT NULL)` constraint instead that support `NOT VALID` option with next `VALIDATE CONSTRAINT`, see article for details https://medium.com/doctolib-engineering/adding-a-not-null-constraint-on-pg-faster-with-minimal-locking-38b2c00c4d1c. There are additionally can be applied `NOT NULL` constraint via direct `pg_catalog.pg_attribute` `attnotnull` update, but it require superuser permissions.
#### Dealing with `UNIQUE` constraint
Postgres has two approaches for uniqueness: `CREATE UNIQUE INDEX` and `ALTER TABLE ADD CONSTRAINT UNIQUE` - both use unique index inside. Difference that we can find that we cannot apply `DROP INDEX CONCURRENTLY` for constraint. However it still unclear what difference for `DROP INDEX` and `DROP INDEX CONCURRENTLY` except difference in locks, but as we seen before both marked as safe - we don't spend time in `DROP INDEX`, just wait for lock. So as django use constraint for uniqueness we also have a hacks to use constraint safely.
#### Dealing with `ALTER TABLE ALTER COLUMN TYPE`
Next operations are safe:
1. `varchar(LESS)` to `varchar(MORE)` where LESS < MORE
2. `varchar(ANY)` to `text`
3. `numeric(LESS, SAME)` to `numeric(MORE, SAME)` where LESS < MORE and SAME == SAME
For other operations propose to create new column and copy data to it. Eg. some types can be also safe, but you should check yourself.
# django-pg-zero-downtime-migrations changelog
## 0.12
- added `serial` and `integer`, `bigserial` and `bigint`, `smallserial` and `smallint`, same types changes as safe migrations
- fixed `AutoField` type changing and concurrent insertions issue for `django<4.1`
- added sequence dropping and creation timeouts as they can be used with `CASCADE` keyword and affect other tables
- added django 4.1 support
- added python 3.11 support
- added postgres 15 support
- marked postgres 10 support deprecated
- drop django 2.2 support
- drop django 3.0 support
- drop django 3.1 support
- drop postgres 9.5 support
- drop postgres 9.6 support
- add github actions checks for pull requests
## 0.11
- fixed rename model with keeping `db_table` raises `ALTER_TABLE_RENAME` error #26
- added django 3.2 support
- added django 4.0 support
- added python 3.9 support
- added python 3.10 support
- added postgres 14 support
- marked django 2.2 support deprecated
- marked django 3.0 support deprecated
- marked django 3.1 support deprecated
- marked python 3.6 support deprecated
- marked python 3.7 support deprecated
- marked postgres 9.5 support deprecated
- marked postgres 9.6 support deprecated
- move to github actions for testing
## 0.10
- added django 3.1 support
- added postgres 13 support
- drop python 3.5 support
- updated test environment
## 0.9
- fixed decimal to float migration error
- fixed django 3.0.2+ tests
## 0.8
- added django 3.0 support
- added concurrently index creation and removal operations
- added exclude constraint support as unsafe operation
- drop postgres 9.4 support
- drop django 2.0 support
- drop django 2.1 support
- drop deprecated `django_zero_downtime_migrations_postgres_backend` module
## 0.7
- added python 3.8 support
- added postgres specific indexes support
- improved tests clearness
- fixed regexp escaping warning for management command
- fixed style check
- improved README
- marked python 3.5 support deprecated
- marked postgres 9.4 support deprecated
- marked django 2.0 support deprecated
- marked django 2.1 support deprecated
## 0.6
- marked `ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL` option deprecated for postgres 12+
- added management command for migration to real `NOT NULL` from `CHECK IS NOT NULL` constraint
- added integration tests for pg 12, pg 11 root, pg 11 compatible not null constraint, pg 11 standard not null constraint and pg 10, 9.6, 9.5, 9.4, postgis databases
- fixed compatible check not null constraint deletion and creation via pg_attribute bugs
- minimized side affect with deferred sql execution between operations in one migration module
- added postgres 12 safe `NOT NULL` constraint creation
- added safe `NOT NULL` constraint creation for extra permissions for `pg_catalog.pg_attribute` with `ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL=USE_PG_ATTRIBUTE_UPDATE_FOR_SUPERUSER` option enabled
- marked `AddField` with `null=False` parameter and compatible `CHECK IS NOT NULL` constraint option as unsafe operation and avoid `ZERO_DOWNTIME_MIGRATIONS_USE_NOT_NULL` value in this case
- added version to package
- fixed pypi README images links
- improved README
## 0.5
- extracted zero-downtime-schema to mixin to allow use this logic with other backends
- moved module from `django_zero_downtime_migrations_postgres_backend` to `django_zero_downtime_migrations.backends.postgres`
- marked `django_zero_downtime_migrations_postgres_backend` module as deprecated
- added postgis backend support
- improved README
## 0.4
- changed defaults for `ZERO_DOWNTIME_MIGRATIONS_LOCK_TIMEOUT` and `ZERO_DOWNTIME_MIGRATIONS_STATEMENT_TIMEOUT` from `0ms` to `None` to get same with default django behavior that respect default postgres timeouts
- added updates to documentations with options defaults
- added updates to documentations with best options usage
- fixed adding nullable field with default had no error and warning issue
- added links to documentation with issue describing and safe alternatives usage for errors and warnings
- added updates to documentations with type casting workarounds
## 0.3
- added django 2.2 support with `Meta.indexes` and `Meta.constraints` attributes
- fixed python deprecation warnings for regexp
- removed unused `TimeoutException`
- improved README and PYPI description
## 0.2
- added option that allow disable `statement_timeout` for long operations like index creation on constraint validation when statement_timeout set globally
## 0.1.1
- added long description content type
## 0.1
- replaced default sql queries with more safe
- added options for `statement_timeout` and `lock_timeout`
- added option for `NOT NULL` constraint behaviour
- added option for unsafe operation restriction
%prep
%autosetup -n django-pg-zero-downtime-migrations-0.12
%build
%py3_build
%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
find usr/lib -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
find usr/lib64 -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
find usr/bin -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
find usr/sbin -type f -printf "/%h/%f\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
find usr/share/man -type f -printf "/%h/%f.gz\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .
%files -n python3-django-pg-zero-downtime-migrations -f filelist.lst
%dir %{python3_sitelib}/*
%files help -f doclist.lst
%{_docdir}/*
%changelog
* Sun Apr 23 2023 Python_Bot <Python_Bot@openeuler.org> - 0.12-1
- Package Spec generated
|