Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add replica usages to checkout and order related queries (#15571)
Marcin Gębalace8274317468
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.pyindex cfa6852b22..3493f023af 100644--- a/saleor/checkout/calculations.py+++ b/saleor/checkout/calculations.py@@ -38,6 +38,7 @@ def checkout_shipping_price(checkout_info: "CheckoutInfo",lines: Iterable["CheckoutLineInfo"],address: Optional["Address"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> "TaxedMoney":"""Return checkout shipping price.@@ -49,6 +50,7 @@ def checkout_shipping_price(manager=manager,lines=lines,address=address,+ database_connection_name=database_connection_name,)return quantize_price(checkout_info.checkout.shipping_price, currency)@@ -59,6 +61,7 @@ def checkout_shipping_tax_rate(checkout_info: "CheckoutInfo",lines: Iterable["CheckoutLineInfo"],address: Optional["Address"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> Decimal:"""Return checkout shipping tax rate.@@ -69,6 +72,7 @@ def checkout_shipping_tax_rate(manager=manager,lines=lines,address=address,+ database_connection_name=database_connection_name,)return checkout_info.checkout.shipping_tax_rate@@ -79,6 +83,7 @@ def checkout_subtotal(checkout_info: "CheckoutInfo",lines: Iterable["CheckoutLineInfo"],address: Optional["Address"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> "TaxedMoney":"""Return the total cost of all the checkout lines, taxes included.@@ -90,6 +95,7 @@ def checkout_subtotal(manager=manager,lines=lines,address=address,+ database_connection_name=database_connection_name,)return quantize_price(checkout_info.checkout.subtotal, currency)@@ -99,16 +105,15 @@ def calculate_checkout_total_with_gift_cards(checkout_info: "CheckoutInfo",lines: Iterable["CheckoutLineInfo"],address: Optional["Address"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> "TaxedMoney":- total = (- checkout_total(- manager=manager,- checkout_info=checkout_info,- lines=lines,- address=address,- )- - checkout_info.checkout.get_total_gift_cards_balance()- )+ total = checkout_total(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=address,+ database_connection_name=database_connection_name,+ ) - checkout_info.checkout.get_total_gift_cards_balance(database_connection_name)return max(total, zero_taxed_money(total.currency))@@ -119,6 +124,7 @@ def checkout_total(checkout_info: "CheckoutInfo",lines: Iterable["CheckoutLineInfo"],address: Optional["Address"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> "TaxedMoney":"""Return the total cost of the checkout.@@ -133,6 +139,7 @@ def checkout_total(manager=manager,lines=lines,address=address,+ database_connection_name=database_connection_name,)return quantize_price(checkout_info.checkout.total, currency)@@ -143,6 +150,7 @@ def checkout_line_total(checkout_info: "CheckoutInfo",lines: Iterable["CheckoutLineInfo"],checkout_line_info: "CheckoutLineInfo",+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> TaxedMoney:"""Return the total price of provided line, taxes included.@@ -155,6 +163,7 @@ def checkout_line_total(manager=manager,lines=lines,address=address,+ database_connection_name=database_connection_name,)checkout_line = find_checkout_line_info(lines, checkout_line_info.line.id).linereturn quantize_price(checkout_line.total_price, currency)@@ -166,6 +175,7 @@ def checkout_line_unit_price(checkout_info: "CheckoutInfo",lines: Iterable["CheckoutLineInfo"],checkout_line_info: "CheckoutLineInfo",+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> TaxedMoney:"""Return the unit price of provided line, taxes included.@@ -178,6 +188,7 @@ def checkout_line_unit_price(manager=manager,lines=lines,address=address,+ database_connection_name=database_connection_name,)checkout_line = find_checkout_line_info(lines, checkout_line_info.line.id).lineunit_price = checkout_line.total_price / checkout_line.quantity@@ -190,6 +201,7 @@ def checkout_line_tax_rate(checkout_info: "CheckoutInfo",lines: Iterable["CheckoutLineInfo"],checkout_line_info: "CheckoutLineInfo",+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> Decimal:"""Return the tax rate of provided line.@@ -201,6 +213,7 @@ def checkout_line_tax_rate(manager=manager,lines=lines,address=address,+ database_connection_name=database_connection_name,)checkout_line_info = find_checkout_line_info(lines, checkout_line_info.line.id)return checkout_line_info.line.tax_rate@@ -212,6 +225,7 @@ def _fetch_checkout_prices_if_expired(lines: Iterable["CheckoutLineInfo"],address: Optional["Address"] = None,force_update: bool = False,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> tuple["CheckoutInfo", Iterable["CheckoutLineInfo"]]:"""Fetch checkout prices with taxes.@@ -228,15 +242,21 @@ def _fetch_checkout_prices_if_expired(tax_configuration = checkout_info.tax_configurationtax_calculation_strategy = get_tax_calculation_strategy_for_checkout(- checkout_info, lines+ checkout_info, lines, database_connection_name=database_connection_name)prices_entered_with_tax = tax_configuration.prices_entered_with_tax- charge_taxes = get_charge_taxes_for_checkout(checkout_info, lines)+ charge_taxes = get_charge_taxes_for_checkout(+ checkout_info, lines, database_connection_name=database_connection_name+ )should_charge_tax = charge_taxes and not checkout.tax_exemption- tax_app_identifier = get_tax_app_identifier_for_checkout(checkout_info, lines)+ tax_app_identifier = get_tax_app_identifier_for_checkout(+ checkout_info, lines, database_connection_name+ )lines = cast(list, lines)- create_or_update_discount_objects_from_promotion_for_checkout(checkout_info, lines)+ create_or_update_discount_objects_from_promotion_for_checkout(+ checkout_info, lines, database_connection_name+ )checkout.tax_error = Noneif prices_entered_with_tax:@@ -252,6 +272,7 @@ def _fetch_checkout_prices_if_expired(lines,prices_entered_with_tax,address,+ database_connection_name=database_connection_name,)except TaxEmptyData as e:checkout.tax_error = str(e)@@ -276,6 +297,7 @@ def _fetch_checkout_prices_if_expired(lines,prices_entered_with_tax,address,+ database_connection_name=database_connection_name,)except TaxEmptyData as e:checkout.tax_error = str(e)@@ -327,6 +349,7 @@ def _calculate_and_add_tax(lines: Iterable["CheckoutLineInfo"],prices_entered_with_tax: bool,address: Optional["Address"] = None,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):if tax_calculation_strategy == TaxCalculationStrategy.TAX_APP:# If taxAppId is not configured run all active plugins and tax apps.@@ -354,7 +377,12 @@ def _calculate_and_add_tax(else:# Get taxes calculated with flat rates and apply to checkout.update_checkout_prices_with_flat_rates(- checkout, checkout_info, lines, prices_entered_with_tax, address+ checkout,+ checkout_info,+ lines,+ prices_entered_with_tax,+ address,+ database_connection_name=database_connection_name,)@@ -553,6 +581,7 @@ def fetch_checkout_data(force_update: bool = False,checkout_transactions: Optional[Iterable["TransactionItem"]] = None,force_status_update: bool = False,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):"""Fetch checkout data.@@ -566,6 +595,7 @@ def fetch_checkout_data(lines=lines,address=address,force_update=force_update,+ database_connection_name=database_connection_name,)current_total_gross = checkout_info.checkout.total.grossif current_total_gross != previous_total_gross or force_status_update:@@ -574,6 +604,7 @@ def fetch_checkout_data(checkout_total_gross=current_total_gross,checkout_has_lines=bool(lines),checkout_transactions=checkout_transactions,+ database_connection_name=database_connection_name,)return checkout_info, linesdiff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.pyindex 3c880e35a9..4965f0c7ba 100644--- a/saleor/checkout/fetch.py+++ b/saleor/checkout/fetch.py@@ -11,6 +11,8 @@ from typing import ()from uuid import UUID+from django.conf import settings+from ..core.utils.lazyobjects import lazy_no_retryfrom ..discount import DiscountType, VoucherTypefrom ..discount.interface import fetch_variant_rules_info, fetch_voucher_info@@ -240,6 +242,7 @@ def fetch_checkout_lines(skip_lines_with_unavailable_variants: bool = True,skip_recalculation: bool = False,voucher: Optional["Voucher"] = None,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> tuple[Iterable[CheckoutLineInfo], Iterable[int]]:"""Fetch checkout lines as CheckoutLineInfo objects."""from .utils import get_voucher_for_checkout@@ -326,7 +329,10 @@ def fetch_checkout_lines(if not skip_recalculation and checkout.voucher_code and lines_info:if not voucher:voucher, _ = get_voucher_for_checkout(- checkout, channel_slug=channel.slug, with_prefetch=True+ checkout,+ channel_slug=channel.slug,+ with_prefetch=True,+ database_connection_name=database_connection_name,)if not voucher:# in case when voucher is expired, it will be null so no need to apply any@@ -429,6 +435,7 @@ def fetch_checkout_info(fetch_delivery_methods=True,voucher: Optional["Voucher"] = None,voucher_code: Optional["VoucherCode"] = None,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> CheckoutInfo:"""Fetch checkout as CheckoutInfo object."""from .utils import get_voucher_for_checkout@@ -441,7 +448,9 @@ def fetch_checkout_info(if not voucher or not voucher_code:voucher, voucher_code = get_voucher_for_checkout(- checkout, channel_slug=channel.slug+ checkout,+ channel_slug=channel.slug,+ database_connection_name=database_connection_name,)delivery_method_info = get_delivery_method_info(None, shipping_address)@@ -468,6 +477,7 @@ def fetch_checkout_info(lines,manager,shipping_channel_listings,+ database_connection_name=database_connection_name,)return checkout_info@@ -534,6 +544,7 @@ def update_checkout_info_shipping_address(lines: Iterable[CheckoutLineInfo],manager: "PluginsManager",shipping_channel_listings: Iterable["ShippingMethodChannelListing"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):checkout_info.shipping_address = address@@ -545,6 +556,7 @@ def update_checkout_info_shipping_address(lines,manager,shipping_channel_listings,+ database_connection_name=database_connection_name,)@@ -553,6 +565,7 @@ def get_valid_internal_shipping_method_list_for_checkout_info(shipping_address: Optional["Address"],lines: Iterable[CheckoutLineInfo],shipping_channel_listings: Iterable[ShippingMethodChannelListing],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> list["ShippingMethodData"]:from . import base_calculationsfrom .utils import get_valid_internal_shipping_methods_for_checkout@@ -586,6 +599,7 @@ def get_valid_internal_shipping_method_list_for_checkout_info(subtotal,shipping_channel_listings,country_code=country_code,+ database_connection_name=database_connection_name,)return valid_shipping_methods@@ -608,6 +622,7 @@ def get_all_shipping_methods_list(lines,shipping_channel_listings,manager,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):return list(itertools.chain(@@ -616,6 +631,7 @@ def get_all_shipping_methods_list(shipping_address,lines,shipping_channel_listings,+ database_connection_name=database_connection_name,),get_valid_external_shipping_method_list_for_checkout_info(checkout_info, shipping_address, lines, manager@@ -632,6 +648,7 @@ def update_delivery_method_lists_for_checkout_info(lines: Iterable[CheckoutLineInfo],manager: "PluginsManager",shipping_channel_listings: Iterable[ShippingMethodChannelListing],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):"""Update the list of shipping methods for checkout info.@@ -650,6 +667,7 @@ def update_delivery_method_lists_for_checkout_info(lines,shipping_channel_listings,manager,+ database_connection_name=database_connection_name,)# Filter shipping methods using sync webhooksexcluded_methods = manager.excluded_shipping_methods_for_checkout(@@ -660,7 +678,11 @@ def update_delivery_method_lists_for_checkout_info(checkout_info.all_shipping_methods = lazy_no_retry(_resolve_all_shipping_methods) # type: ignore[assignment] # using lazy object breaks protocolcheckout_info.valid_pick_up_points = lazy_no_retry(- lambda: (get_valid_collection_points_for_checkout_info(lines, checkout_info))+ lambda: (+ get_valid_collection_points_for_checkout_info(+ lines, checkout_info, database_connection_name=database_connection_name+ )+ )) # type: ignore[assignment] # using lazy object breaks protocolupdate_checkout_info_delivery_method_info(checkout_info,@@ -673,11 +695,15 @@ def update_delivery_method_lists_for_checkout_info(def get_valid_collection_points_for_checkout_info(lines: Iterable[CheckoutLineInfo],checkout_info: CheckoutInfo,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):from .utils import get_valid_collection_points_for_checkoutvalid_collection_points = get_valid_collection_points_for_checkout(- lines, checkout_info.channel.id, quantity_check=False+ lines,+ checkout_info.channel.id,+ quantity_check=False,+ database_connection_name=database_connection_name,)return list(valid_collection_points)diff --git a/saleor/checkout/models.py b/saleor/checkout/models.pyindex 533e1ebe26..04011e966e 100644--- a/saleor/checkout/models.py+++ b/saleor/checkout/models.py@@ -219,11 +219,17 @@ class Checkout(models.Model):"""Return `True` if any of the lines requires shipping."""return any(line.is_shipping_required() for line in self)- def get_total_gift_cards_balance(self) -> Money:+ def get_total_gift_cards_balance(+ self, database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME+ ) -> Money:"""Return the total balance of the gift cards assigned to the checkout."""- balance = self.gift_cards.active(date=date.today()).aggregate(- models.Sum("current_balance_amount")- )["current_balance_amount__sum"]+ balance = (+ self.gift_cards.using(database_connection_name)+ .active(date=date.today())+ .aggregate(models.Sum("current_balance_amount"))[+ "current_balance_amount__sum"+ ]+ )if balance is None:return zero_money(currency=self.currency)return Money(balance, self.currency)diff --git a/saleor/checkout/payment_utils.py b/saleor/checkout/payment_utils.pyindex b92c83b812..0b2a6a9694 100644--- a/saleor/checkout/payment_utils.py+++ b/saleor/checkout/payment_utils.py@@ -3,6 +3,7 @@from collections.abc import Iterablefrom typing import Optional+from django.conf import settingsfrom django.db.models import Exists, Qfrom prices import Money@@ -84,12 +85,15 @@ def update_checkout_payment_statuses(checkout_has_lines: bool,checkout_transactions: Optional[Iterable["TransactionItem"]] = None,save: bool = True,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):current_authorize_status = checkout.authorize_statuscurrent_charge_status = checkout.charge_statusif checkout_transactions is None:- checkout_transactions = checkout.payment_transactions.all()+ checkout_transactions = checkout.payment_transactions.all().using(+ database_connection_name+ )total_authorized_amount, total_charged_amount = _get_payment_amount_for_checkout(checkout_transactions, checkout.currency)diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 614ab54745..be07aab2b7 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -559,18 +559,20 @@ def get_voucher_for_checkout(channel_slug: str,with_lock: bool = False,with_prefetch: bool = False,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> tuple[Optional[Voucher], Optional[VoucherCode]]:"""Return voucher assigned to checkout."""if checkout.voucher_code is not None:try:- code = VoucherCode.objects.get(code=checkout.voucher_code, is_active=True)+ code = VoucherCode.objects.using(database_connection_name).get(+ code=checkout.voucher_code, is_active=True+ )except VoucherCode.DoesNotExist:return None, Nonevoucher = (- Voucher.objects.active_in_channel(- date=timezone.now(), channel_slug=channel_slug- )+ Voucher.objects.using(database_connection_name)+ .active_in_channel(date=timezone.now(), channel_slug=channel_slug).filter(id=code.voucher_id).first())@@ -589,8 +591,10 @@ def get_voucher_for_checkout()if voucher.usage_limit is not None and with_lock:- code = VoucherCode.objects.select_for_update().get(- code=checkout.voucher_code+ code = (+ VoucherCode.objects.using(database_connection_name)+ .select_for_update()+ .get(code=checkout.voucher_code))return voucher, code@@ -847,13 +851,16 @@ def get_valid_internal_shipping_methods_for_checkout(subtotal: "Money",shipping_channel_listings: Iterable["ShippingMethodChannelListing"],country_code: Optional[str] = None,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> list[ShippingMethodData]:if not is_shipping_required(lines):return []if not checkout_info.shipping_address:return []- shipping_methods = ShippingMethod.objects.applicable_shipping_methods_for_instance(+ shipping_methods = ShippingMethod.objects.using(+ database_connection_name+ ).applicable_shipping_methods_for_instance(checkout_info.checkout,channel_id=checkout_info.checkout.channel_id,price=subtotal,@@ -879,6 +886,7 @@ def get_valid_collection_points_for_checkout(lines: Iterable["CheckoutLineInfo"],channel_id: int,quantity_check: bool = True,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):"""Return a collection of `Warehouse`s that can be used as a collection point.@@ -890,14 +898,16 @@ def get_valid_collection_points_for_checkout(return []line_ids = [line_info.line.id for line_info in lines]- lines = CheckoutLine.objects.filter(id__in=line_ids)+ lines = CheckoutLine.objects.using(database_connection_name).filter(id__in=line_ids)return (- Warehouse.objects.applicable_for_click_and_collect(lines, channel_id)+ Warehouse.objects.using(+ database_connection_name+ ).applicable_for_click_and_collect(lines, channel_id)if quantity_check- else Warehouse.objects.applicable_for_click_and_collect_no_quantity_check(- lines, channel_id- )+ else Warehouse.objects.using(+ database_connection_name+ ).applicable_for_click_and_collect_no_quantity_check(lines, channel_id))@@ -921,6 +931,7 @@ def is_fully_paid(manager: PluginsManager,checkout_info: "CheckoutInfo",lines: Iterable["CheckoutLineInfo"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):"""Check if provided payment methods cover the checkout's total amount.@@ -935,6 +946,7 @@ def is_fully_paid(checkout_info=checkout_info,lines=lines,address=address,+ database_connection_name=database_connection_name,)checkout_total = max(checkout_total, zero_taxed_money(checkout_total.currency)diff --git a/saleor/discount/utils.py b/saleor/discount/utils.pyindex 174042908f..cf27fb685f 100644--- a/saleor/discount/utils.py+++ b/saleor/discount/utils.py@@ -348,9 +348,12 @@ def apply_discount_to_value(def create_or_update_discount_objects_from_promotion_for_checkout(checkout_info: "CheckoutInfo",lines_info: Iterable["CheckoutLineInfo"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):create_discount_objects_for_catalogue_promotions(lines_info)- create_discount_objects_for_order_promotions(checkout_info, lines_info)+ create_discount_objects_for_order_promotions(+ checkout_info, lines_info, database_connection_name=database_connection_name+ )def create_discount_objects_for_catalogue_promotions(@@ -541,6 +544,7 @@ def create_discount_objects_for_order_promotions(lines_info: Iterable["CheckoutLineInfo"],*,save: bool = False,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):# The base prices are required for order promotion discount qualification._set_checkout_base_prices(checkout_info, lines_info)@@ -554,7 +558,7 @@ def create_discount_objects_for_order_promotions(channel = checkout_info.channelrule_data = get_best_rule_for_checkout(- checkout, channel, checkout_info.get_country()+ checkout, channel, checkout_info.get_country(), database_connection_name)if not rule_data:_clear_checkout_discount(checkout_info, lines_info, save)@@ -575,12 +579,17 @@ def create_discount_objects_for_order_promotions()-def get_best_rule_for_checkout(checkout: "Checkout", channel: "Channel", country: str):+def get_best_rule_for_checkout(+ checkout: "Checkout",+ channel: "Channel",+ country: str,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+):RuleDiscount = namedtuple("RuleDiscount", ["rule", "discount_amount", "gift_listing"])subtotal = checkout.base_subtotal- rules = fetch_promotion_rules_for_checkout(checkout)+ rules = fetch_promotion_rules_for_checkout(checkout, database_connection_name)if not rules:return@@ -598,7 +607,9 @@ def get_best_rule_for_checkout(checkout: "Checkout", channel: "Channel", countryrule_discounts.append(RuleDiscount(rule, discount_amount, None))if gift_rules:- rule, gift_listing = _get_best_gift_reward(gift_rules, channel, country)+ rule, gift_listing = _get_best_gift_reward(+ gift_rules, channel, country, database_connection_name+ )if rule and gift_listing:rule_discounts.append(RuleDiscount(rule, gift_listing.discounted_price_amount, gift_listing)@@ -669,14 +680,19 @@ def _clear_checkout_discount(def _get_best_gift_reward(- rules: Iterable["PromotionRule"], channel: "Channel", country: str+ rules: Iterable["PromotionRule"],+ channel: "Channel",+ country: str,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> tuple[Optional[PromotionRule], Optional[ProductVariantChannelListing]]:from ..warehouse.availability import check_stock_quantity_bulkrule_ids = [rule.id for rule in rules]PromotionRuleGift = PromotionRule.gifts.through- rule_gifts = PromotionRuleGift.objects.filter(promotionrule_id__in=rule_ids)- variants = ProductVariant.objects.filter(+ rule_gifts = PromotionRuleGift.objects.using(database_connection_name).filter(+ promotionrule_id__in=rule_ids+ )+ variants = ProductVariant.objects.using(database_connection_name).filter(Exists(rule_gifts.values("productvariant_id").filter(productvariant_id=OuterRef("id")@@ -694,6 +710,7 @@ def _get_best_gift_reward([1] * variants.count(),channel.slug,None,+ database_connection_name=database_connection_name,)except InsufficientStock as error:variant_ids_with_insufficient_stock = {@@ -709,13 +726,17 @@ def _get_best_gift_reward(# check if variant is available for purchaseavailable_variant_ids = _get_available_for_purchase_variant_ids(- available_variant_ids, channel+ available_variant_ids,+ channel,+ database_connection_name=database_connection_name,)if not available_variant_ids:return None, None# check variant channel availability- available_variant_listings = ProductVariantChannelListing.objects.filter(+ available_variant_listings = ProductVariantChannelListing.objects.using(+ database_connection_name+ ).filter(variant_id__in=available_variant_ids,channel_id=channel.id,price_amount__isnull=False,@@ -734,11 +755,17 @@ def _get_best_gift_reward(def _get_available_for_purchase_variant_ids(- available_variant_ids: set[int], channel: "Channel"+ available_variant_ids: set[int],+ channel: "Channel",+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):today = datetime.datetime.now(pytz.UTC)- variants = ProductVariant.objects.filter(id__in=available_variant_ids)- product_listings = ProductChannelListing.objects.filter(+ variants = ProductVariant.objects.using(database_connection_name).filter(+ id__in=available_variant_ids+ )+ product_listings = ProductChannelListing.objects.using(+ database_connection_name+ ).filter(Exists(variants.filter(product_id=OuterRef("product_id"))),available_for_purchase_at__lte=today,channel_id=channel.id,@@ -951,7 +978,9 @@ def get_variants_to_promotion_rules_map("""rules_info_per_variant: dict[int, list[PromotionRuleInfo]] = defaultdict(list)- promotions = Promotion.objects.active()+ promotions = Promotion.objects.using(+ settings.DATABASE_CONNECTION_REPLICA_NAME+ ).active()PromotionRuleVariant = PromotionRule.variants.throughpromotion_rule_variants = PromotionRuleVariant.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME@@ -986,6 +1015,7 @@ def get_variants_to_promotion_rules_map(def fetch_promotion_rules_for_checkout(checkout: Checkout,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):from ..graphql.discount.utils import PredicateObjectType, filter_qs_by_predicate@@ -995,13 +1025,19 @@ def fetch_promotion_rules_for_checkout(PromotionRuleChannels = PromotionRule.channels.through.objects.filter(channel_id=checkout_channel_id)- rules = PromotionRule.objects.filter(- Exists(promotions.filter(id=OuterRef("promotion_id"))),- Exists(PromotionRuleChannels.filter(promotionrule_id=OuterRef("id"))),- ).exclude(order_predicate={})+ rules = (+ PromotionRule.objects.using(database_connection_name)+ .filter(+ Exists(promotions.filter(id=OuterRef("promotion_id"))),+ Exists(PromotionRuleChannels.filter(promotionrule_id=OuterRef("id"))),+ )+ .exclude(order_predicate={})+ )- currency = checkout.channel.currency_code- checkout_qs = Checkout.objects.filter(pk=checkout.pk)+ currency = checkout.currency+ checkout_qs = Checkout.objects.using(database_connection_name).filter(+ pk=checkout.pk+ )for rule in rules.iterator():checkouts = filter_qs_by_predicate(rule.order_predicate,diff --git a/saleor/graphql/checkout/dataloaders.py b/saleor/graphql/checkout/dataloaders.pyindex 5805c664e2..8220bcee1c 100644--- a/saleor/graphql/checkout/dataloaders.py+++ b/saleor/graphql/checkout/dataloaders.py@@ -562,6 +562,7 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):checkout_lines,manager,shipping_method_listings,+ database_connection_name=self.database_connection_name,)checkout_info_map[key] = checkout_infodiff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.pyindex d34ecfe24f..c80c36cfb6 100644--- a/saleor/graphql/checkout/mutations/utils.py+++ b/saleor/graphql/checkout/mutations/utils.py@@ -14,6 +14,7 @@ from typing import (import grapheneimport pytz+from django.conf import settingsfrom django.core.exceptions import ObjectDoesNotExist, ValidationErrorfrom django.db import transactionfrom django.db.models import Exists, OuterRef, Q, QuerySet@@ -530,7 +531,10 @@ def find_variant_id_when_line_parameter_used(return str(line_info[0].line.variant_id)-def apply_gift_reward_if_applicable_on_checkout_creation(checkout: "Checkout") -> None:+def apply_gift_reward_if_applicable_on_checkout_creation(+ checkout: "Checkout",+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+) -> None:"""Apply gift reward if applicable on newly created checkout.This method apply the gift reward if any gift promotion exists and@@ -547,7 +551,7 @@ def apply_gift_reward_if_applicable_on_checkout_creation(checkout: "Checkout") -_set_checkout_base_subtotal_and_total_on_checkout_creation(checkout)best_rule_data = get_best_rule_for_checkout(- checkout, checkout.channel, checkout.get_country()+ checkout, checkout.channel, checkout.get_country(), database_connection_name)if not best_rule_data:returndiff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex 8b7cbf5ac8..7dc79c2d0e 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -413,7 +413,7 @@ def test_create_checkout_with_reservations(}}- with django_assert_num_queries(67):+ with django_assert_num_queries(66):response = api_client.post_graphql(query, variables)assert get_graphql_content(response)["data"]["checkoutCreate"]assert Checkout.objects.first().lines.count() == 1@@ -431,7 +431,7 @@ def test_create_checkout_with_reservations(}}- with django_assert_num_queries(67):+ with django_assert_num_queries(66):response = api_client.post_graphql(query, variables)assert get_graphql_content(response)["data"]["checkoutCreate"]assert Checkout.objects.first().lines.count() == 10@@ -817,7 +817,7 @@ def test_update_checkout_lines_with_reservations(reservation_length=5,)- with django_assert_num_queries(82):+ with django_assert_num_queries(81):variant_id = graphene.Node.to_global_id("ProductVariant", variants[0].pk)variables = {"id": to_global_id_or_none(checkout),@@ -831,7 +831,7 @@ def test_update_checkout_lines_with_reservations(assert not data["errors"]# Updating multiple lines in checkout has same query count as updating one- with django_assert_num_queries(82):+ with django_assert_num_queries(81):variables = {"id": to_global_id_or_none(checkout),"lines": [],@@ -1076,7 +1076,7 @@ def test_add_checkout_lines_with_reservations(new_lines.append({"quantity": 2, "variantId": variant_id})# Adding multiple lines to checkout has same query count as adding one- with django_assert_num_queries(81):+ with django_assert_num_queries(80):variables = {"id": Node.to_global_id("Checkout", checkout.pk),"lines": [new_lines[0]],@@ -1089,7 +1089,7 @@ def test_add_checkout_lines_with_reservations(checkout.lines.exclude(id=line.id).delete()- with django_assert_num_queries(81):+ with django_assert_num_queries(80):variables = {"id": Node.to_global_id("Checkout", checkout.pk),"lines": new_lines,@@ -1125,7 +1125,7 @@ def test_add_checkout_lines_order_discount_applies(}# when- with django_assert_num_queries(76):+ with django_assert_num_queries(75):response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)# then@@ -1159,7 +1159,7 @@ def test_add_checkout_lines_gift_discount_applies(}# when- with django_assert_num_queries(102):+ with django_assert_num_queries(101):response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)# thendiff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.pyindex 30a39871f3..9980516c7d 100644--- a/saleor/graphql/checkout/types.py+++ b/saleor/graphql/checkout/types.py@@ -13,6 +13,7 @@ from ...checkout.calculations import fetch_checkout_datafrom ...checkout.utils import get_valid_collection_points_for_checkoutfrom ...core.taxes import zero_money, zero_taxed_moneyfrom ...core.utils.lazyobjects import unwrap_lazy+from ...graphql.core.context import get_database_connection_namefrom ...payment.interface import ListStoredPaymentMethodsRequestDatafrom ...permission.auth_filters import AuthorizationFiltersfrom ...permission.enums import (@@ -288,10 +289,8 @@ class CheckoutLine(ModelObjectType[models.CheckoutLine]):)def calculate_line_unit_price(data):- (- checkout_info,- lines,- ) = data+ checkout_info, lines = data+ database_connection_name = get_database_connection_name(info.context)for line_info in lines:if line_info.line.pk == root.pk:return calculations.checkout_line_unit_price(@@ -299,6 +298,7 @@ class CheckoutLine(ModelObjectType[models.CheckoutLine]):checkout_info=checkout_info,lines=lines,checkout_line_info=line_info,+ database_connection_name=database_connection_name,)return None@@ -367,6 +367,7 @@ class CheckoutLine(ModelObjectType[models.CheckoutLine]):def calculate_line_total_price(data):(checkout_info, lines) = data+ database_connection_name = get_database_connection_name(info.context)for line_info in lines:if line_info.line.pk == root.pk:return calculations.checkout_line_total(@@ -374,6 +375,7 @@ class CheckoutLine(ModelObjectType[models.CheckoutLine]):checkout_info=checkout_info,lines=lines,checkout_line_info=line_info,+ database_connection_name=database_connection_name,)return None@@ -885,11 +887,13 @@ class Checkout(ModelObjectType[models.Checkout]):def resolve_total_price(root: models.Checkout, info: ResolveInfo):def calculate_total_price(data):address, lines, checkout_info, manager = data+ database_connection_name = get_database_connection_name(info.context)taxed_total = calculations.calculate_checkout_total_with_gift_cards(manager=manager,checkout_info=checkout_info,lines=lines,address=address,+ database_connection_name=database_connection_name,)return max(taxed_total, zero_taxed_money(root.currency))@@ -902,11 +906,13 @@ class Checkout(ModelObjectType[models.Checkout]):def resolve_subtotal_price(root: models.Checkout, info: ResolveInfo):def calculate_subtotal_price(data):address, lines, checkout_info, manager = data+ database_connection_name = get_database_connection_name(info.context)return calculations.checkout_subtotal(manager=manager,checkout_info=checkout_info,lines=lines,address=address,+ database_connection_name=database_connection_name,)dataloaders = list(get_dataloaders_for_fetching_checkout_data(root, info))@@ -918,11 +924,13 @@ class Checkout(ModelObjectType[models.Checkout]):def resolve_shipping_price(root: models.Checkout, info: ResolveInfo):def calculate_shipping_price(data):address, lines, checkout_info, manager = data+ database_connection_name = get_database_connection_name(info.context)return calculations.checkout_shipping_price(manager=manager,checkout_info=checkout_info,lines=lines,address=address,+ database_connection_name=database_connection_name,)dataloaders = list(get_dataloaders_for_fetching_checkout_data(root, info))@@ -946,7 +954,12 @@ class Checkout(ModelObjectType[models.Checkout]):@traced_resolverdef resolve_available_collection_points(root: models.Checkout, info: ResolveInfo):def get_available_collection_points(lines):- return get_valid_collection_points_for_checkout(lines, root.channel_id)+ database_connection_name = get_database_connection_name(info.context)+ return get_valid_collection_points_for_checkout(+ lines,+ root.channel_id,+ database_connection_name=database_connection_name,+ )return (CheckoutLinesInfoByCheckoutTokenLoader(info.context)@@ -1166,6 +1179,7 @@ class Checkout(ModelObjectType[models.Checkout]):def resolve_authorize_status(root: models.Checkout, info):def _resolve_authorize_status(data):address, lines, checkout_info, manager, transactions = data+ database_connection_name = get_database_connection_name(info.context)fetch_checkout_data(checkout_info=checkout_info,manager=manager,@@ -1173,6 +1187,7 @@ class Checkout(ModelObjectType[models.Checkout]):address=address,checkout_transactions=transactions,force_status_update=True,+ database_connection_name=database_connection_name,)return checkout_info.checkout.authorize_status@@ -1186,6 +1201,7 @@ class Checkout(ModelObjectType[models.Checkout]):def resolve_charge_status(root: models.Checkout, info):def _resolve_charge_status(data):address, lines, checkout_info, manager, transactions = data+ database_connection_name = get_database_connection_name(info.context)fetch_checkout_data(checkout_info=checkout_info,manager=manager,@@ -1193,6 +1209,7 @@ class Checkout(ModelObjectType[models.Checkout]):address=address,checkout_transactions=transactions,force_status_update=True,+ database_connection_name=database_connection_name,)return checkout_info.checkout.charge_status@@ -1204,6 +1221,8 @@ class Checkout(ModelObjectType[models.Checkout]):@staticmethoddef resolve_total_balance(root: models.Checkout, info):+ database_connection_name = get_database_connection_name(info.context)+def _calculate_total_balance_for_transactions(data):address, lines, checkout_info, manager, transactions = datataxed_total = calculations.calculate_checkout_total_with_gift_cards(@@ -1211,6 +1230,7 @@ class Checkout(ModelObjectType[models.Checkout]):checkout_info=checkout_info,lines=lines,address=address,+ database_connection_name=database_connection_name,)checkout_total = max(taxed_total, zero_taxed_money(root.currency))total_charged = zero_money(root.currency)diff --git a/saleor/graphql/core/utils/__init__.py b/saleor/graphql/core/utils/__init__.pyindex 6820066dc1..131429e103 100644--- a/saleor/graphql/core/utils/__init__.py+++ b/saleor/graphql/core/utils/__init__.py@@ -5,6 +5,7 @@ from dataclasses import dataclassfrom typing import Literal, Optional, Union, overloadimport graphene+from django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom graphene import ObjectTypefrom graphql.error import GraphQLError@@ -124,10 +125,15 @@ def raise_validation_error(field=None, message=None, code=None):raise ValidationError({field: ValidationError(message, code=code)})-def ext_ref_to_global_id_or_error(model, external_reference):+def ext_ref_to_global_id_or_error(+ model,+ external_reference,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+):"""Convert external reference to global id."""internal_id = (- model.objects.filter(external_reference=external_reference)+ model.objects.using(database_connection_name)+ .filter(external_reference=external_reference).values_list("id", flat=True).first())diff --git a/saleor/graphql/core/validators/__init__.py b/saleor/graphql/core/validators/__init__.pyindex 1b37760357..a1bb991459 100644--- a/saleor/graphql/core/validators/__init__.py+++ b/saleor/graphql/core/validators/__init__.py@@ -2,6 +2,7 @@ from typing import TYPE_CHECKING, Optionalfrom uuid import UUIDimport graphene+from django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom django_prices.utils.formatting import get_currency_fractionfrom graphene.utils.str_converters import to_camel_case@@ -95,13 +96,19 @@ def validate_decimal_max_value(value: "Decimal", max_value=10**9):def get_not_available_variants_in_channel(- variants_id: set, channel_id: int+ variants_id: set,+ channel_id: int,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> tuple[set[int], set[str]]:- available_variants = ProductVariantChannelListing.objects.filter(- variant__id__in=variants_id,- channel_id=channel_id,- price_amount__isnull=False,- ).values_list("variant_id", flat=True)+ available_variants = (+ ProductVariantChannelListing.objects.using(database_connection_name)+ .filter(+ variant__id__in=variants_id,+ channel_id=channel_id,+ price_amount__isnull=False,+ )+ .values_list("variant_id", flat=True)+ )not_available_variants = variants_id - set(available_variants)not_available_graphql_ids = {graphene.Node.to_global_id("ProductVariant", pk)@@ -114,12 +121,15 @@ def validate_variants_available_in_channel(variants_id: set,channel_id: int,error_code: str,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):"""Validate available variants in specific channel."""(not_available_variants,not_available_graphql_ids,- ) = get_not_available_variants_in_channel(variants_id, channel_id)+ ) = get_not_available_variants_in_channel(+ variants_id, channel_id, database_connection_name+ )if not_available_variants:raise ValidationError({diff --git a/saleor/graphql/order/schema.py b/saleor/graphql/order/schema.pyindex 5509289b8f..f697531c33 100644--- a/saleor/graphql/order/schema.py+++ b/saleor/graphql/order/schema.py@@ -8,6 +8,7 @@ from ...order import modelsfrom ...permission.enums import OrderPermissionsfrom ..core import ResolveInfofrom ..core.connection import create_connection_slice, filter_connection_queryset+from ..core.context import get_database_connection_namefrom ..core.descriptions import ADDED_IN_310, DEPRECATED_IN_3X_FIELDfrom ..core.doc_category import DOC_CATEGORY_ORDERSfrom ..core.enums import ReportingPeriod@@ -164,9 +165,12 @@ class OrderQueries(graphene.ObjectType):validate_one_of_args_is_in_query("id", id, "external_reference", external_reference)+ database_connection_name = get_database_connection_name(info.context)if not id:try:- id = ext_ref_to_global_id_or_error(models.Order, external_reference)+ id = ext_ref_to_global_id_or_error(+ models.Order, external_reference, database_connection_name+ )except ValidationError:return None_, id = from_global_id_or_error(id, Order)diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex ea099f4007..3112f2065f 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -17,6 +17,7 @@ from ...core.prices import quantize_pricefrom ...core.taxes import zero_moneyfrom ...discount import DiscountTypefrom ...graphql.checkout.types import DeliveryMethod+from ...graphql.core.context import get_database_connection_namefrom ...graphql.core.federation.entities import federated_entityfrom ...graphql.core.federation.resolvers import resolve_federation_referencesfrom ...graphql.order.resolvers import resolve_orders@@ -933,8 +934,13 @@ class OrderLine(ModelObjectType[models.OrderLine]):def resolve_unit_price(root: models.OrderLine, info):def _resolve_unit_price(data):order, lines, manager = data+ database_connection_name = get_database_connection_name(info.context)return calculations.order_line_unit(- order, root, manager, lines+ order,+ root,+ manager,+ lines,+ database_connection_name=database_connection_name,).price_with_discountsorder = OrderByIdLoader(info.context).load(root.order_id)@@ -952,8 +958,13 @@ class OrderLine(ModelObjectType[models.OrderLine]):def resolve_undiscounted_unit_price(root: models.OrderLine, info):def _resolve_undiscounted_unit_price(data):order, lines, manager = data+ database_connection_name = get_database_connection_name(info.context)return calculations.order_line_unit(- order, root, manager, lines+ order,+ root,+ manager,+ lines,+ database_connection_name=database_connection_name,).undiscounted_priceorder = OrderByIdLoader(info.context).load(root.order_id)@@ -980,8 +991,13 @@ class OrderLine(ModelObjectType[models.OrderLine]):def resolve_tax_rate(root: models.OrderLine, info):def _resolve_tax_rate(data):order, lines, manager = data+ database_connection_name = get_database_connection_name(info.context)return calculations.order_line_tax_rate(- order, root, manager, lines+ order,+ root,+ manager,+ lines,+ database_connection_name=database_connection_name,) or Decimal(0)order = OrderByIdLoader(info.context).load(root.order_id)@@ -995,8 +1011,13 @@ class OrderLine(ModelObjectType[models.OrderLine]):def resolve_total_price(root: models.OrderLine, info):def _resolve_total_price(data):order, lines, manager = data+ database_connection_name = get_database_connection_name(info.context)return calculations.order_line_total(- order, root, manager, lines+ order,+ root,+ manager,+ lines,+ database_connection_name=database_connection_name,).price_with_discountsorder = OrderByIdLoader(info.context).load(root.order_id)@@ -1010,8 +1031,13 @@ class OrderLine(ModelObjectType[models.OrderLine]):def resolve_undiscounted_total_price(root: models.OrderLine, info):def _resolve_undiscounted_total_price(data):order, lines, manager = data+ database_connection_name = get_database_connection_name(info.context)return calculations.order_line_total(- order, root, manager, lines+ order,+ root,+ manager,+ lines,+ database_connection_name=database_connection_name,).undiscounted_priceorder = OrderByIdLoader(info.context).load(root.order_id)@@ -1613,7 +1639,10 @@ class Order(ModelObjectType[models.Order]):def resolve_shipping_price(root: models.Order, info):def _resolve_shipping_price(data):lines, manager = data- return calculations.order_shipping(root, manager, lines)+ database_connection_name = get_database_connection_name(info.context)+ return calculations.order_shipping(+ root, manager, lines, database_connection_name=database_connection_name+ )lines = OrderLinesByOrderIdLoader(info.context).load(root.id)manager = get_plugin_manager_promise(info.context)@@ -1625,8 +1654,9 @@ class Order(ModelObjectType[models.Order]):def resolve_shipping_tax_rate(root: models.Order, info):def _resolve_shipping_tax_rate(data):lines, manager = data+ database_connection_name = get_database_connection_name(info.context)return calculations.order_shipping_tax_rate(- root, manager, lines+ root, manager, lines, database_connection_name=database_connection_name) or Decimal(0)lines = OrderLinesByOrderIdLoader(info.context).load(root.id)@@ -1657,7 +1687,13 @@ class Order(ModelObjectType[models.Order]):def resolve_subtotal(root: models.Order, info):def _resolve_subtotal(data):order_lines, manager = data- return calculations.order_subtotal(root, manager, order_lines)+ database_connection_name = get_database_connection_name(info.context)+ return calculations.order_subtotal(+ root,+ manager,+ order_lines,+ database_connection_name=database_connection_name,+ )order_lines = OrderLinesByOrderIdLoader(info.context).load(root.id)manager = get_plugin_manager_promise(info.context)@@ -1670,7 +1706,10 @@ class Order(ModelObjectType[models.Order]):@plugin_manager_promise_callbackdef resolve_total(root: models.Order, info, manager):def _resolve_total(lines):- return calculations.order_total(root, manager, lines)+ database_connection_name = get_database_connection_name(info.context)+ return calculations.order_total(+ root, manager, lines, database_connection_name=database_connection_name+ )return (OrderLinesByOrderIdLoader(info.context).load(root.id).then(_resolve_total)@@ -1682,7 +1721,10 @@ class Order(ModelObjectType[models.Order]):def resolve_undiscounted_total(root: models.Order, info):def _resolve_undiscounted_total(lines_and_manager):lines, manager = lines_and_manager- return calculations.order_undiscounted_total(root, manager, lines)+ database_connection_name = get_database_connection_name(info.context)+ return calculations.order_undiscounted_total(+ root, manager, lines, database_connection_name=database_connection_name+ )lines = OrderLinesByOrderIdLoader(info.context).load(root.id)manager = get_plugin_manager_promise(info.context)@@ -1880,8 +1922,14 @@ class Order(ModelObjectType[models.Order]):def _validate_draft_order(manager):country = get_order_country(root)+ database_connection_name = get_database_connection_name(info.context)try:- validate_draft_order(root, country, manager)+ validate_draft_order(+ root,+ country,+ manager,+ database_connection_name=database_connection_name,+ )except ValidationError:return Falsereturn True@@ -1995,10 +2043,14 @@ class Order(ModelObjectType[models.Order]):def resolve_shipping_methods(cls, root: models.Order, info):def with_channel(data):channel, manager = data+ database_connection_name = get_database_connection_name(info.context)def with_listings(channel_listings):return get_valid_shipping_methods_for_order(- root, channel_listings, manager+ root,+ channel_listings,+ manager,+ database_connection_name=database_connection_name,)return (@@ -2025,7 +2077,10 @@ class Order(ModelObjectType[models.Order]):@traced_resolverdef resolve_available_collection_points(cls, root: models.Order, info):def get_available_collection_points(lines):- return get_valid_collection_points_for_order(lines, root.channel_id)+ database_connection_name = get_database_connection_name(info.context)+ return get_valid_collection_points_for_order(+ lines, root.channel_id, database_connection_name+ )return cls.resolve_lines(root, info).then(get_available_collection_points)@@ -2087,8 +2142,14 @@ class Order(ModelObjectType[models.Order]):def _validate_order(manager):country = get_order_country(root)+ database_connection_name = get_database_connection_name(info.context)try:- validate_draft_order(root, country, manager)+ validate_draft_order(+ root,+ country,+ manager,+ database_connection_name=database_connection_name,+ )except ValidationError as e:return validation_error_to_error_type(e, OrderError)return []diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.pyindex 6faa54e767..53197fc0b8 100644--- a/saleor/graphql/order/utils.py+++ b/saleor/graphql/order/utils.py@@ -4,6 +4,7 @@ from decimal import Decimalfrom typing import TYPE_CHECKING, Optionalimport graphene+from django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom ...core.exceptions import InsufficientStock@@ -52,6 +53,7 @@ def get_shipping_method_availability_error(order: "Order",method: Optional["ShippingMethodData"],manager: "PluginsManager",+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):"""Validate whether shipping method is still available for the order."""is_valid = False@@ -62,6 +64,7 @@ def get_shipping_method_availability_error(order,order.channel.shipping_method_listings.all(),manager,+ database_connection_name=database_connection_name,)if m.active}@@ -75,7 +78,10 @@ def get_shipping_method_availability_error(def validate_shipping_method(- order: "Order", errors: T_ERRORS, manager: "PluginsManager"+ order: "Order",+ errors: T_ERRORS,+ manager: "PluginsManager",+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):if not order.shipping_method:error = ValidationError(@@ -110,6 +116,7 @@ def validate_shipping_method(order,convert_to_shipping_method_data(order.shipping_method, listing),manager,+ database_connection_name=database_connection_name,)if error:@@ -136,7 +143,12 @@ def validate_shipping_address(order: "Order", errors: T_ERRORS):)-def validate_order_lines(order: "Order", country: str, errors: T_ERRORS):+def validate_order_lines(+ order: "Order",+ country: str,+ errors: T_ERRORS,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+):for line in order.lines.all():if line.variant is None:errors["lines"].append(@@ -153,6 +165,7 @@ def validate_order_lines(order: "Order", country: str, errors: T_ERRORS):order.channel.slug,line.quantity,order_line=line,+ database_connection_name=database_connection_name,)except InsufficientStock as exc:errors["lines"].extend(@@ -160,23 +173,34 @@ def validate_order_lines(order: "Order", country: str, errors: T_ERRORS):)-def validate_variants_is_available(order: "Order", errors: T_ERRORS):+def validate_variants_is_available(+ order: "Order",+ errors: T_ERRORS,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+):variants_ids = {line.variant_id for line in order.lines.all()}try:validate_variants_available_in_channel(variants_ids,order.channel_id,OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.value,+ database_connection_name=database_connection_name,)except ValidationError as e:errors["lines"].extend(e.error_dict["lines"])-def validate_product_is_published(order: "Order", errors: T_ERRORS):+def validate_product_is_published(+ order: "Order",+ errors: T_ERRORS,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+):variant_ids = [line.variant_id for line in order.lines.all()]- unpublished_product = Product.objects.filter(- variants__id__in=variant_ids- ).not_published(order.channel.slug)+ unpublished_product = (+ Product.objects.using(database_connection_name)+ .filter(variants__id__in=variant_ids)+ .not_published(order.channel.slug)+ )if unpublished_product.exists():errors["lines"].append(ValidationError(@@ -187,7 +211,9 @@ def validate_product_is_published(order: "Order", errors: T_ERRORS):def validate_product_is_published_in_channel(- variants: Iterable[ProductVariant], channel: "Channel"+ variants: Iterable[ProductVariant],+ channel: "Channel",+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):if not channel:raise ValidationError(@@ -200,12 +226,16 @@ def validate_product_is_published_in_channel()variant_ids = [variant.id for variant in variants]unpublished_product = list(- Product.objects.filter(variants__id__in=variant_ids).not_published(channel.slug)+ Product.objects.using(database_connection_name)+ .filter(variants__id__in=variant_ids)+ .not_published(channel.slug))if unpublished_product:- unpublished_variants = ProductVariant.objects.filter(- product_id__in=unpublished_product, id__in=variant_ids- ).values_list("pk", flat=True)+ unpublished_variants = (+ ProductVariant.objects.using(database_connection_name)+ .filter(product_id__in=unpublished_product, id__in=variant_ids)+ .values_list("pk", flat=True)+ )unpublished_variants_global_ids = [graphene.Node.to_global_id("ProductVariant", unpublished_variant)for unpublished_variant in unpublished_variants@@ -241,15 +271,21 @@ def validate_variant_channel_listings()-def validate_product_is_available_for_purchase(order: "Order", errors: T_ERRORS):+def validate_product_is_available_for_purchase(+ order: "Order",+ errors: T_ERRORS,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+):invalid_lines = []for line in order.lines.all():variant = line.variantif not variant:continue- product_channel_listing = ProductChannelListing.objects.filter(- channel_id=order.channel_id, product_id=variant.product_id- ).first()+ product_channel_listing = (+ ProductChannelListing.objects.using(database_connection_name)+ .filter(channel_id=order.channel_id, product_id=variant.product_id)+ .first()+ )if not (product_channel_listingand product_channel_listing.is_available_for_purchase()@@ -288,7 +324,12 @@ def _validate_voucher(order: "Order", errors: T_ERRORS):)-def validate_draft_order(order: "Order", country: str, manager: "PluginsManager"):+def validate_draft_order(+ order: "Order",+ country: str,+ manager: "PluginsManager",+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+):"""Check if the given order contains the proper data.- Has proper customer data,@@ -304,13 +345,13 @@ def validate_draft_order(order: "Order", country: str, manager: "PluginsManager"validate_billing_address(order, errors)if order.is_shipping_required():validate_shipping_address(order, errors)- validate_shipping_method(order, errors, manager)+ validate_shipping_method(order, errors, manager, database_connection_name)validate_total_quantity(order, errors)- validate_order_lines(order, country, errors)+ validate_order_lines(order, country, errors, database_connection_name)validate_channel_is_active(order.channel, errors)- validate_product_is_published(order, errors)- validate_product_is_available_for_purchase(order, errors)- validate_variants_is_available(order, errors)+ validate_product_is_published(order, errors, database_connection_name)+ validate_product_is_available_for_purchase(order, errors, database_connection_name)+ validate_variants_is_available(order, errors, database_connection_name)_validate_voucher(order, errors)if errors:diff --git a/saleor/graphql/shop/resolvers.py b/saleor/graphql/shop/resolvers.pyindex d62a2e05c6..ff0a7b4849 100644--- a/saleor/graphql/shop/resolvers.py+++ b/saleor/graphql/shop/resolvers.py@@ -14,9 +14,9 @@ from .utils import get_countries_codes_list@traced_resolverdef resolve_available_shipping_methods(info, *, channel_slug: str, address):instances = []- available = ShippingMethod.objects.for_channel(channel_slug).using(+ available = ShippingMethod.objects.using(get_database_connection_name(info.context)- )+ ).for_channel(channel_slug)if address and address.country:available = available.filter(shipping_zone__countries__contains=address.country,diff --git a/saleor/graphql/webhook/resolvers.py b/saleor/graphql/webhook/resolvers.pyindex 6f93c62369..c4f49e29ff 100644--- a/saleor/graphql/webhook/resolvers.py+++ b/saleor/graphql/webhook/resolvers.py@@ -1,3 +1,4 @@+from django.conf import settingsfrom django.db.models import Exists, OuterRef, Qfrom ...app.models import App@@ -61,7 +62,12 @@ def resolve_sample_payload(info: ResolveInfo, event_name, app):raise PermissionDenied(permissions=[required_permission])-def resolve_shipping_methods_for_checkout(info: ResolveInfo, checkout, manager):+def resolve_shipping_methods_for_checkout(+ info: ResolveInfo,+ checkout,+ manager,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+):lines, _ = fetch_checkout_lines(checkout)shipping_channel_listings = checkout.channel.shipping_method_listings.all()checkout_info = fetch_checkout_info(@@ -70,6 +76,7 @@ def resolve_shipping_methods_for_checkout(info: ResolveInfo, checkout, manager):manager,shipping_channel_listings,fetch_delivery_methods=False,+ database_connection_name=database_connection_name,)all_shipping_methods = get_all_shipping_methods_list(checkout_info,@@ -77,5 +84,6 @@ def resolve_shipping_methods_for_checkout(info: ResolveInfo, checkout, manager):lines,shipping_channel_listings,manager,+ database_connection_name=database_connection_name,)return all_shipping_methodsdiff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.pyindex ace7ca3131..dd52f318d8 100644--- a/saleor/graphql/webhook/subscription_types.py+++ b/saleor/graphql/webhook/subscription_types.py@@ -2568,7 +2568,10 @@ class ShippingListMethodsForCheckout(SubscriptionObjectType, CheckoutBase):@plugin_manager_promise_callbackdef resolve_shipping_methods(root, info: ResolveInfo, manager):_, checkout = root- return resolve_shipping_methods_for_checkout(info, checkout, manager)+ database_connection_name = get_database_connection_name(info.context)+ return resolve_shipping_methods_for_checkout(+ info, checkout, manager, database_connection_name+ )class Meta:root_type = None@@ -2609,7 +2612,10 @@ class CheckoutFilterShippingMethods(SubscriptionObjectType, CheckoutBase):@plugin_manager_promise_callbackdef resolve_shipping_methods(root, info: ResolveInfo, manager):_, checkout = root- return resolve_shipping_methods_for_checkout(info, checkout, manager)+ database_connection_name = get_database_connection_name(info.context)+ return resolve_shipping_methods_for_checkout(+ info, checkout, manager, database_connection_name+ )class Meta:root_type = Nonediff --git a/saleor/order/base_calculations.py b/saleor/order/base_calculations.pyindex aacae01001..219b77f2c8 100644--- a/saleor/order/base_calculations.py+++ b/saleor/order/base_calculations.py@@ -1,6 +1,7 @@from collections.abc import Iterablefrom typing import TYPE_CHECKING, Optional+from django.conf import settingsfrom prices import Money, TaxedMoneyfrom ..core.prices import quantize_price@@ -37,12 +38,21 @@ def base_order_subtotal(order: "Order", lines: Iterable["OrderLine"]) -> Money:return quantize_price(subtotal, currency)-def base_order_total(order: "Order", lines: Iterable["OrderLine"]) -> Money:+def base_order_total(+ order: "Order",+ lines: Iterable["OrderLine"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+) -> Money:"""Return order total, recalculate, and update order discounts.All discounts are included in this price."""- subtotal, shipping_price = apply_order_discounts(order, lines, assign_prices=False)+ subtotal, shipping_price = apply_order_discounts(+ order,+ lines,+ assign_prices=False,+ database_connection_name=database_connection_name,+ )return subtotal + shipping_price@@ -147,6 +157,7 @@ def apply_order_discounts(order: "Order",lines: Iterable["OrderLine"],assign_prices=True,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> tuple[Money, Money]:"""Calculate prices after applying order level discounts.@@ -168,6 +179,7 @@ def apply_order_discounts(lines,subtotal,shipping_price,+ database_connection_name=database_connection_name,)subtotal_discount = base_subtotal - subtotalapply_subtotal_discount_to_order_lines(lines, base_subtotal, subtotal_discount)@@ -284,6 +296,7 @@ def assign_order_prices(lines: Iterable["OrderLine"],subtotal: Money,shipping_price: Money,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):order.shipping_price_net_amount = shipping_price.amountorder.shipping_price_gross_amount = shipping_price.amount@@ -293,19 +306,28 @@ def assign_order_prices(order.subtotal_net_amount = subtotal.amountorder.subtotal_gross_amount = subtotal.amount- undiscounted_total = undiscounted_order_total(order, lines)+ undiscounted_total = undiscounted_order_total(+ order, lines, database_connection_name=database_connection_name+ )order.undiscounted_total_net_amount = undiscounted_total.amountorder.undiscounted_total_gross_amount = undiscounted_total.amount-def undiscounted_order_shipping(order: "Order") -> Money:+def undiscounted_order_shipping(+ order: "Order",+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+) -> Money:"""Return shipping price without any discounts."""# TODO: add undiscounted_shipping_price field to order model.# https://github.com/saleor/saleor/issues/14915if shipping_method := order.shipping_method:- if listing := ShippingMethodChannelListing.objects.filter(- channel=order.channel, shipping_method=shipping_method- ).first():+ if (+ listing := ShippingMethodChannelListing.objects.using(+ database_connection_name+ )+ .filter(channel=order.channel, shipping_method=shipping_method)+ .first()+ ):return Money(listing.price_amount, order.currency)return zero_money(order.currency)@@ -320,8 +342,14 @@ def undiscounted_order_subtotal(order: "Order", lines: Iterable["OrderLine"]) ->return quantize_price(subtotal, currency)-def undiscounted_order_total(order: "Order", lines: Iterable["OrderLine"]) -> Money:+def undiscounted_order_total(+ order: "Order",+ lines: Iterable["OrderLine"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+) -> Money:"""Return order total without any discounts."""subtotal = undiscounted_order_subtotal(order, lines)- shipping_price = undiscounted_order_shipping(order)+ shipping_price = undiscounted_order_shipping(+ order, database_connection_name=database_connection_name+ )return quantize_price(subtotal + shipping_price, order.currency)diff --git a/saleor/order/calculations.py b/saleor/order/calculations.pyindex fffc936b7d..8d649bd324 100644--- a/saleor/order/calculations.py+++ b/saleor/order/calculations.py@@ -2,6 +2,7 @@ from collections.abc import Iterablefrom decimal import Decimalfrom typing import Optional+from django.conf import settingsfrom django.db import transactionfrom django.db.models import prefetch_related_objectsfrom prices import Money, TaxedMoney@@ -32,6 +33,7 @@ def fetch_order_prices_if_expired(manager: PluginsManager,lines: Optional[Iterable[OrderLine]] = None,force_update: bool = False,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> tuple[Order, Optional[Iterable[OrderLine]]]:"""Fetch order prices with taxes.@@ -47,14 +49,20 @@ def fetch_order_prices_if_expired(return order, linesif lines is None:- lines = list(order.lines.select_related("variant__product__product_type"))+ lines = list(+ order.lines.using(database_connection_name).select_related(+ "variant__product__product_type"+ )+ )else:prefetch_related_objects(lines, "variant__product__product_type")order.should_refresh_prices = False_update_order_discount_for_voucher(order)- _recalculate_prices(order, manager, lines)+ _recalculate_prices(+ order, manager, lines, database_connection_name=database_connection_name+ )order.subtotal = get_subtotal(lines, order.currency)with transaction.atomic(savepoint=False):@@ -128,6 +136,7 @@ def _recalculate_prices(order: Order,manager: PluginsManager,lines: Iterable[OrderLine],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):"""Calculate prices after handling order level discounts and taxes."""tax_configuration = order.channel.tax_configuration@@ -140,7 +149,12 @@ def _recalculate_prices(order.tax_error = None# propagate the order level discount on the prices without taxes.- apply_order_discounts(order, lines, assign_prices=True)+ apply_order_discounts(+ order,+ lines,+ assign_prices=True,+ database_connection_name=database_connection_name,+ )if prices_entered_with_tax:# If prices are entered with tax, we need to always calculate it anyway, to# display the tax rate to the user.@@ -152,6 +166,7 @@ def _recalculate_prices(lines,manager,prices_entered_with_tax,+ database_connection_name=database_connection_name,)except TaxEmptyData as e:order.tax_error = str(e)@@ -174,6 +189,7 @@ def _recalculate_prices(lines,manager,prices_entered_with_tax,+ database_connection_name=database_connection_name,)except TaxEmptyData as e:order.tax_error = str(e)@@ -188,6 +204,7 @@ def _calculate_and_add_tax(lines: Iterable["OrderLine"],manager: "PluginsManager",prices_entered_with_tax: bool,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):if tax_calculation_strategy == TaxCalculationStrategy.TAX_APP:# If taxAppId is not configured run all active plugins and tax apps.@@ -209,7 +226,12 @@ def _calculate_and_add_tax()else:# Get taxes calculated with flat rates and apply to order.- update_order_prices_with_flat_rates(order, lines, prices_entered_with_tax)+ update_order_prices_with_flat_rates(+ order,+ lines,+ prices_entered_with_tax,+ database_connection_name=database_connection_name,+ )def _call_plugin_or_tax_app(@@ -399,6 +421,7 @@ def order_line_unit(manager: PluginsManager,lines: Optional[Iterable[OrderLine]] = None,force_update: bool = False,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> OrderTaxedPricesData:"""Return the unit price of provided line, taxes included.@@ -407,7 +430,13 @@ def order_line_unit(and save them in the model directly."""currency = order.currency- _, lines = fetch_order_prices_if_expired(order, manager, lines, force_update)+ _, lines = fetch_order_prices_if_expired(+ order,+ manager,+ lines,+ force_update,+ database_connection_name=database_connection_name,+ )order_line = _find_order_line(lines, order_line)return OrderTaxedPricesData(undiscounted_price=quantize_price(order_line.undiscounted_unit_price, currency),@@ -421,6 +450,7 @@ def order_line_total(manager: PluginsManager,lines: Optional[Iterable[OrderLine]] = None,force_update: bool = False,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> OrderTaxedPricesData:"""Return the total price of provided line, taxes included.@@ -429,7 +459,13 @@ def order_line_total(and save them in the model directly."""currency = order.currency- _, lines = fetch_order_prices_if_expired(order, manager, lines, force_update)+ _, lines = fetch_order_prices_if_expired(+ order,+ manager,+ lines,+ force_update,+ database_connection_name=database_connection_name,+ )order_line = _find_order_line(lines, order_line)return OrderTaxedPricesData(undiscounted_price=quantize_price(@@ -445,6 +481,7 @@ def order_line_tax_rate(manager: PluginsManager,lines: Optional[Iterable[OrderLine]] = None,force_update: bool = False,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> Optional[Decimal]:"""Return the tax rate of provided line.@@ -452,7 +489,13 @@ def order_line_tax_rate(If the prices are expired, call all order price calculation methodsand save them in the model directly."""- _, lines = fetch_order_prices_if_expired(order, manager, lines, force_update)+ _, lines = fetch_order_prices_if_expired(+ order,+ manager,+ lines,+ force_update,+ database_connection_name=database_connection_name,+ )order_line = _find_order_line(lines, order_line)return order_line.tax_rate@@ -462,6 +505,7 @@ def order_shipping(manager: PluginsManager,lines: Optional[Iterable[OrderLine]] = None,force_update: bool = False,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> TaxedMoney:"""Return the shipping price of the order.@@ -470,7 +514,13 @@ def order_shipping(and save them in the model directly."""currency = order.currency- order, _ = fetch_order_prices_if_expired(order, manager, lines, force_update)+ order, _ = fetch_order_prices_if_expired(+ order,+ manager,+ lines,+ force_update,+ database_connection_name=database_connection_name,+ )return quantize_price(order.shipping_price, currency)@@ -479,6 +529,7 @@ def order_shipping_tax_rate(manager: PluginsManager,lines: Optional[Iterable[OrderLine]] = None,force_update: bool = False,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> Optional[Decimal]:"""Return the shipping tax rate of the order.@@ -486,15 +537,22 @@ def order_shipping_tax_rate(If the prices are expired, call all order price calculation methodsand save them in the model directly."""- order, _ = fetch_order_prices_if_expired(order, manager, lines, force_update)+ order, _ = fetch_order_prices_if_expired(+ order,+ manager,+ lines,+ force_update,+ database_connection_name=database_connection_name,+ )return order.shipping_tax_ratedef order_subtotal(order: Order,manager: PluginsManager,- lines: Iterable[OrderLine],+ lines: Optional[Iterable[OrderLine]] = None,force_update: bool = False,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):"""Return the total price of the order.@@ -503,7 +561,13 @@ def order_subtotal(and save them in the model directly."""currency = order.currency- order, lines = fetch_order_prices_if_expired(order, manager, lines, force_update)+ order, lines = fetch_order_prices_if_expired(+ order,+ manager,+ lines,+ force_update,+ database_connection_name=database_connection_name,+ )# Lines aren't returned only if# we don't pass them to `fetch_order_prices_if_expired`.return quantize_price(order.subtotal, currency)@@ -514,6 +578,7 @@ def order_total(manager: PluginsManager,lines: Optional[Iterable[OrderLine]] = None,force_update: bool = False,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> TaxedMoney:"""Return the total price of the order.@@ -522,7 +587,13 @@ def order_total(and save them in the model directly."""currency = order.currency- order, _ = fetch_order_prices_if_expired(order, manager, lines, force_update)+ order, _ = fetch_order_prices_if_expired(+ order,+ manager,+ lines,+ force_update,+ database_connection_name=database_connection_name,+ )return quantize_price(order.total, currency)@@ -531,6 +602,7 @@ def order_undiscounted_total(manager: PluginsManager,lines: Optional[Iterable[OrderLine]] = None,force_update: bool = False,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> TaxedMoney:"""Return the undiscounted total price of the order.@@ -539,5 +611,11 @@ def order_undiscounted_total(and save them in the model directly."""currency = order.currency- order, _ = fetch_order_prices_if_expired(order, manager, lines, force_update)+ order, _ = fetch_order_prices_if_expired(+ order,+ manager,+ lines,+ force_update,+ database_connection_name=database_connection_name,+ )return quantize_price(order.undiscounted_total, currency)diff --git a/saleor/order/tests/test_calculations.py b/saleor/order/tests/test_calculations.pyindex 117268c864..f2c0c78b76 100644--- a/saleor/order/tests/test_calculations.py+++ b/saleor/order/tests/test_calculations.py@@ -651,7 +651,10 @@ def test_fetch_order_prices_if_expired_flat_rates(# thenmocked_update_order_prices_with_flat_rates.assert_called_once_with(- order, list(order.lines.all()), prices_entered_with_tax+ order,+ list(order.lines.all()),+ prices_entered_with_tax,+ database_connection_name=order.lines.db,)assert line.tax_rate == Decimal("0.2300")assert order.shipping_tax_rate == Decimal("0.2300")diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 5fa2ea5227..ed0317155c 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -3,6 +3,7 @@ from decimal import Decimalfrom functools import wrapsfrom typing import TYPE_CHECKING, Optional, cast+from django.conf import settingsfrom django.db.models import QuerySet, Sumfrom django.utils import timezonefrom prices import Money, TaxedMoney@@ -605,6 +606,7 @@ def sum_order_totals(qs, currency_code):def get_all_shipping_methods_for_order(order: Order,shipping_channel_listings: Iterable["ShippingMethodChannelListing"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> list[ShippingMethodData]:if not order.is_shipping_required():return []@@ -614,12 +616,16 @@ def get_all_shipping_methods_for_order(all_methods = []- shipping_methods = ShippingMethod.objects.applicable_shipping_methods_for_instance(- order,- channel_id=order.channel_id,- price=order.subtotal.gross,- country_code=order.shipping_address.country.code,- ).prefetch_related("channel_listings")+ shipping_methods = (+ ShippingMethod.objects.using(database_connection_name)+ .applicable_shipping_methods_for_instance(+ order,+ channel_id=order.channel_id,+ price=order.subtotal.gross,+ country_code=order.shipping_address.country.code,+ )+ .prefetch_related("channel_listings")+ )listing_map = {listing.shipping_method_id: listing for listing in shipping_channel_listings@@ -637,9 +643,12 @@ def get_valid_shipping_methods_for_order(order: Order,shipping_channel_listings: Iterable["ShippingMethodChannelListing"],manager: "PluginsManager",+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> list[ShippingMethodData]:"""Return a list of shipping methods according to Saleor's own business logic."""- valid_methods = get_all_shipping_methods_for_order(order, shipping_channel_listings)+ valid_methods = get_all_shipping_methods_for_order(+ order, shipping_channel_listings, database_connection_name+ )if not valid_methods:return []@@ -654,15 +663,19 @@ def is_shipping_required(lines: Iterable["OrderLine"]):def get_valid_collection_points_for_order(- lines: Iterable["OrderLine"], channel_id: int+ lines: Iterable["OrderLine"],+ channel_id: int,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):if not is_shipping_required(lines):return []line_ids = [line.id for line in lines]- qs = OrderLine.objects.filter(id__in=line_ids)+ qs = OrderLine.objects.using(database_connection_name).filter(id__in=line_ids)- return Warehouse.objects.applicable_for_click_and_collect(qs, channel_id)+ return Warehouse.objects.using(+ database_connection_name+ ).applicable_for_click_and_collect(qs, channel_id)def get_discounted_lines(lines, voucher):diff --git a/saleor/plugins/webhook/tests/test_tax_webhook.py b/saleor/plugins/webhook/tests/test_tax_webhook.pyindex ae14d26619..e945c33563 100644--- a/saleor/plugins/webhook/tests/test_tax_webhook.py+++ b/saleor/plugins/webhook/tests/test_tax_webhook.py@@ -29,7 +29,9 @@ def test_get_taxes_for_checkout_no_permission(# givenplugin = webhook_plugin()lines, _ = fetch_checkout_lines(checkout)- checkout_info = fetch_checkout_info(checkout, lines, plugin)+ checkout_info = fetch_checkout_info(+ checkout, lines, get_plugins_manager(allow_replica=False)+ )app_identifier = None# whendiff --git a/saleor/product/managers.py b/saleor/product/managers.pyindex c9685cc5d4..952839af6c 100644--- a/saleor/product/managers.py+++ b/saleor/product/managers.py@@ -2,7 +2,6 @@ import datetimefrom typing import Optional, Unionimport pytz-from django.conf import settingsfrom django.contrib.postgres.aggregates import StringAggfrom django.db import modelsfrom django.db.models import (@@ -34,15 +33,19 @@ class ProductsQueryset(models.QuerySet):today = datetime.datetime.now(pytz.UTC)if channel := (- Channel.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ Channel.objects.using(self.db).filter(slug=str(channel_slug), is_active=True).first()):- channel_listings = ProductChannelListing.objects.filter(- Q(published_at__lte=today) | Q(published_at__isnull=True),- channel_id=channel.id,- is_published=True,- ).values("id")+ channel_listings = (+ ProductChannelListing.objects.using(self.db)+ .filter(+ Q(published_at__lte=today) | Q(published_at__isnull=True),+ channel_id=channel.id,+ is_published=True,+ )+ .values("id")+ )return self.filter(Exists(channel_listings.filter(product_id=OuterRef("pk"))))@@ -60,13 +63,19 @@ class ProductsQueryset(models.QuerySet):from .models import ProductVariant, ProductVariantChannelListingif channel := (- Channel.objects.filter(slug=str(channel_slug), is_active=True).first()+ Channel.objects.using(self.db)+ .filter(slug=str(channel_slug), is_active=True)+ .first()):- variant_channel_listings = ProductVariantChannelListing.objects.filter(- channel_id=channel.id,- price_amount__isnull=False,- ).values("id")- variants = ProductVariant.objects.filter(+ variant_channel_listings = (+ ProductVariantChannelListing.objects.using(self.db)+ .filter(+ channel_id=channel.id,+ price_amount__isnull=False,+ )+ .values("id")+ )+ variants = ProductVariant.objects.using(self.db).filter(Exists(variant_channel_listings.filter(variant_id=OuterRef("pk"))))return self.published(channel_slug).filter(@@ -81,10 +90,17 @@ class ProductsQueryset(models.QuerySet):if has_one_of_permissions(requestor, ALL_PRODUCTS_PERMISSIONS):if channel_slug:- if channel := Channel.objects.filter(slug=str(channel_slug)).first():- channel_listings = ProductChannelListing.objects.filter(- channel_id=channel.id- ).values("id")+ channel = (+ Channel.objects.using(self.db)+ .filter(slug=str(channel_slug))+ .first()+ )+ if channel:+ channel_listings = (+ ProductChannelListing.objects.using(self.db)+ .filter(channel_id=channel.id)+ .values("id")+ )return self.filter(Exists(channel_listings.filter(product_id=OuterRef("pk"))))@@ -103,9 +119,9 @@ class ProductsQueryset(models.QuerySet):from .models import ProductChannelListingquery = Subquery(- ProductChannelListing.objects.filter(- product_id=OuterRef("pk"), channel__slug=str(channel_slug)- ).values_list("is_published")[:1]+ ProductChannelListing.objects.using(self.db)+ .filter(product_id=OuterRef("pk"), channel__slug=str(channel_slug))+ .values_list("is_published")[:1])return self.annotate(is_published=ExpressionWrapper(query, output_field=BooleanField())@@ -115,9 +131,9 @@ class ProductsQueryset(models.QuerySet):from .models import ProductChannelListingquery = Subquery(- ProductChannelListing.objects.filter(- product_id=OuterRef("pk"), channel__slug=str(channel_slug)- ).values_list("published_at")[:1]+ ProductChannelListing.objects.using(self.db)+ .filter(product_id=OuterRef("pk"), channel__slug=str(channel_slug))+ .values_list("published_at")[:1])return self.annotate(published_at=ExpressionWrapper(query, output_field=DateTimeField())@@ -127,9 +143,9 @@ class ProductsQueryset(models.QuerySet):from .models import ProductChannelListingquery = Subquery(- ProductChannelListing.objects.filter(- product_id=OuterRef("pk"), channel__slug=str(channel_slug)- ).values_list("visible_in_listings")[:1]+ ProductChannelListing.objects.using(self.db)+ .filter(product_id=OuterRef("pk"), channel__slug=str(channel_slug))+ .values_list("visible_in_listings")[:1])return self.annotate(visible_in_listings=ExpressionWrapper(query, output_field=BooleanField())@@ -170,13 +186,13 @@ class ProductsQueryset(models.QuerySet):# then consider the concatenated values as empty (non-null).When(Exists(- AttributeProduct.objects.filter(+ AttributeProduct.objects.using(self.db).filter(product_type_id=OuterRef("product_type_id"),attribute_id=attribute_pk,))& ~Exists(- AssignedProductAttributeValue.objects.filter(+ AssignedProductAttributeValue.objects.using(self.db).filter(product_id=OuterRef("id"), value__attribute_id=attribute_pk)),@@ -253,7 +269,8 @@ class ProductVariantQueryset(models.QuerySet):from saleor.warehouse.models import Allocationallocations_subquery = (- Allocation.objects.filter(stock__product_variant=OuterRef("pk"))+ Allocation.objects.using(self.db)+ .filter(stock__product_variant=OuterRef("pk")).values("stock__product_variant").annotate(total_allocated=Coalesce(Sum("quantity_allocated"), 0)).values("total_allocated")diff --git a/saleor/product/utils/variant_prices.py b/saleor/product/utils/variant_prices.pyindex 23a970435a..141af70eb5 100644--- a/saleor/product/utils/variant_prices.py+++ b/saleor/product/utils/variant_prices.py@@ -38,9 +38,9 @@ def update_discounted_prices_for_promotion(When only_dirty_products set to True, the prices will be recalculated only for thelistings marked as dirty."""- variant_qs = ProductVariant.objects.filter(- Exists(products.filter(id=OuterRef("product_id")))- )+ variant_qs = ProductVariant.objects.using(+ settings.DATABASE_CONNECTION_REPLICA_NAME+ ).filter(Exists(products.filter(id=OuterRef("product_id"))))rules_info_per_variant = get_variants_to_promotion_rules_map(variant_qs)product_to_variant_listings_per_channel_map = (_get_product_to_variant_channel_listings_per_channel_map(variant_qs)diff --git a/saleor/shipping/models.py b/saleor/shipping/models.pyindex a9dec0da8f..996aed4275 100644--- a/saleor/shipping/models.py+++ b/saleor/shipping/models.py@@ -42,7 +42,12 @@ def _applicable_weight_based_methods(weight, qs):return qs.filter(min_weight_matched & max_weight_matched)-def _applicable_price_based_methods(price: Money, qs, channel_id):+def _applicable_price_based_methods(+ price: Money,+ qs,+ channel_id,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+):"""Return price based shipping methods that are applicable for the given total."""qs_shipping_method = qs.price_based()@@ -53,12 +58,16 @@ def _applicable_price_based_methods(price: Money, qs, channel_id):no_price_limit = Q(maximum_order_price_amount__isnull=True)max_price_matched = Q(maximum_order_price_amount__gte=price.amount)- applicable_price_based_methods = ShippingMethodChannelListing.objects.filter(- channel_filter- & price_based- & (min_price_is_null | min_price_matched)- & (no_price_limit | max_price_matched)- ).values_list("shipping_method__id", flat=True)+ applicable_price_based_methods = (+ ShippingMethodChannelListing.objects.using(database_connection_name)+ .filter(+ channel_filter+ & price_based+ & (min_price_is_null | min_price_matched)+ & (no_price_limit | max_price_matched)+ )+ .values_list("shipping_method__id", flat=True)+ )return qs_shipping_method.filter(id__in=applicable_price_based_methods)@@ -104,11 +113,12 @@ class ShippingMethodQueryset(models.QuerySet["ShippingMethod"]):channel_listings__channel__slug=channel_slug,)- @staticmethod- def applicable_shipping_methods_by_channel(shipping_methods, channel_id):- query = ShippingMethodChannelListing.objects.filter(- shipping_method=OuterRef("pk"), channel_id=channel_id- ).values_list("price_amount")+ def applicable_shipping_methods_by_channel(self, shipping_methods, channel_id):+ query = (+ ShippingMethodChannelListing.objects.using(self.db)+ .filter(shipping_method=OuterRef("pk"), channel_id=channel_id)+ .values_list("price_amount")+ )return shipping_methods.annotate(price_amount=Subquery(query)).order_by("price_amount")@@ -142,7 +152,9 @@ class ShippingMethodQueryset(models.QuerySet["ShippingMethod"]):if product_ids:qs = self.exclude_shipping_methods_for_excluded_products(qs, product_ids)- price_based_methods = _applicable_price_based_methods(price, qs, channel_id)+ price_based_methods = _applicable_price_based_methods(+ price, qs, channel_id, database_connection_name=self.db+ )weight_based_methods = _applicable_weight_based_methods(weight, qs)shipping_methods = price_based_methods | weight_based_methodsdiff --git a/saleor/tax/calculations/checkout.py b/saleor/tax/calculations/checkout.pyindex 15b80ff83e..266b8d1c26 100644--- a/saleor/tax/calculations/checkout.py+++ b/saleor/tax/calculations/checkout.py@@ -2,6 +2,7 @@ from collections.abc import Iterablefrom decimal import Decimalfrom typing import TYPE_CHECKING, Optional+from django.conf import settingsfrom prices import TaxedMoneyfrom ...checkout import base_calculations@@ -24,11 +25,14 @@ def update_checkout_prices_with_flat_rates(lines: Iterable["CheckoutLineInfo"],prices_entered_with_tax: bool,address: Optional["Address"] = None,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):country_code = get_active_country(checkout_info.channel, address)- default_country_rate_obj = TaxClassCountryRate.objects.filter(- country=country_code, tax_class=None- ).first()+ default_country_rate_obj = (+ TaxClassCountryRate.objects.using(database_connection_name)+ .filter(country=country_code, tax_class=None)+ .first()+ )default_tax_rate = (default_country_rate_obj.rate if default_country_rate_obj else Decimal(0))diff --git a/saleor/tax/calculations/order.py b/saleor/tax/calculations/order.pyindex 6bf33f2425..dfa1a0b022 100644--- a/saleor/tax/calculations/order.py+++ b/saleor/tax/calculations/order.py@@ -2,6 +2,7 @@ from collections.abc import Iterablefrom decimal import Decimalfrom typing import TYPE_CHECKING+from django.conf import settingsfrom prices import TaxedMoneyfrom ...core.prices import quantize_price@@ -24,6 +25,7 @@ def update_order_prices_with_flat_rates(order: "Order",lines: Iterable["OrderLine"],prices_entered_with_tax: bool,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):country_code = get_order_country(order)default_country_rate_obj = TaxClassCountryRate.objects.filter(@@ -66,16 +68,21 @@ def update_order_prices_with_flat_rates(# Calculate order total.order.undiscounted_total = undiscounted_subtotal + order.base_shipping_price- order.total = _calculate_order_total(order, lines)+ order.total = _calculate_order_total(+ order, lines, database_connection_name=database_connection_name+ )def _calculate_order_total(order: "Order",lines: Iterable["OrderLine"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> TaxedMoney:currency = order.currency- default_value = base_calculations.base_order_total(order, lines)+ default_value = base_calculations.base_order_total(+ order, lines, database_connection_name=database_connection_name+ )default_value = TaxedMoney(default_value, default_value)if default_value <= zero_taxed_money(currency):return quantize_price(default_value, currency)diff --git a/saleor/tax/utils.py b/saleor/tax/utils.pyindex 66283df9a2..86a6d80d13 100644--- a/saleor/tax/utils.py+++ b/saleor/tax/utils.py@@ -2,6 +2,7 @@ from collections.abc import Iterablefrom decimal import Decimalfrom typing import TYPE_CHECKING, Optional+from django.conf import settingsfrom prices import TaxedMoneyfrom ..core.utils.country import get_active_country@@ -128,7 +129,9 @@ def get_tax_app_identifier_for_order(order: "Order"):def _get_tax_configuration_for_checkout(- checkout_info: "CheckoutInfo", lines: Iterable["CheckoutLineInfo"]+ checkout_info: "CheckoutInfo",+ lines: Iterable["CheckoutLineInfo"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> tuple["TaxConfiguration", Optional["TaxConfigurationPerCountry"]]:tax_configuration = checkout_info.tax_configurationcountry_code = get_active_country(@@ -139,7 +142,9 @@ def _get_tax_configuration_for_checkout(country_tax_configuration = next((tc- for tc in tax_configuration.country_exceptions.all()+ for tc in tax_configuration.country_exceptions.using(+ database_connection_name+ ).all()if tc.country.code == country_code),None,@@ -148,31 +153,37 @@ def _get_tax_configuration_for_checkout(def get_charge_taxes_for_checkout(- checkout_info: "CheckoutInfo", lines: Iterable["CheckoutLineInfo"]+ checkout_info: "CheckoutInfo",+ lines: Iterable["CheckoutLineInfo"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):"""Get charge_taxes value for checkout."""tax_configuration, country_tax_configuration = _get_tax_configuration_for_checkout(- checkout_info, lines+ checkout_info, lines, database_connection_name=database_connection_name)return get_charge_taxes(tax_configuration, country_tax_configuration)def get_tax_calculation_strategy_for_checkout(- checkout_info: "CheckoutInfo", lines: Iterable["CheckoutLineInfo"]+ checkout_info: "CheckoutInfo",+ lines: Iterable["CheckoutLineInfo"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):"""Get tax_calculation_strategy value for checkout."""tax_configuration, country_tax_configuration = _get_tax_configuration_for_checkout(- checkout_info, lines+ checkout_info, lines, database_connection_name=database_connection_name)return get_tax_calculation_strategy(tax_configuration, country_tax_configuration)def get_tax_app_identifier_for_checkout(- checkout_info: "CheckoutInfo", lines: Iterable["CheckoutLineInfo"]+ checkout_info: "CheckoutInfo",+ lines: Iterable["CheckoutLineInfo"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):"""Get tax_app_id value for checkout."""tax_configuration, country_tax_configuration = _get_tax_configuration_for_checkout(- checkout_info, lines+ checkout_info, lines, database_connection_name=database_connection_name)return get_tax_app_id(tax_configuration, country_tax_configuration)diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.pyindex f97bfc79bf..41e87434ec 100644--- a/saleor/warehouse/availability.py+++ b/saleor/warehouse/availability.py@@ -8,6 +8,7 @@ from typing import (Optional,)+from django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom django.db.models import F, QuerySet, Sumfrom django.db.models.functions import Coalesce@@ -67,6 +68,7 @@ def check_stock_and_preorder_quantity(checkout_lines: Optional[list["CheckoutLine"]] = None,check_reservations: bool = False,order_line: Optional["OrderLine"] = None,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):"""Validate if there is stock/preorder available for given variant.@@ -75,7 +77,12 @@ def check_stock_and_preorder_quantity("""if variant.is_preorder_active():check_preorder_threshold_in_orders(- variant, quantity, channel_slug, checkout_lines, check_reservations+ variant,+ quantity,+ channel_slug,+ checkout_lines,+ check_reservations,+ database_connection_name=database_connection_name,)else:check_stock_quantity(@@ -86,6 +93,7 @@ def check_stock_and_preorder_quantity(checkout_lines,check_reservations,order_line,+ database_connection_name,)@@ -97,6 +105,7 @@ def check_stock_quantity(checkout_lines: Optional[list["CheckoutLine"]] = None,check_reservations: bool = False,order_line: Optional["OrderLine"] = None,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):"""Validate if there is stock available for given variant in given country.@@ -104,9 +113,9 @@ def check_stock_quantity(exception."""if variant.track_inventory:- stocks = Stock.objects.get_variant_stocks_for_country(- country_code, channel_slug, variant- )+ stocks = Stock.objects.using(+ database_connection_name+ ).get_variant_stocks_for_country(country_code, channel_slug, variant)if not stocks:raise InsufficientStock([@@ -232,6 +241,7 @@ def check_stock_quantity_bulk(existing_lines: Optional[Iterable["CheckoutLineInfo"]] = None,replace=False,check_reservations: bool = False,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):"""Validate if there is stock available for given variants in given country.@@ -253,9 +263,11 @@ def check_stock_quantity_bulk(delivery_method_info.warehouse_pk if delivery_method_info else None)stocks = (- Stock.objects.for_channel_and_click_and_collect(channel_slug)+ Stock.objects.using(database_connection_name).for_channel_and_click_and_collect(+ channel_slug+ )if collection_point- else Stock.objects.for_channel_and_country(+ else Stock.objects.using(database_connection_name).for_channel_and_country(channel_slug, country_code, include_cc_warehouses))@@ -312,12 +324,14 @@ def check_stock_quantity_bulk(raise InsufficientStock(insufficient_stocks)-def _get_variants_channel_availbility_info(+def _get_variants_channel_availability_info(variants: Iterable["ProductVariant"],channel_slug: str,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> VariantsChannelAvailbilityInfo:all_variants_channel_listings = (- ProductVariantChannelListing.objects.filter(variant__in=variants)+ ProductVariantChannelListing.objects.using(database_connection_name)+ .filter(variant__in=variants).annotate_preorder_quantity_allocated().annotate(available_preorder_quantity=F("preorder_quantity_threshold")@@ -360,6 +374,7 @@ def check_preorder_threshold_in_orders(channel_slug: str,checkout_lines: Optional[Iterable["CheckoutLine"]],check_reservations: bool,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):"""Validate if there is preorder available for given variants in given country.@@ -371,11 +386,15 @@ def check_preorder_threshold_in_orders(variants_global_allocations,all_variants_channel_listings,variant_channels,- ) = _get_variants_channel_availbility_info([variant], channel_slug)+ ) = _get_variants_channel_availability_info(+ [variant], channel_slug, database_connection_name=database_connection_name+ )if check_reservations:listings_reservations = get_listings_reservations(- checkout_lines, all_variants_channel_listings+ checkout_lines,+ all_variants_channel_listings,+ database_connection_name=database_connection_name,)else:listings_reservations = defaultdict(int)@@ -439,7 +458,7 @@ def check_preorder_threshold_bulk(variants_global_allocations,all_variants_channel_listings,variant_channels,- ) = _get_variants_channel_availbility_info(variants, channel_slug)+ ) = _get_variants_channel_availability_info(variants, channel_slug)if check_reservations:listings_reservations = get_listings_reservations(diff --git a/saleor/warehouse/reservations.py b/saleor/warehouse/reservations.pyindex 48ef47cc06..052cfc456e 100644--- a/saleor/warehouse/reservations.py+++ b/saleor/warehouse/reservations.py@@ -3,6 +3,7 @@ from collections.abc import Iterablefrom datetime import datetime, timedeltafrom typing import TYPE_CHECKING, Optional+from django.conf import settingsfrom django.db.models import F, Sumfrom django.db.models.functions import Coalescefrom django.utils import timezone@@ -401,9 +402,11 @@ def get_reservation_length(site, user) -> Optional[int]:def get_listings_reservations(checkout_lines: Optional[Iterable["CheckoutLine"]],all_variants_channel_listings,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> dict[int, int]:quantity_reservation_list = (- PreorderReservation.objects.filter(+ PreorderReservation.objects.using(database_connection_name)+ .filter(product_variant_channel_listing__in=all_variants_channel_listings,quantity_reserved__gt=0,)