Skip to content

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

Use read replica in tests (#15936)

Marcin Gębala719d6c0da615
diff --git a/conftest.py b/conftest.py
index 9cfa6fe2e5..e8ecc13535 100644
--- a/conftest.py
+++ b/conftest.py
@@ -8,6 +8,13 @@ from django.core.management import call_command
from django.db import connections
from 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.py
index 8f874b1fcd..4f27fe4e72 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -92,6 +92,7 @@ class CheckoutInfo:
collection_point: Optional["Warehouse"] = None
voucher: Optional["Voucher"] = None
voucher_code: Optional["VoucherCode"] = None
+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME
@cached_property
def 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 webhooks
excluded_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_info
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 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 argument
return checkout.metadata_storage
else:
return CheckoutMetadata(checkout=checkout)
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index 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_code
qs = instance._meta.model.objects.using(database_connection_name).filter( # type: ignore[attr-defined] # noqa: E501
pk=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.py
index 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_info
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index 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.ANY
mocked_list_gateways.assert_called_with(
currency=currency,
checkout_info=checkout_info,
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index 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) = results
return manager.list_payment_gateways(
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index a3986e38ef..2fcb1d2b55 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -1573,6 +1573,7 @@ class Order(ModelObjectType[models.Order]):
@staticmethod
def 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.py
index bf97b72d01..3262f7dbeb 100644
--- a/saleor/order/base_calculations.py
+++ b/saleor/order/base_calculations.py
@@ -4,6 +4,7 @@ from typing import TYPE_CHECKING, Optional
from django.conf import settings
from prices import Money, TaxedMoney
+from ..core.db.connection import allow_writer
from ..core.prices import quantize_price
from ..core.taxes import zero_money
from ..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_name
diff --git a/saleor/order/calculations.py b/saleor/order/calculations.py
index 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_id
diff --git a/saleor/order/fetch.py b/saleor/order/fetch.py
index 5bab6e8ab9..eab485ca52 100644
--- a/saleor/order/fetch.py
+++ b/saleor/order/fetch.py
@@ -6,6 +6,7 @@ from uuid import UUID
from django.db.models import prefetch_related_objects
from ..channel.models import Channel
+from ..core.db.connection import allow_writer
from ..discount import DiscountType
from ..discount.interface import VariantPromotionRuleInfo, fetch_variant_rules_info
from ..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.py
index 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_writer
from ..graphql.core import SaleorContext
from .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.py
index 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.py
index 54dba13197..380854ac25 100644
--- a/saleor/shipping/utils.py
+++ b/saleor/shipping/utils.py
@@ -3,6 +3,7 @@ from typing import TYPE_CHECKING, Optional
from django_countries import countries
+from ..core.db.connection import allow_writer
from ..plugins.base_plugin import ExcludedShippingMethod
from .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_class
return ShippingMethodData(
id=str(shipping_method.id),
diff --git a/saleor/tests/settings.py b/saleor/tests/settings.py
index deb5301734..09cfba8165 100644
--- a/saleor/tests/settings.py
+++ b/saleor/tests/settings.py
@@ -93,7 +93,7 @@ FdkAmFzQhgLtnEtnb+eBI7DNOJEuPLD52Jwnq2pGnJ/LxlqjjWJ5FsQQVSoDHGfM
8yodVX6OCKwHYrgleLjVWs5ZmaGfGpqcy1YgquiYGVF4x8qBe5bpwHw=
-----END RSA PRIVATE KEY-----"""
-DATABASE_CONNECTION_REPLICA_NAME = DATABASE_CONNECTION_DEFAULT_NAME # noqa: F405
-
HTTP_IP_FILTER_ENABLED = False
HTTP_IP_FILTER_ALLOW_LOOPBACK_IPS = True
+
+MIDDLEWARE.insert(0, "saleor.core.db.connection.restrict_writer_middleware") # noqa: F405
diff --git a/saleor/tests/test_db_connections.py b/saleor/tests/test_db_connections.py
new file mode 100644
index 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.py
index bb677fc9c1..566f83790a 100644
--- a/saleor/tests/utils.py
+++ b/saleor/tests/utils.py
@@ -2,22 +2,49 @@ import json
import math
from decimal import Decimal
+from django.conf import settings
from 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_exit
def dummy_editorjs(text, json_format=False):