Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Drop recursion from migrations and move migration tasks to migration code (#14286)

Iga Karbowiaka4895075351a
diff --git a/saleor/attribute/migrations/0034_assignedpageattributevalue_page_data_migration.py b/saleor/attribute/migrations/0034_assignedpageattributevalue_page_data_migration.py
index 965cd49182..d9a1c3f997 100644
--- a/saleor/attribute/migrations/0034_assignedpageattributevalue_page_data_migration.py
+++ b/saleor/attribute/migrations/0034_assignedpageattributevalue_page_data_migration.py
@@ -1,18 +1,52 @@
# Generated by Django 3.2.20 on 2023-08-24 11:25
-from django.db import migrations
-from django.db.models.signals import post_migrate
-from django.apps import apps as registry
+from django.db import migrations, transaction, connection
-from .tasks.saleor3_16 import assign_pages_to_attribute_values_task
+PAGE_BATCH_SIZE = 5000
-def data_migration(apps, _schema_editor):
- def on_migrations_complete(sender=None, **kwargs):
- assign_pages_to_attribute_values_task.delay()
- sender = registry.get_app_config("attribute")
- post_migrate.connect(on_migrations_complete, weak=False, sender=sender)
+def data_migration(apps, _schema_editor):
+ AssignedPageAttributeValue = apps.get_model(
+ "attribute", "AssignedPageAttributeValue"
+ )
+ while (
+ AssignedPageAttributeValue.objects.filter(page__isnull=True)
+ .values_list("pk", flat=True)
+ .exists()
+ ):
+ update_page_assignment()
+
+
+def update_page_assignment():
+ """Update Page assignment.
+
+ Update a batch of 'AssignedPageAttributeValue' rows by setting their 'page' based
+ on their related 'assignment'.
+
+ The number of rows updated in each batch is determined by the BATCH_SIZE.
+ Rows are locked during the update to prevent concurrent modifications.
+ """
+ with transaction.atomic():
+ with connection.cursor() as cursor:
+ cursor.execute(
+ """
+ WITH limited AS (
+ SELECT av.id
+ FROM attribute_assignedpageattributevalue AS av
+ WHERE av.page_id IS NULL
+ ORDER BY av.id DESC
+ LIMIT %s
+ FOR UPDATE
+ )
+ UPDATE attribute_assignedpageattributevalue AS av
+ SET page_id = apa.page_id
+ FROM attribute_assignedpageattribute AS apa
+ WHERE av.id IN (SELECT id FROM limited)
+ AND av.assignment_id = apa.id;
+ """, # noqa
+ [PAGE_BATCH_SIZE],
+ )
class Migration(migrations.Migration):
diff --git a/saleor/attribute/migrations/0036_assignedproductattributevalue_product_data_migration.py b/saleor/attribute/migrations/0036_assignedproductattributevalue_product_data_migration.py
index 012641a0fa..e95dd8fe0f 100644
--- a/saleor/attribute/migrations/0036_assignedproductattributevalue_product_data_migration.py
+++ b/saleor/attribute/migrations/0036_assignedproductattributevalue_product_data_migration.py
@@ -1,18 +1,50 @@
# Generated by Django 3.2.20 on 2023-08-24 11:25
-from django.db import migrations
-from django.db.models.signals import post_migrate
-from django.apps import apps as registry
+from django.db import migrations, transaction, connection
-from .tasks.saleor3_16 import assign_products_to_attribute_values_task
+PRODUCT_BATCH_SIZE = 1000
-def data_migration(apps, _schema_editor):
- def on_migrations_complete(sender=None, **kwargs):
- assign_products_to_attribute_values_task.delay()
- sender = registry.get_app_config("attribute")
- post_migrate.connect(on_migrations_complete, weak=False, sender=sender)
+def data_migration(apps, _schema_editor):
+ AssignedProductAttributeValue = apps.get_model(
+ "attribute", "AssignedProductAttributeValue"
+ )
+ while (
+ AssignedProductAttributeValue.objects.filter(product__isnull=True)
+ .values_list("pk", flat=True)
+ .exists()
+ ):
+ update_product_assignment()
+
+
+def update_product_assignment():
+ """Assign product_id to a new field on assignedproductattributevalue.
+
+ Take the values from attribute_assignedproductattribute to product_id.
+ The old field has already been deleted in Django State operations so we need
+ to use raw SQL to get the value and copy the assignment from the old table.
+ """
+ with transaction.atomic():
+ with connection.cursor() as cursor:
+ cursor.execute(
+ """
+ UPDATE attribute_assignedproductattributevalue
+ SET product_id = (
+ SELECT product_id
+ FROM attribute_assignedproductattribute
+ WHERE attribute_assignedproductattributevalue.assignment_id = attribute_assignedproductattribute.id
+ )
+ WHERE id IN (
+ SELECT ID FROM attribute_assignedproductattributevalue
+ WHERE product_id IS NULL
+ ORDER BY ID DESC
+ FOR UPDATE
+ LIMIT %s
+ );
+ """, # noqa
+ [PRODUCT_BATCH_SIZE],
+ )
class Migration(migrations.Migration):
diff --git a/saleor/attribute/migrations/tasks/__init__.py b/saleor/attribute/migrations/tasks/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/saleor/attribute/migrations/tasks/saleor3_16.py b/saleor/attribute/migrations/tasks/saleor3_16.py
deleted file mode 100644
index 9abcd052bf..0000000000
--- a/saleor/attribute/migrations/tasks/saleor3_16.py
+++ /dev/null
@@ -1,101 +0,0 @@
-from ....celeryconf import app
-from ...models import AssignedProductAttributeValue, AssignedPageAttributeValue
-
-from django.db import transaction, connection
-
-# batch size to make sure that task is completed in 1 second
-# and we don't use too much memory
-PRODUCT_BATCH_SIZE = 1000
-PAGE_BATCH_SIZE = 5000
-
-
-def update_product_assignment():
- """Assign product_id to a new field on assignedproductattributevalue.
-
- Take the values from attribute_assignedproductattribute to product_id.
- The old field has already been deleted in Django State operations so we need
- to use raw SQL to get the value and copy the assignment from the old table.
- """
- with connection.cursor() as cursor:
- cursor.execute(
- """
- UPDATE attribute_assignedproductattributevalue
- SET product_id = (
- SELECT product_id
- FROM attribute_assignedproductattribute
- WHERE attribute_assignedproductattributevalue.assignment_id = attribute_assignedproductattribute.id
- )
- WHERE id IN (
- SELECT ID FROM attribute_assignedproductattributevalue
- WHERE product_id IS NULL
- ORDER BY ID DESC
- FOR UPDATE
- LIMIT %s
- );
- """, # noqa
- [PRODUCT_BATCH_SIZE],
- )
-
-
-def assign_products_to_attribute_values_task():
- # Order events proceed from the newest to the oldest
- assigned_values = (
- AssignedProductAttributeValue.objects.filter(product__isnull=True)
- .values_list("pk", flat=True)
- .exists()
- )
- # If we found data, queue next execution of the task
- if assigned_values:
- update_product_assignment()
- assign_products_to_attribute_values_task.delay()
-
-
-def update_page_assignment():
- """Update Page assignment.
-
- Update a batch of 'AssignedPageAttributeValue' rows by setting their 'page' based
- on their related 'assignment'.
-
- The number of rows updated in each batch is determined by the BATCH_SIZE.
- Rows are locked during the update to prevent concurrent modifications.
- """
- with transaction.atomic():
- with connection.cursor() as cursor:
- cursor.execute(
- """
- WITH limited AS (
- SELECT av.id
- FROM attribute_assignedpageattributevalue AS av
- WHERE av.page_id IS NULL
- ORDER BY av.id DESC
- LIMIT %s
- FOR UPDATE
- )
- UPDATE attribute_assignedpageattributevalue AS av
- SET page_id = apa.page_id
- FROM attribute_assignedpageattribute AS apa
- WHERE av.id IN (SELECT id FROM limited)
- AND av.assignment_id = apa.id;
- """, # noqa
- [PAGE_BATCH_SIZE],
- )
-
-
-def assign_pages_to_attribute_values_task():
- """Celery task to update 'AssignedPageAttributeValue' rows in batches.
-
- Checks for rows where the 'page' is null and updates them based on their
- related 'assignment'. After updating a batch, the task schedules
- itself for the next batch if more rows need updating.
- """
- assigned_values = (
- AssignedPageAttributeValue.objects.filter(page__isnull=True)
- .values_list("pk", flat=True)
- .exists()
- )
- # If we found data, queue next execution of the task
- if assigned_values:
- update_page_assignment()
- assign_pages_to_attribute_values_task.delay()
diff --git a/saleor/attribute/tests/test_page_attributes_migration.py b/saleor/attribute/tests/test_page_attributes_migration.py
deleted file mode 100644
index ff5312c5f0..0000000000
--- a/saleor/attribute/tests/test_page_attributes_migration.py
+++ /dev/null
@@ -1,42 +0,0 @@
-from unittest.mock import patch
-
-import pytest
-
-from saleor.attribute.migrations.tasks.saleor3_16 import (
- assign_pages_to_attribute_values_task,
-)
-from saleor.attribute.models import AssignedPageAttributeValue
-
-
-def test_update_page_assignment(second_page):
- page1, page2 = second_page
- apa_values_init = AssignedPageAttributeValue.objects.filter(
- assignment__page_id__in=[page1.id, page2.id]
- )
- # check that initially page field is populated in a default manner
- assert len(apa_values_init) == 12
- for assigned_page in apa_values_init:
- assert assigned_page.assignment.page.id == assigned_page.page.id
-
- # create state before migration
- AssignedPageAttributeValue.objects.filter(
- assignment__page_id__in=[page1.id, page2.id]
- ).update(page=None)
-
- apa_values_before_migration = AssignedPageAttributeValue.objects.filter(
- assignment__page_id__in=[page1.id, page2.id]
- )
- assert len(apa_values_before_migration) == 12
- for assigned_page in apa_values_before_migration:
- assert assigned_page.page is None
-
- with patch("saleor.attribute.migrations.tasks.saleor3_16.PAGE_BATCH_SIZE", 5):
- assign_pages_to_attribute_values_task()
-
- apa_values_post_migration = AssignedPageAttributeValue.objects.filter(
- assignment__page_id__in=[page1.id, page2.id]
- )
- assert len(apa_values_post_migration) == 12
- for assigned_page in apa_values_post_migration:
- assert assigned_page.assignment.page.id == assigned_page.page.id
diff --git a/saleor/celeryconf.py b/saleor/celeryconf.py
index 8fcab60f4d..2bd58a9cd8 100644
--- a/saleor/celeryconf.py
+++ b/saleor/celeryconf.py
@@ -27,12 +27,6 @@ app = Celery("saleor")
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()
-app.autodiscover_tasks(
- packages=[
- "saleor.attribute.migrations.tasks",
- ],
- related_name="saleor3_16",
-)
app.autodiscover_tasks(
packages=[
"saleor.discount.migrations.tasks",
diff --git a/saleor/discount/migrations/0047_migrate_sales_to_promotions.py b/saleor/discount/migrations/0047_migrate_sales_to_promotions.py
index 5913f7d977..3747da1c1b 100644
--- a/saleor/discount/migrations/0047_migrate_sales_to_promotions.py
+++ b/saleor/discount/migrations/0047_migrate_sales_to_promotions.py
@@ -71,11 +71,12 @@ def migrate_sales_with_listing(
sales = Sale.objects.exclude(
Exists(Promotion.objects.filter(old_sale_id=OuterRef("pk")))
).order_by("pk")
- sales_listing = SaleChannelListing.objects.order_by("sale_id").filter(
- Exists(sales.filter(id=OuterRef("sale_id")))
- )[:BATCH_SIZE]
- sale_ids = list(sales_listing.values_list("sale_id", flat=True))
- if sale_ids:
+ sales_listing = (
+ SaleChannelListing.objects.order_by("sale_id")
+ .filter(Exists(sales.filter(id=OuterRef("sale_id"))))
+ .order_by("sale_id")
+ )
+ for sale_ids in sale_id_in_batches(sales_listing):
with transaction.atomic():
qs = (
Sale.objects.filter(
@@ -100,20 +101,19 @@ def migrate_sales_with_listing(
OrderLine,
CheckoutLineDiscount,
OrderLineDiscount,
- sales,
+ qs,
)
- migrate_sales_with_listing(
- Promotion,
- PromotionRule,
- PromotionTranslation,
- Sale,
- SaleChannelListing,
- SaleTranslation,
- RuleInfo,
- OrderLine,
- CheckoutLineDiscount,
- OrderLineDiscount,
- )
+
+
+def sale_id_in_batches(queryset):
+ sale_id = 0
+ while True:
+ qs = queryset.values("sale_id").filter(sale_id__gt=sale_id)[:BATCH_SIZE]
+ sale_pks = [v["sale_id"] for v in qs]
+ if not sale_pks:
+ break
+ yield sale_pks
+ sale_id = sale_pks[-1]
def _migrate_sales_with_listing(
@@ -168,8 +168,7 @@ def migrate_sales_without_listing(
~Exists(sales_listing.filter(sale_id=OuterRef("pk"))),
~Exists(Promotion.objects.filter(old_sale_id=OuterRef("pk"))),
).order_by("pk")
- ids = list(sales_not_listed.values_list("pk", flat=True)[:BATCH_SIZE])
- if ids:
+ for ids in queryset_in_batches(sales_not_listed):
with transaction.atomic():
qs = Sale.objects.filter(
~Exists(Promotion.objects.filter(old_sale_id=OuterRef("pk"))),
@@ -184,14 +183,17 @@ def migrate_sales_without_listing(
_migrate_sales_without_listing(
Promotion, PromotionRule, PromotionTranslation, Sale, SaleTranslation, qs
)
- migrate_sales_without_listing(
- Promotion,
- PromotionRule,
- PromotionTranslation,
- Sale,
- SaleTranslation,
- SaleChannelListing,
- )
+
+
+def queryset_in_batches(queryset):
+ start_pk = 0
+ while True:
+ qs = queryset.values("pk").filter(pk__gt=start_pk)[:BATCH_SIZE]
+ pks = [v["pk"] for v in qs]
+ if not pks:
+ break
+ yield pks
+ start_pk = pks[-1]
def _migrate_sales_without_listing(