Skip to content

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

fix(clearorders): crash when checkout delivery is assigned (#19495)

Mikail86889f43afd5
diff --git a/saleor/core/management/commands/clearorders.py b/saleor/core/management/commands/clearorders.py
index 763fe635ce..c21522e0b1 100644
--- a/saleor/core/management/commands/clearorders.py
+++ b/saleor/core/management/commands/clearorders.py
@@ -6,6 +6,7 @@ configuration, such as: warehouses, shipping zones, staff accounts, plugin confi
"""
from django.core.management.base import BaseCommand
+from django.db import transaction
from ....account.models import Address, CustomerEvent, CustomerNote, User
from ....checkout.models import (
@@ -95,11 +96,20 @@ class Command(BaseCommand):
checkout_lines = CheckoutLine.objects.all()
checkout_lines._raw_delete(checkout_lines.db)
- checkout_deliveries = CheckoutDelivery.objects.all()
- checkout_deliveries._raw_delete(checkout_deliveries.db)
-
- checkout = Checkout.objects.all()
- checkout._raw_delete(checkout.db)
+ # We use a transaction in order to defer PostgreSQL FK checks due to
+ # Checkout and CheckoutDelivery models/tables referencing each other,
+ # thus this requires deferring the FK checks after deleting both tables
+ # (thus deferring autocommit)
+ #
+ # Note: this may cause locks to be held for longer, however this is the
+ # the cheapest approach. Doing a bulk update would be highly
+ # expensive in comparison
+ with transaction.atomic():
+ checkout_deliveries = CheckoutDelivery.objects.all()
+ checkout_deliveries._raw_delete(checkout_deliveries.db)
+
+ checkout = Checkout.objects.all()
+ checkout._raw_delete(checkout.db)
self.stdout.write("Removed checkouts")
def delete_payments(self):
diff --git a/saleor/core/tests/commands/test_clearorders.py b/saleor/core/tests/commands/test_clearorders.py
index a17b248eea..30ba63bf97 100644
--- a/saleor/core/tests/commands/test_clearorders.py
+++ b/saleor/core/tests/commands/test_clearorders.py
@@ -5,9 +5,26 @@ from ....checkout.models import Checkout, CheckoutDelivery
@pytest.mark.django_db
-def test_delete_checkouts_with_checkout_delivery(checkout, checkout_delivery):
+ ("_case", "assign_delivery"),
+ [
+ # These two cases cause two different types of FK-checks
+ # which can cause PostgreSQL to refuse to delete these checkouts.
+ # Thus we need these two cases to ensure both FK checks are properly
+ # handled.
+ ("delivery_not_assigned", False),
+ ("delivery_assigned_to_checkout", True),
+ ],
+)
+def test_delete_checkouts_with_checkout_delivery(
+ _case, checkout, checkout_delivery, assign_delivery
+):
# given
delivery = checkout_delivery(checkout)
+ if assign_delivery:
+ checkout.assigned_delivery = delivery
+ checkout.save(update_fields=["assigned_delivery"])
+
assert Checkout.objects.filter(pk=checkout.pk).exists()
assert CheckoutDelivery.objects.filter(pk=delivery.pk).exists()