Skip to content

Commit

Permalink
fix: make migration 0013 reversible (#533)
Browse files Browse the repository at this point in the history
* fix: make migration 0013 reversible

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix: write backwards data migration function

* fix: only call json.dumps if fields are TextField

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
browniebroke and pre-commit-ci[bot] authored Dec 21, 2023
1 parent e90019f commit 848f45c
Showing 1 changed file with 41 additions and 2 deletions.
43 changes: 41 additions & 2 deletions social_django/migrations/0013_migrate_extra_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import json

from django.db import migrations
from django.db import migrations, models


def migrate_json_field(apps, schema_editor):
Expand Down Expand Up @@ -41,11 +41,50 @@ def migrate_json_field(apps, schema_editor):
auth.save(update_fields=["data_new"])


def migrate_json_field_backwards(apps, schema_editor):
UserSocialAuth = apps.get_model("social_django", "UserSocialAuth")
Partial = apps.get_model("social_django", "Partial")
db_alias = schema_editor.connection.alias
to_be_updated = []

is_text_field = isinstance(
UserSocialAuth._meta.get_field("extra_data"),
models.TextField,
)
for auth in UserSocialAuth.objects.using(db_alias).iterator():
new_value = auth.extra_data_new
if is_text_field:
new_value = json.dumps(new_value)
auth.extra_data = new_value
to_be_updated.append(auth)

if len(to_be_updated) >= 1000:
UserSocialAuth.objects.bulk_update(to_be_updated, ["extra_data"])
to_be_updated.clear()

if to_be_updated:
UserSocialAuth.objects.bulk_update(to_be_updated, ["extra_data"])
to_be_updated.clear()

is_text_field = issubclass(
Partial._meta.get_field("data"),
models.TextField,
)
for auth in Partial.objects.using(db_alias).all():
new_value = auth.data_new
if is_text_field:
new_value = json.dumps(new_value)
auth.data = new_value
auth.save(update_fields=["data"])


class Migration(migrations.Migration):
dependencies = [
("social_django", "0012_usersocialauth_extra_data_new"),
]

operations = [
migrations.RunPython(migrate_json_field, elidable=True),
migrations.RunPython(
migrate_json_field, migrate_json_field_backwards, elidable=True
),
]

0 comments on commit 848f45c

Please sign in to comment.