-
-
Notifications
You must be signed in to change notification settings - Fork 303
Zero-downtime migration tooling; widen File.file_size to bigint (expand stage) #5986
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
rtibbles
wants to merge
3
commits into
learningequality:hotfixes
Choose a base branch
from
rtibbles:widen_file_size_bigint
base: hotfixes
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
Empty file.
12 changes: 12 additions & 0 deletions
12
contentcuration/contentcuration/db/backends/zero_downtime_prometheus/base.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| from django_prometheus.db.backends.postgresql.base import ( | ||
| DatabaseWrapper as PrometheusDatabaseWrapper, | ||
| ) | ||
| from django_zero_downtime_migrations.backends.postgres.schema import ( | ||
| DatabaseSchemaEditor, | ||
| ) | ||
|
|
||
|
|
||
| class DatabaseWrapper(PrometheusDatabaseWrapper): | ||
| """Prometheus query metrics + zero-downtime safe-DDL schema editor.""" | ||
|
|
||
| SchemaEditorClass = DatabaseSchemaEditor |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| import hashlib | ||
|
|
||
| import pgtrigger | ||
|
|
||
|
|
||
| def mirror_field(source, target): | ||
| """Mirror Django field `source` into `target` via a BEFORE INSERT/UPDATE | ||
| trigger (expand/contract dual-write).""" | ||
|
|
||
| def decorator(model): | ||
| source_col = model._meta.get_field(source).column | ||
| target_col = model._meta.get_field(target).column | ||
| name = "mirror_{}_to_{}".format(source_col, target_col) | ||
| if len(name) > 43: # stay safely under pgtrigger's trigger-name limit | ||
| digest = hashlib.sha1( | ||
| "{}_{}".format(source_col, target_col).encode() | ||
| ).hexdigest()[:8] | ||
| name = "mirror_{}".format(digest) | ||
| # Change-guard (IS DISTINCT FROM): keeps a read cutover from clobbering | ||
| # writes to the repointed column with the stale source value. | ||
| trigger = pgtrigger.Trigger( | ||
| name=name, | ||
| when=pgtrigger.Before, | ||
| operation=pgtrigger.Insert | pgtrigger.Update, | ||
| func="IF NEW.{s} IS DISTINCT FROM OLD.{s} THEN NEW.{t} = NEW.{s}; END IF; RETURN NEW;".format( | ||
| s=source_col, t=target_col | ||
| ), | ||
| ) | ||
| return pgtrigger.register(trigger)(model) | ||
|
|
||
| return decorator |
100 changes: 100 additions & 0 deletions
100
contentcuration/contentcuration/management/commands/backfill_column.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| from django.apps import apps | ||
| from django.core.exceptions import FieldDoesNotExist | ||
| from django.core.management.base import BaseCommand | ||
| from django.core.management.base import CommandError | ||
| from django.db import transaction | ||
| from django.db.models import F | ||
|
|
||
|
|
||
| class Command(BaseCommand): | ||
| help = ( | ||
| "Idempotent, resumable online backfill of one column into another, in batches." | ||
| ) | ||
|
|
||
| def add_arguments(self, parser): | ||
| parser.add_argument("--model", required=True, help="app_label.ModelName") | ||
| parser.add_argument("--source-field", required=True) | ||
| parser.add_argument("--target-field", required=True) | ||
| parser.add_argument("--batch-size", type=int, default=10000) | ||
| parser.add_argument("--start-id", default=None, help="resume from this pk") | ||
| parser.add_argument( | ||
| "--progress-check", | ||
| action="store_true", | ||
| help="report unbackfilled rows, exit nonzero if any", | ||
| ) | ||
|
|
||
| def _resolve_model_fields(self, model_label, source, target): | ||
| try: | ||
| model = apps.get_model(model_label) | ||
| except (LookupError, ValueError) as e: | ||
| raise CommandError("Bad --model {!r}: {}".format(model_label, e)) | ||
| try: | ||
| model._meta.get_field(source) | ||
| model._meta.get_field(target) | ||
| except FieldDoesNotExist as e: | ||
| raise CommandError(str(e)) | ||
| return model | ||
|
|
||
| def _batch_end_pk(self, queryset, pk_name, start_pk, batch_size): | ||
| """Last pk of the batch of `batch_size` rows starting at `start_pk`. | ||
|
|
||
| Returns None when fewer than `batch_size` rows remain at/after | ||
| `start_pk` — the final, short batch. Keyset paging by pk, so it works | ||
| for any pk type (int or UUID). | ||
| """ | ||
| return ( | ||
| queryset.filter(pk__gte=start_pk) | ||
| .order_by(pk_name) | ||
| .values_list("pk", flat=True)[batch_size - 1 : batch_size] | ||
| .first() | ||
| ) | ||
|
|
||
| def handle(self, *args, **options): | ||
| if options["batch_size"] < 1: | ||
| raise CommandError("--batch-size must be >= 1") | ||
| source = options["source_field"] | ||
| target = options["target_field"] | ||
| model = self._resolve_model_fields(options["model"], source, target) | ||
|
|
||
| pk_name = model._meta.pk.name | ||
| batch_size = options["batch_size"] | ||
| only_unfilled = {target + "__isnull": True, source + "__isnull": False} | ||
| unfilled = model.objects.filter(**only_unfilled) | ||
| unfilled_pks = unfilled.order_by(pk_name).values_list("pk", flat=True) | ||
|
|
||
| if options["progress_check"]: | ||
| # exists(), not count() — the target table can have millions of rows. | ||
| if unfilled.exists(): | ||
| raise CommandError("backfill incomplete: rows still pending") | ||
| self.stdout.write("Backfill complete: no rows pending.") | ||
| return | ||
|
|
||
| # Start at the first unfilled pk (>= --start-id if given); re-runs and | ||
| # resumes skip straight past an already-filled prefix. | ||
| batch_start = unfilled_pks | ||
| if options["start_id"] is not None: | ||
| batch_start = batch_start.filter(pk__gte=options["start_id"]) | ||
| batch_start = batch_start.first() | ||
|
|
||
| total = 0 | ||
| while batch_start is not None: | ||
| batch_end = self._batch_end_pk( | ||
| model.objects, pk_name, batch_start, batch_size | ||
| ) | ||
| if batch_end is None: | ||
| window = {"pk__gte": batch_start} | ||
| else: | ||
| window = {"pk__gte": batch_start, "pk__lte": batch_end} | ||
| with transaction.atomic(): | ||
| total += model.objects.filter(**window, **only_unfilled).update( | ||
| **{target: F(source)} | ||
| ) | ||
| self.stdout.write( | ||
| "backfilled through pk={} (updated {} so far)".format( | ||
| batch_start if batch_end is None else batch_end, total | ||
| ) | ||
| ) | ||
| if batch_end is None: | ||
| break | ||
| batch_start = unfilled_pks.filter(pk__gt=batch_end).first() | ||
| self.stdout.write("Done. {} rows updated.".format(total)) |
43 changes: 43 additions & 0 deletions
43
contentcuration/contentcuration/migrations/0167_file_size_bigint_expand.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| # Generated by Django 3.2.24 on 2026-06-23 05:56 | ||
| import pgtrigger.compiler | ||
| import pgtrigger.migrations | ||
| from django.db import migrations | ||
| from django.db import models | ||
| from django.db.models import Q | ||
|
|
||
|
|
||
| class Migration(migrations.Migration): | ||
|
|
||
| dependencies = [ | ||
| ("contentcuration", "0166_add_usersubscription"), | ||
| ] | ||
|
|
||
| operations = [ | ||
| migrations.AddField( | ||
| model_name="file", | ||
| name="file_size_bigint", | ||
| field=models.BigIntegerField(blank=True, null=True), | ||
| ), | ||
| migrations.AddIndex( | ||
| model_name="file", | ||
| index=models.Index( | ||
| fields=["checksum", "file_size_bigint"], | ||
| name="file_checksum_fsizebig_idx", | ||
| condition=Q(file_size_bigint__isnull=False), | ||
| ), | ||
| ), | ||
| pgtrigger.migrations.AddTrigger( | ||
| model_name="file", | ||
| trigger=pgtrigger.compiler.Trigger( | ||
| name="mirror_file_size_to_file_size_bigint", | ||
| sql=pgtrigger.compiler.UpsertTriggerSql( | ||
| func="IF NEW.file_size IS DISTINCT FROM OLD.file_size THEN NEW.file_size_bigint = NEW.file_size; END IF; RETURN NEW;", | ||
| hash="051e321c4cdf91ea81f96b9f9a29e3b5015def67", | ||
| operation="INSERT OR UPDATE", | ||
| pgid="pgtrigger_mirror_file_size_to_file_size_bigint_54326", | ||
| table="contentcuration_file", | ||
| when="BEFORE", | ||
| ), | ||
| ), | ||
| ), | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A constraint on
file_size_bigintbeing not null may speed up this creation of this new index.