Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Use read replica in tests (#15936)
Marcin Gębala719d6c0da615
diff --git a/conftest.py b/conftest.pyindex 9cfa6fe2e5..e8ecc13535 100644--- a/conftest.py+++ b/conftest.py@@ -8,6 +8,13 @@ from django.core.management import call_commandfrom django.db import connectionsfrom django.test.testcases import TransactionTestCase+from saleor.tests.utils import prepare_test_db_connections++django.test.TransactionTestCase.databases = "__all__"+django.test.TestCase.databases = "__all__"++prepare_test_db_connections()+pytest_plugins = ["saleor.tests.fixtures","saleor.discount.tests.test_utils.fixtures",diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.pyindex 8f874b1fcd..4f27fe4e72 100644--- a/saleor/checkout/fetch.py+++ b/saleor/checkout/fetch.py@@ -92,6 +92,7 @@ class CheckoutInfo:collection_point: Optional["Warehouse"] = Nonevoucher: Optional["Voucher"] = Nonevoucher_code: Optional["VoucherCode"] = None+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME@cached_propertydef all_shipping_methods(self) -> list["ShippingMethodData"]:@@ -101,6 +102,7 @@ class CheckoutInfo:self.lines,self.shipping_channel_listings,self.manager,+ self.database_connection_name,)# Filter shipping methods using sync webhooksexcluded_methods = self.manager.excluded_shipping_methods_for_checkout(@@ -534,6 +536,7 @@ def fetch_checkout_info(collection_point=checkout.collection_point,voucher=voucher,voucher_code=voucher_code,+ database_connection_name=database_connection_name,)return checkout_infodiff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 0640f033f6..82c697ef1e 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -1046,8 +1046,10 @@ def get_or_create_checkout_metadata(checkout: "Checkout") -> CheckoutMetadata:return CheckoutMetadata.objects.create(checkout=checkout)+@allow_writer()def get_checkout_metadata(checkout: "Checkout"):if hasattr(checkout, "metadata_storage"):+ # TODO: load metadata_storage with dataloader and pass as an argumentreturn checkout.metadata_storageelse:return CheckoutMetadata(checkout=checkout)diff --git a/saleor/discount/utils.py b/saleor/discount/utils.pyindex da5c1b7542..309f8bbf1f 100644--- a/saleor/discount/utils.py+++ b/saleor/discount/utils.py@@ -889,6 +889,7 @@ def _get_available_for_purchase_variant_ids(return set(available_variant_ids)+@allow_writer()def _handle_order_promotion_for_checkout(checkout_info: CheckoutInfo,lines_info: Iterable[CheckoutLineInfo],@@ -932,6 +933,7 @@ def _handle_order_promotion_for_checkout(delete_gift_line(checkout, lines_info)+@allow_writer()def delete_gift_line(order_or_checkout: Union[Checkout, Order],lines_info: Iterable[Union["CheckoutLineInfo", "DraftOrderLineInfo"]],@@ -1102,6 +1104,10 @@ def fetch_promotion_rules_for_checkout_or_order():from ..graphql.discount.utils import PredicateObjectType, filter_qs_by_predicate+ with allow_writer():+ # TODO: channel should be loaded using dataloader+ currency = instance.channel.currency_code+applicable_rules = []promotions = Promotion.objects.active()rules = (@@ -1113,7 +1119,6 @@ def fetch_promotion_rules_for_checkout_or_order(rule_to_channel_ids_map = _get_rule_to_channel_ids_map(rules)channel_id = instance.channel_id- currency = instance.channel.currency_codeqs = instance._meta.model.objects.using(database_connection_name).filter( # type: ignore[attr-defined] # noqa: E501pk=instance.pk)@@ -1322,9 +1327,12 @@ def create_order_discount_objects_for_order_promotions(from ..order.utils import get_order_country# If voucher is set or manual discount applied, then skip order promotions- if order.voucher_code or order.discounts.filter(type=DiscountType.MANUAL):- _clear_order_discount(order, lines_info)- return+ with allow_writer():+ # TODO: country and order discounts should be loaded with dataloader+ country = get_order_country(order)+ if order.voucher_code or order.discounts.filter(type=DiscountType.MANUAL):+ _clear_order_discount(order, lines_info)+ return# The base prices are required for order promotion discount qualification._set_order_base_prices(order, lines_info)@@ -1336,7 +1344,7 @@ def create_order_discount_objects_for_order_promotions(rule_data = get_best_rule(rules=rules,channel=channel,- country=get_order_country(order),+ country=country,subtotal=subtotal,database_connection_name=database_connection_name,)@@ -1389,6 +1397,7 @@ def create_order_discount_objects_for_order_promotions()+@allow_writer()def _clear_order_discount(order_or_checkout: Union[Checkout, Order],lines_info: Iterable[DraftOrderLineInfo],diff --git a/saleor/graphql/checkout/dataloaders.py b/saleor/graphql/checkout/dataloaders.pyindex 8671820e50..7103d28998 100644--- a/saleor/graphql/checkout/dataloaders.py+++ b/saleor/graphql/checkout/dataloaders.py@@ -554,6 +554,7 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):collection_point=collection_point,voucher=voucher_code.voucher if voucher_code else None,voucher_code=voucher_code,+ database_connection_name=self.database_connection_name,)checkout_info_map[key] = checkout_infodiff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex 6f3c825312..263fb3ea31 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -221,6 +221,8 @@ def test_checkout_available_payment_gateways_valid_info_sent(api_client.post_graphql(query, variables)# then+ checkout_info.manager = mock.ANY+ checkout_info.database_connection_name = mock.ANYmocked_list_gateways.assert_called_with(currency=currency,checkout_info=checkout_info,diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.pyindex 0fa6ccdaff..58c9eee002 100644--- a/saleor/graphql/checkout/types.py+++ b/saleor/graphql/checkout/types.py@@ -996,6 +996,7 @@ class Checkout(ModelObjectType[models.Checkout]):root.token)+ @allow_writer_in_context(info.context)def get_available_payment_gateways(results):(checkout_info, lines_info) = resultsreturn manager.list_payment_gateways(diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex a3986e38ef..2fcb1d2b55 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -1573,6 +1573,7 @@ class Order(ModelObjectType[models.Order]):@staticmethoddef resolve_discounts(root: models.Order, info):+ @allow_writer_in_context(info.context)def with_manager(manager):fetch_order_prices_if_expired(root, manager)return OrderDiscountsByOrderIDLoader(info.context).load(root.id)diff --git a/saleor/order/base_calculations.py b/saleor/order/base_calculations.pyindex bf97b72d01..3262f7dbeb 100644--- a/saleor/order/base_calculations.py+++ b/saleor/order/base_calculations.py@@ -4,6 +4,7 @@ from typing import TYPE_CHECKING, Optionalfrom django.conf import settingsfrom prices import Money, TaxedMoney+from ..core.db.connection import allow_writerfrom ..core.prices import quantize_pricefrom ..core.taxes import zero_moneyfrom ..discount import DiscountType, DiscountValueType, VoucherType@@ -329,7 +330,12 @@ def undiscounted_order_shipping("""Return shipping price without any discounts."""# TODO: add undiscounted_shipping_price field to order model.# https://github.com/saleor/saleor/issues/14915- if shipping_method := order.shipping_method:++ with allow_writer():+ # TODO: load shipping_method with dataloader and pass as an argument+ shipping_method = order.shipping_method++ if shipping_method:if (listing := ShippingMethodChannelListing.objects.using(database_connection_namediff --git a/saleor/order/calculations.py b/saleor/order/calculations.pyindex 4ac30e918f..1e87078bf2 100644--- a/saleor/order/calculations.py+++ b/saleor/order/calculations.py@@ -60,7 +60,9 @@ def fetch_order_prices_if_expired(_update_order_discount_for_voucher(order)_clear_prefetched_discounts(order, lines)- prefetch_related_objects([order], "discounts")+ with allow_writer():+ # TODO: Load discounts with a dataloader and pass as argument+ prefetch_related_objects([order], "discounts")# handle taxes_recalculate_prices(@@ -111,11 +113,11 @@ def fetch_order_prices_if_expired(return order, lines+@allow_writer()def _update_order_discount_for_voucher(order: Order):"""Create or delete OrderDiscount instances."""if not order.voucher_id:- with allow_writer():- order.discounts.filter(type=DiscountType.VOUCHER).delete()+ order.discounts.filter(type=DiscountType.VOUCHER).delete()elif (order.voucher_iddiff --git a/saleor/order/fetch.py b/saleor/order/fetch.pyindex 5bab6e8ab9..eab485ca52 100644--- a/saleor/order/fetch.py+++ b/saleor/order/fetch.py@@ -6,6 +6,7 @@ from uuid import UUIDfrom django.db.models import prefetch_related_objectsfrom ..channel.models import Channel+from ..core.db.connection import allow_writerfrom ..discount import DiscountTypefrom ..discount.interface import VariantPromotionRuleInfo, fetch_variant_rules_infofrom ..discount.models import OrderLineDiscount, Voucher@@ -98,7 +99,8 @@ class DraftOrderLineInfo:def fetch_draft_order_lines_info(- order: "Order", lines: Optional[Iterable["OrderLine"]] = None+ order: "Order",+ lines: Optional[Iterable["OrderLine"]] = None,) -> list[DraftOrderLineInfo]:prefetch_related_fields = ["discounts__promotion_rule__promotion",@@ -106,12 +108,18 @@ def fetch_draft_order_lines_info("variant__channel_listings__variantlistingpromotionrule__promotion_rule__translations",]if lines is None:- lines = list(order.lines.prefetch_related(*prefetch_related_fields))+ with allow_writer():+ # TODO: load lines with dataloader and pass as an argument+ lines = list(order.lines.prefetch_related(*prefetch_related_fields))else:prefetch_related_objects(lines, *prefetch_related_fields)lines_info = []- channel = order.channel++ with allow_writer():+ # TODO: load channel with dataloader and pass as an argument+ channel = order.channel+for line in lines:variant = cast(ProductVariant, line.variant)variant_channel_listing = get_prefetched_variant_listing(variant, channel.id)diff --git a/saleor/plugins/views.py b/saleor/plugins/views.pyindex c6346dc404..233ca455b1 100644--- a/saleor/plugins/views.py+++ b/saleor/plugins/views.py@@ -1,14 +1,17 @@from django.http import HttpResponse+from ..core.db.connection import allow_writerfrom ..graphql.core import SaleorContextfrom .manager import get_plugins_manager+@allow_writer()def handle_plugin_webhook(request: SaleorContext, plugin_id: str) -> HttpResponse:manager = get_plugins_manager(allow_replica=False)return manager.webhook_endpoint_without_channel(request, plugin_id)+@allow_writer()def handle_global_plugin_webhook(request: SaleorContext, plugin_id: str) -> HttpResponse:@@ -16,6 +19,7 @@ def handle_global_plugin_webhook(return manager.webhook(request, plugin_id, channel_slug=None)+@allow_writer()def handle_plugin_per_channel_webhook(request: SaleorContext, plugin_id: str, channel_slug: str) -> HttpResponse:diff --git a/saleor/settings.py b/saleor/settings.pyindex 94180e45c8..70ec6d5cc2 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -113,6 +113,9 @@ DATABASES = {conn_max_age=DB_CONN_MAX_AGE,),}+DATABASES[DATABASE_CONNECTION_REPLICA_NAME]["TEST"] = {+ "MIRROR": DATABASE_CONNECTION_DEFAULT_NAME+}DATABASE_ROUTERS = ["saleor.core.db_routers.PrimaryReplicaRouter"]diff --git a/saleor/shipping/utils.py b/saleor/shipping/utils.pyindex 54dba13197..380854ac25 100644--- a/saleor/shipping/utils.py+++ b/saleor/shipping/utils.py@@ -3,6 +3,7 @@ from typing import TYPE_CHECKING, Optionalfrom django_countries import countries+from ..core.db.connection import allow_writerfrom ..plugins.base_plugin import ExcludedShippingMethodfrom .interface import ShippingMethodData@@ -41,7 +42,9 @@ def convert_to_shipping_method_data(if not tax_class:# Tax class should be passed as argument, this is a fallback.- tax_class = shipping_method.tax_class+ # TODO: load tax_class with data loader and pass as an argument+ with allow_writer():+ tax_class = shipping_method.tax_classreturn ShippingMethodData(id=str(shipping_method.id),diff --git a/saleor/tests/settings.py b/saleor/tests/settings.pyindex deb5301734..09cfba8165 100644--- a/saleor/tests/settings.py+++ b/saleor/tests/settings.py@@ -93,7 +93,7 @@ FdkAmFzQhgLtnEtnb+eBI7DNOJEuPLD52Jwnq2pGnJ/LxlqjjWJ5FsQQVSoDHGfM8yodVX6OCKwHYrgleLjVWs5ZmaGfGpqcy1YgquiYGVF4x8qBe5bpwHw=-----END RSA PRIVATE KEY-----"""-DATABASE_CONNECTION_REPLICA_NAME = DATABASE_CONNECTION_DEFAULT_NAME # noqa: F405-HTTP_IP_FILTER_ENABLED = FalseHTTP_IP_FILTER_ALLOW_LOOPBACK_IPS = True++MIDDLEWARE.insert(0, "saleor.core.db.connection.restrict_writer_middleware") # noqa: F405diff --git a/saleor/tests/test_db_connections.py b/saleor/tests/test_db_connections.pynew file mode 100644index 0000000000..82f024e48e--- /dev/null+++ b/saleor/tests/test_db_connections.py@@ -0,0 +1,16 @@+import pytest+from django.conf import settings++from ..app.models import App, AppExtension+++def test_subqueries_no_allowed_across_different_databases(app_with_extensions):+ replica = settings.DATABASE_CONNECTION_REPLICA_NAME+ writer = settings.DATABASE_CONNECTION_DEFAULT_NAME+ subquery = App.objects.using(replica).all()+ query = AppExtension.objects.using(writer).filter(app_id__in=subquery)++ with pytest.raises(+ ValueError, match="Subqueries aren't allowed across different databases."+ ):+ list(query)diff --git a/saleor/tests/utils.py b/saleor/tests/utils.pyindex bb677fc9c1..566f83790a 100644--- a/saleor/tests/utils.py+++ b/saleor/tests/utils.py@@ -2,22 +2,49 @@ import jsonimport mathfrom decimal import Decimal+from django.conf import settingsfrom django.db import connections, transaction+class TestDBConnectionWrapper:+ def __init__(self, conn, default_conn):+ self._wrapped_conn = conn+ self._default_conn = default_conn++ def cursor(self, *args, **kwargs):+ cursor = self._default_conn.cursor(*args, **kwargs)+ cursor.db = self+ return cursor++ def chunked_cursor(self, *args, **kwargs):+ cursor = self._default_conn.chunked_cursor(*args, **kwargs)+ cursor.db = self+ return cursor++ def __getattr__(self, attr):+ if attr in ["alias", "settings_dict"]:+ return getattr(self._wrapped_conn, attr)+ return getattr(self._default_conn, attr)+++def prepare_test_db_connections():+ replica = settings.DATABASE_CONNECTION_REPLICA_NAME+ default_conn = connections[settings.DATABASE_CONNECTION_DEFAULT_NAME]+ connections[replica] = TestDBConnectionWrapper(connections[replica], default_conn) # type: ignore++def flush_post_commit_hooks():"""Run all pending `transaction.on_commit()` callbacks.Forces all `on_commit()` hooks to run even if the transaction was not committed yet."""- for alias in connections:- connection = transaction.get_connection(alias)- was_atomic = connection.in_atomic_block- was_commit_on_exit = connection.commit_on_exit- connection.in_atomic_block = False- connection.run_and_clear_commit_hooks()- connection.in_atomic_block = was_atomic- connection.commit_on_exit = was_commit_on_exit+ connection = transaction.get_connection(settings.DATABASE_CONNECTION_DEFAULT_NAME)+ was_atomic = connection.in_atomic_block+ was_commit_on_exit = connection.commit_on_exit+ connection.in_atomic_block = False+ connection.run_and_clear_commit_hooks()+ connection.in_atomic_block = was_atomic+ connection.commit_on_exit = was_commit_on_exitdef dummy_editorjs(text, json_format=False):