Skip to content

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

Add new field to store page in AssignedPageAttributeValue (#13814)

Michał Macioszczyk8668dcfb886c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2cd9e32ca3..6071e5bfd2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -50,12 +50,14 @@ All notable, unreleased changes to this project will be documented in this file.
- Fix error in variant available stock calculation - 13593 by @awaisdar001
- Add missing currency in action for transaction requests - 13786 by @AjmalPonneth
- Fix giftcard code description - #13728 by @rafiwts
+
- Change error message when denying a permission - #13334 by @rafiwts
- Add filter by slugs to attribute choices - #13761 by @rafiwts
- Add a new `product` field on `AssignedProductAttributeValue`. First part of a simplification of Attribute - Product relation from #12881. by @aniav
- Lazy legacy webhooks payload generation - #13758 by @maarcingebala
- Fix NoneType in `prodcutChannelsListingUpdate` - #13694 by @Manoj-gowra
- Extended `AttributeValueTranslation.name` to 250 characters - #13776 by @aniav
+- Add a new `page` field on `AssignedPageAttributeValue`. First stage (migration) of a simplification of Attribute - Page relation from #13403. by michal-macioszczyk
# 3.15.0
diff --git a/saleor/attribute/migrations/0032_assignedpageattributevalue_page_add_field.py b/saleor/attribute/migrations/0032_assignedpageattributevalue_page_add_field.py
new file mode 100644
index 0000000000..585fb5853b
--- /dev/null
+++ b/saleor/attribute/migrations/0032_assignedpageattributevalue_page_add_field.py
@@ -0,0 +1,24 @@
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("page", "0028_add_default_page_type"),
+ ("attribute", "0031_extend_attributr_value_fields_length"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="assignedpageattributevalue",
+ name="page",
+ field=models.ForeignKey(
+ null=True,
+ blank=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="attributevalues",
+ to="page.page",
+ db_index=False,
+ ),
+ ),
+ ]
diff --git a/saleor/attribute/migrations/0033_assignedpageattributevalue_page_add_index.py b/saleor/attribute/migrations/0033_assignedpageattributevalue_page_add_index.py
new file mode 100644
index 0000000000..f979ee41d6
--- /dev/null
+++ b/saleor/attribute/migrations/0033_assignedpageattributevalue_page_add_index.py
@@ -0,0 +1,21 @@
+# Generated by Django 3.2.20 on 2023-08-24 11:25
+
+from django.db import migrations
+from django.contrib.postgres.operations import AddIndexConcurrently
+from django.contrib.postgres.indexes import BTreeIndex
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("page", "0028_add_default_page_type"),
+ ("attribute", "0032_assignedpageattributevalue_page_add_field"),
+ ]
+
+ operations = [
+ AddIndexConcurrently(
+ model_name="assignedpageattributevalue",
+ index=BTreeIndex(fields=["page"], name="assignedpageattrvalue_page_idx"),
+ ),
+ ]
diff --git a/saleor/attribute/migrations/0034_assignedpageattributevalue_page_data_migration.py b/saleor/attribute/migrations/0034_assignedpageattributevalue_page_data_migration.py
new file mode 100644
index 0000000000..965cd49182
--- /dev/null
+++ b/saleor/attribute/migrations/0034_assignedpageattributevalue_page_data_migration.py
@@ -0,0 +1,26 @@
+# 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 .tasks.saleor3_16 import assign_pages_to_attribute_values_task
+
+
+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)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("page", "0028_add_default_page_type"),
+ ("attribute", "0033_assignedpageattributevalue_page_add_index"),
+ ]
+
+ operations = [
+ migrations.RunPython(data_migration, migrations.RunPython.noop),
+ ]
diff --git a/saleor/attribute/migrations/tasks/__init__.py b/saleor/attribute/migrations/tasks/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/attribute/migrations/tasks/saleor3_16.py b/saleor/attribute/migrations/tasks/saleor3_16.py
index 8b6a22a0c0..a7c27d81df 100644
--- a/saleor/attribute/migrations/tasks/saleor3_16.py
+++ b/saleor/attribute/migrations/tasks/saleor3_16.py
@@ -1,11 +1,12 @@
from ....celeryconf import app
-from ...models import AssignedProductAttributeValue
+from ...models import AssignedProductAttributeValue, AssignedPageAttributeValue
-from django.db import connection
+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
BATCH_SIZE = 1000
+PAGE_BATCH_SIZE = 5000
def update_product_assignment():
@@ -47,3 +48,53 @@ def assign_products_to_attribute_values_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/models/page.py b/saleor/attribute/models/page.py
index a8d4cfde62..2d6c7cbf9d 100644
--- a/saleor/attribute/models/page.py
+++ b/saleor/attribute/models/page.py
@@ -1,3 +1,4 @@
+from django.contrib.postgres.indexes import BTreeIndex
from django.db import models
from ...core.models import SortableModel
@@ -16,10 +17,19 @@ class AssignedPageAttributeValue(SortableModel):
on_delete=models.CASCADE,
related_name="pagevalueassignment",
)
+ page = models.ForeignKey(
+ Page,
+ related_name="attributevalues",
+ on_delete=models.CASCADE,
+ null=True,
+ blank=True,
+ db_index=False,
+ )
class Meta:
unique_together = (("value", "assignment"),)
ordering = ("sort_order", "pk")
+ indexes = [BTreeIndex(fields=["page"], name="assignedpageattrvalue_page_idx")]
def get_ordering_queryset(self):
return self.assignment.pagevalueassignment.all()
diff --git a/saleor/attribute/tests/test_page_attributes_migration.py b/saleor/attribute/tests/test_page_attributes_migration.py
new file mode 100644
index 0000000000..648ac7415d
--- /dev/null
+++ b/saleor/attribute/tests/test_page_attributes_migration.py
@@ -0,0 +1,42 @@
+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.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/attribute/utils.py b/saleor/attribute/utils.py
index a5ea8d166f..6e1222ea3f 100644
--- a/saleor/attribute/utils.py
+++ b/saleor/attribute/utils.py
@@ -51,6 +51,13 @@ def associate_attribute_values_to_instance(
assignment_id=assignment.pk
).update(product_id=instance.pk)
+ # This code will be deleted in new release (3.17), it is temporary solution between
+ # releases to keep database in sync
+ elif isinstance(instance, Page):
+ AssignedPageAttributeValue.objects.filter(assignment_id=assignment.pk).update(
+ page_id=instance.pk
+ )
+
sort_assigned_attribute_values(instance, assignment, values)
return assignment
diff --git a/saleor/graphql/page/tests/mutations/test_page_reorder_attribute_values.py b/saleor/graphql/page/tests/mutations/test_page_reorder_attribute_values.py
index a212ff69c9..014be89382 100644
--- a/saleor/graphql/page/tests/mutations/test_page_reorder_attribute_values.py
+++ b/saleor/graphql/page/tests/mutations/test_page_reorder_attribute_values.py
@@ -1,6 +1,6 @@
import graphene
-from .....attribute.models import AttributeValue
+from .....attribute.models import AssignedPageAttributeValue, AttributeValue
from .....attribute.utils import associate_attribute_values_to_instance
from .....page.error_codes import PageErrorCode
from ....tests.utils import get_graphql_content
@@ -112,6 +112,11 @@ def test_sort_page_attribute_values(
assert db_type == "AttributeValue"
assert int(value_pk) == expected_pk
+ apa_values = AssignedPageAttributeValue.objects.filter(assignment__page_id=page.id)
+ assert len(apa_values) == 3
+ for assigned_page in apa_values:
+ assert assigned_page.assignment.page.id == assigned_page.page.id
+
def test_sort_page_attribute_values_invalid_attribute_id(
staff_api_client,
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 5c5cd573be..fdb9063b39 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -5664,6 +5664,44 @@ def page(db, page_type):
return page
+def second_page(page):
+ data = {
+ "slug": "test-url-2",
+ "title": "Test page 2",
+ "content": dummy_editorjs("Test content 2."),
+ "is_published": True,
+ "page_type": page.page_type,
+ }
+ page2 = Page.objects.create(**data)
+
+ # associate attribute value to the second page
+ page_attr = page.page_type.page_attributes.first()
+ page_attr_value = page_attr.values.first()
+
+ associate_attribute_values_to_instance(page2, page_attr, page_attr_value)
+
+ attribute = Attribute.objects.create(
+ slug="test-attribute",
+ name="Test Attribute",
+ type="some_attribute_type",
+ input_type=AttributeInputType.DROPDOWN,
+ )
+ attribute.page_types.add(page.page_type)
+
+ attribute_values = []
+ for i in range(10):
+ attribute_values.append(
+ AttributeValue.objects.create(
+ attribute=attribute,
+ name=f"Test-name-attribute-value-{i}",
+ slug=f"test-slug-attribute-value-{i}",
+ )
+ )
+ associate_attribute_values_to_instance(page2, attribute, *attribute_values)
+ return page, page2
+
+
@pytest.fixture
def page_with_rich_text_attribute(db, page_type_with_rich_text_attribute):
data = {