Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Refactor `select_for_update` utils (#17866)
Filip Owczarek20a2b1f48f34
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex c1117c10c7..c2de671746 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -406,6 +406,26 @@ otherwise to the main module directory, usually to the `utils.py` file.Try to find a name as descriptive as possible when writing such a method.Also, do not forget about the docstring, especially in a complicated function.+### Locking Objects++To lock objects and prevent race conditions in concurrent operations, use Django's [`select_for_update()`](https://docs.djangoproject.com/en/stable/ref/models/querysets/#select-for-update) method on querysets.++#### General Guidelines++- When locking **multiple objects**, always lock them **in a consistent order** to avoid deadlocks.+ - Use a clear and stable ordering—typically by `pk`.+ - When locking **across multiple models**, always acquire locks in a defined order. For example, lock the `Order` model **before** `OrderLine`.++#### Best Practices++To reduce the chance of deadlocks and to keep the locking logic consistent:++- Wrap all locking logic in **helper functions**.+- Place these helper functions in a file named `lock_objects.py` located in the same app directory as the model you're locking.+ - For single-model locks, use the model's app directory (e.g. `orders/lock_objects.py`).+ - For multi-model locks, place the function in the directory of the **last model being locked**.+ - Example: If locking `Order` and `TransactionItem`, and `TransactionItem` is locked last, use `payment/lock_objects.py`.+### SearchingSo far, we have mainly used the `GinIndex` and `ilike` operators for searching, but currently, we are testing a new solution with the use of `SearchVector` and `SearchRank`.diff --git a/saleor/checkout/lock_objects.py b/saleor/checkout/lock_objects.pynew file mode 100644index 0000000000..4c12ae6dbc--- /dev/null+++ b/saleor/checkout/lock_objects.py@@ -0,0 +1,11 @@+from django.db.models import QuerySet++from .models import Checkout, CheckoutLine+++def checkout_qs_select_for_update() -> QuerySet[Checkout]:+ return Checkout.objects.order_by("pk").select_for_update(of=(["self"]))+++def checkout_lines_qs_select_for_update() -> QuerySet[CheckoutLine]:+ return CheckoutLine.objects.order_by("pk").select_for_update(of=(["self"]))diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex dbf88ebfad..5f85135a8c 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -9,7 +9,7 @@ import graphenefrom django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom django.db import transaction-from django.db.models import QuerySet, prefetch_related_objects+from django.db.models import prefetch_related_objectsfrom django.utils import timezonefrom prices import Money@@ -61,6 +61,7 @@ from ..warehouse.models import Warehousefrom ..warehouse.reservations import reserve_stocks_and_preordersfrom . import AddressType, base_calculations, calculationsfrom .error_codes import CheckoutErrorCode+from .lock_objects import checkout_lines_qs_select_for_updatefrom .models import Checkout, CheckoutLine, CheckoutMetadataif TYPE_CHECKING:@@ -123,10 +124,6 @@ def invalidate_checkout_prices(return updated_fields-def checkout_lines_qs_select_for_update() -> QuerySet[CheckoutLine]:- return CheckoutLine.objects.order_by("id").select_for_update(of=(["self"]))--def checkout_lines_bulk_update(lines_to_update: list["CheckoutLine"], fields_to_update: list[str]):diff --git a/saleor/discount/utils/order.py b/saleor/discount/utils/order.pyindex fd7e3f7462..2fa10e936b 100644--- a/saleor/discount/utils/order.py+++ b/saleor/discount/utils/order.py@@ -13,6 +13,7 @@ from ...core.db.connection import allow_writerfrom ...core.prices import quantize_pricefrom ...core.taxes import zero_moneyfrom ...order.base_calculations import base_order_subtotal+from ...order.lock_objects import order_qs_select_for_updatefrom ...order.models import Order, OrderLinefrom .. import DiscountTypefrom ..interface import VariantPromotionRuleInfo@@ -43,8 +44,6 @@ def create_order_line_discount_objects(list[str],],) -> None | list["EditableOrderLineInfo"]:- from ...order.utils import order_qs_select_for_update-if not discount_data or not lines_info:return None@@ -282,8 +281,6 @@ def create_order_line_discount_objects_for_catalogue_promotions(rules_info: Iterable[VariantPromotionRuleInfo],channel: Channel,) -> list["OrderLineDiscount"]:- from ...order.utils import order_qs_select_for_update-line_discounts_to_create: list[OrderLineDiscount] = []for rule_info in rules_info:line_discount = _create_order_line_discount_for_catalogue_promotion(diff --git a/saleor/discount/utils/promotion.py b/saleor/discount/utils/promotion.pyindex 70fbe44e06..0d9e67ddb5 100644--- a/saleor/discount/utils/promotion.py+++ b/saleor/discount/utils/promotion.py@@ -15,11 +15,13 @@ from prices import Moneyfrom ...channel.models import Channelfrom ...checkout.fetch import CheckoutLineInfo+from ...checkout.lock_objects import checkout_lines_qs_select_for_updatefrom ...checkout.models import Checkout, CheckoutLinefrom ...core.db.connection import allow_writerfrom ...core.exceptions import InsufficientStockfrom ...core.taxes import zero_moneyfrom ...order.fetch import EditableOrderLineInfo+from ...order.lock_objects import order_lines_qs_select_for_updatefrom ...order.models import Orderfrom ...product.models import (Product,@@ -404,9 +406,6 @@ def _get_available_for_purchase_variant_ids(def delete_gift_lines_qs(order_or_checkout: Checkout | Order,):- from ...checkout.utils import checkout_lines_qs_select_for_update- from ...order.utils import order_lines_qs_select_for_update-with transaction.atomic():if isinstance(order_or_checkout, Checkout):locked_checkout_lines_qs = checkout_lines_qs_select_for_update()diff --git a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py b/saleor/graphql/payment/mutations/transaction/transaction_event_report.pyindex cca890fc0f..e6c00ccaa0 100644--- a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py+++ b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py@@ -9,7 +9,6 @@ from .....app.models import Appfrom .....checkout.actions import (transaction_amounts_for_checkout_updated_without_price_recalculation,)-from .....checkout.models import Checkoutfrom .....core.exceptions import PermissionDeniedfrom .....core.prices import quantize_pricefrom .....core.tracing import traced_atomic_transaction@@ -25,6 +24,11 @@ from .....order.utils import (from .....payment import OPTIONAL_AMOUNT_EVENTS, TransactionEventTypefrom .....payment import models as payment_modelsfrom .....payment.interface import PaymentMethodDetails+from .....payment.lock_objects import (+ get_checkout_and_transaction_item_locked_for_update,+ get_order_and_transaction_item_locked_for_update,+ transaction_item_qs_select_for_update,+)from .....payment.transaction_item_calculations import recalculate_transaction_amountsfrom .....payment.utils import (authorization_success_already_exists,@@ -312,16 +316,9 @@ class TransactionEventReport(DeprecatedModelMutation):):order = cast(order_models.Order, transaction.order)with traced_atomic_transaction():- order = (- order_models.Order.objects.prefetch_related(- "payments", "payment_transactions", "granted_refunds"- )- .select_for_update()- .get(pk=order.pk)+ order, transaction = get_order_and_transaction_item_locked_for_update(+ order.pk, transaction.pk)- transaction = payment_models.TransactionItem.objects.select_for_update(- of=("self",)- ).get(pk=transaction.pk)updates_amounts_for_order(order)update_order_search_vector(order)order_info = fetch_order_info(order)@@ -353,14 +350,11 @@ class TransactionEventReport(DeprecatedModelMutation):checkout_deleted = Falseif transaction.checkout_id:with traced_atomic_transaction():- locked_checkout = (- Checkout.objects.select_for_update()- .filter(pk=transaction.checkout_id)- .first()+ locked_checkout, transaction = (+ get_checkout_and_transaction_item_locked_for_update(+ transaction.checkout_id, transaction.pk+ ))- transaction = payment_models.TransactionItem.objects.select_for_update(- of=("self",)- ).get(pk=transaction.pk)if transaction.checkout_id and locked_checkout:transaction_amounts_for_checkout_updated_without_price_recalculation(transaction, locked_checkout, manager, user, app@@ -485,8 +479,8 @@ class TransactionEventReport(DeprecatedModelMutation):# thread race. We need to be sure, that we will always create a single event# on our side for specific action._transaction = (- payment_models.TransactionItem.objects.filter(pk=transaction.pk)- .select_for_update(of=("self",))+ transaction_item_qs_select_for_update()+ .filter(pk=transaction.pk).first())diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.pyindex c2eaad4769..17d2fcf4e4 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py@@ -13,8 +13,8 @@ from ....core.postgres import FlatConcatSearchVectorfrom ....core.tracing import traced_atomic_transactionfrom ....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirtyfrom ....order import events as order_events+from ....order.lock_objects import order_lines_qs_select_for_updatefrom ....order.tasks import recalculate_orders_task-from ....order.utils import order_lines_qs_select_for_updatefrom ....permission.enums import ProductPermissionsfrom ....product import modelsfrom ....product.search import prepare_product_search_vector_valuediff --git a/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.py b/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.pyindex 75c83aa394..b1e6760d62 100644--- a/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.py+++ b/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.py@@ -8,7 +8,7 @@ from ....core.tracing import traced_atomic_transactionfrom ....permission.enums import ProductPermissionsfrom ....warehouse import modelsfrom ....warehouse.error_codes import StockBulkUpdateErrorCode-from ....warehouse.management import stock_qs_select_for_update+from ....warehouse.lock_objects import stock_qs_select_for_updatefrom ....webhook.event_types import WebhookEventAsyncTypefrom ....webhook.utils import get_webhooks_for_eventfrom ...core.doc_category import DOC_CATEGORY_PRODUCTSdiff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex 3e49269a6f..b8935fde43 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -22,7 +22,7 @@ from ..core.utils.events import (webhook_async_event_requires_sync_webhooks_to_trigger,)from ..giftcard import GiftCardLineData-from ..order.utils import order_lines_qs_select_for_update+from ..order.lock_objects import order_lines_qs_select_for_updatefrom ..payment import (ChargeStatus,CustomPaymentChoices,diff --git a/saleor/order/lock_objects.py b/saleor/order/lock_objects.pynew file mode 100644index 0000000000..d924eecdcc--- /dev/null+++ b/saleor/order/lock_objects.py@@ -0,0 +1,11 @@+from django.db.models import QuerySet++from .models import Order, OrderLine+++def order_lines_qs_select_for_update() -> QuerySet[OrderLine]:+ return OrderLine.objects.order_by("pk").select_for_update(of=["self"])+++def order_qs_select_for_update() -> QuerySet[Order]:+ return Order.objects.order_by("pk").select_for_update(of=(["self"]))diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 714485c776..c4d930daa8 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -84,14 +84,6 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)-def order_qs_select_for_update():- return Order.objects.order_by("id").select_for_update(of=(["self"]))---def order_lines_qs_select_for_update() -> QuerySet[OrderLine]:- return OrderLine.objects.order_by("pk").select_for_update(of=["self"])--def get_order_country(order: Order) -> str:"""Return country to which order will be shipped."""return get_active_country(diff --git a/saleor/payment/lock_objects.py b/saleor/payment/lock_objects.pynew file mode 100644index 0000000000..2d28b8c2cc--- /dev/null+++ b/saleor/payment/lock_objects.py@@ -0,0 +1,36 @@+from typing import TYPE_CHECKING, Optional+from uuid import UUID++from django.db.models import QuerySet++from ..checkout.lock_objects import checkout_qs_select_for_update+from ..order.lock_objects import order_qs_select_for_update+from .models import TransactionItem++if TYPE_CHECKING:+ from ..checkout.models import Checkout+ from ..order.models import Order+++def transaction_item_qs_select_for_update() -> QuerySet[TransactionItem]:+ return TransactionItem.objects.order_by("pk").select_for_update(of=["self"])+++def get_order_and_transaction_item_locked_for_update(+ order_id: UUID, transaction_item_id: int+) -> tuple["Order", TransactionItem]:+ order = order_qs_select_for_update().get(pk=order_id)+ transaction_item = transaction_item_qs_select_for_update().get(+ pk=transaction_item_id+ )+ return order, transaction_item+++def get_checkout_and_transaction_item_locked_for_update(+ checkout_id: UUID, transaction_item_id: int+) -> tuple[Optional["Checkout"], TransactionItem]:+ checkout = checkout_qs_select_for_update().filter(pk=checkout_id).first()+ transaction_item = transaction_item_qs_select_for_update().get(+ pk=transaction_item_id+ )+ return checkout, transaction_itemdiff --git a/saleor/warehouse/lock_objects.py b/saleor/warehouse/lock_objects.pynew file mode 100644index 0000000000..3b99c1d904--- /dev/null+++ b/saleor/warehouse/lock_objects.py@@ -0,0 +1,22 @@+from .models import Allocation, Stock+++def stock_select_for_update_for_existing_qs(qs):+ return qs.order_by("pk").select_for_update(of=(["self"]))+++def stock_qs_select_for_update():+ return stock_select_for_update_for_existing_qs(Stock.objects.all())+++def allocation_with_stock_qs_select_for_update():+ return (+ Allocation.objects.select_related("stock")+ .select_for_update(+ of=(+ "self",+ "stock",+ )+ )+ .order_by("stock__pk")+ )diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.pyindex 34e87cd6b6..b5febccb79 100644--- a/saleor/warehouse/management.py+++ b/saleor/warehouse/management.py@@ -23,6 +23,11 @@ from ..order.fetch import OrderLineInfofrom ..order.models import OrderLinefrom ..plugins.manager import PluginsManagerfrom ..product.models import ProductVariant, ProductVariantChannelListing+from .lock_objects import (+ allocation_with_stock_qs_select_for_update,+ stock_qs_select_for_update,+ stock_select_for_update_for_existing_qs,+)from .models import (Allocation,ChannelWarehouse,@@ -42,14 +47,6 @@ class StockData(NamedTuple):quantity: int-def stock_select_for_update_for_existing_qs(qs):- return qs.order_by("pk").select_for_update(of=(["self"]))---def stock_qs_select_for_update():- return stock_select_for_update_for_existing_qs(Stock.objects.all())--def delete_stocks(stock_pks_to_delete: list[int]):with transaction.atomic():return Stock.objects.filter(@@ -70,19 +67,6 @@ def stock_bulk_update(stocks: list[Stock], fields_to_update: list[str]):Stock.objects.bulk_update(stocks, fields_to_update)-def allocation_with_stock_qs_select_for_update():- return (- Allocation.objects.select_related("stock")- .select_for_update(- of=(- "self",- "stock",- )- )- .order_by("stock__pk")- )--def delete_allocations(allocation_pks_to_delete: list[int]):with transaction.atomic():return Allocation.objects.filter(diff --git a/saleor/warehouse/reservations.py b/saleor/warehouse/reservations.pyindex 60fb413ad2..a204d52898 100644--- a/saleor/warehouse/reservations.py+++ b/saleor/warehouse/reservations.py@@ -11,7 +11,8 @@ from django.utils import timezonefrom ..core.exceptions import InsufficientStock, InsufficientStockDatafrom ..core.tracing import traced_atomic_transactionfrom ..product.models import ProductVariant, ProductVariantChannelListing-from .management import sort_stocks, stock_qs_select_for_update+from .lock_objects import stock_qs_select_for_update+from .management import sort_stocksfrom .models import Allocation, PreorderReservation, Reservationif TYPE_CHECKING: