Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Improve warehouse filtering performance (#9622)
Tomasz Szymańskia1a7a223bba2
diff --git a/saleor/account/migrations/0065_address_warehouse_address_search_gin.py b/saleor/account/migrations/0065_address_warehouse_address_search_gin.pynew file mode 100644index 0000000000..b871a377b4--- /dev/null+++ b/saleor/account/migrations/0065_address_warehouse_address_search_gin.py@@ -0,0 +1,36 @@+# Generated by Django 3.2.13 on 2022-04-27 09:10++import django.contrib.postgres.indexes+from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("account", "0064_rewrite_customerevent_order_relation"),+ ]++ operations = [+ migrations.AddIndex(+ model_name="address",+ index=django.contrib.postgres.indexes.GinIndex(+ fields=[+ "company_name",+ "street_address_1",+ "street_address_2",+ "city",+ "postal_code",+ "phone",+ ],+ name="warehouse_address_search_gin",+ opclasses=[+ "gin_trgm_ops",+ "gin_trgm_ops",+ "gin_trgm_ops",+ "gin_trgm_ops",+ "gin_trgm_ops",+ "gin_trgm_ops",+ ],+ ),+ ),+ ]diff --git a/saleor/account/models.py b/saleor/account/models.pyindex 173d2b4b39..3925dd5336 100644--- a/saleor/account/models.py+++ b/saleor/account/models.py@@ -80,6 +80,19 @@ class Address(models.Model):fields=["first_name", "last_name", "city", "country"],opclasses=["gin_trgm_ops"] * 4,),+ GinIndex(+ name="warehouse_address_search_gin",+ # `opclasses` and `fields` should be the same length+ fields=[+ "company_name",+ "street_address_1",+ "street_address_2",+ "city",+ "postal_code",+ "phone",+ ],+ opclasses=["gin_trgm_ops"] * 6,+ ),]@propertydiff --git a/saleor/graphql/core/tests/test_graphql.py b/saleor/graphql/core/tests/test_graphql.pyindex e5c280ba25..2c7886d050 100644--- a/saleor/graphql/core/tests/test_graphql.py+++ b/saleor/graphql/core/tests/test_graphql.py@@ -1,10 +1,9 @@from functools import partial-from unittest.mock import Mock, patch+from unittest.mock import Mockimport grapheneimport pytestfrom django.contrib.auth.models import AnonymousUser-from django.db.models import Qfrom django.shortcuts import reversefrom graphql.error import GraphQLErrorfrom graphql_relay import to_global_id@@ -15,7 +14,6 @@ from ...order.types import Orderfrom ...product.types import Productfrom ...tests.utils import get_graphql_contentfrom ...utils import get_nodes-from ...utils.filters import filter_by_query_paramdef test_middleware_dont_generate_sql_requests(client, settings, assert_num_queries):@@ -336,19 +334,6 @@ def test_get_nodes_for_order_with_uuid_and_int_id(order_list):assert orders == order_list-@patch("saleor.product.models.Product.objects")-def test_filter_by_query_param(qs):- qs.filter.return_value = qs-- qs = filter_by_query_param(qs, "test", ["name", "force"])- test_kwargs = {"name__icontains": "test", "force__icontains": "test"}- q_objects = Q()- for q in test_kwargs:- q_objects |= Q(**{q: test_kwargs[q]})- # FIXME: django 1.11 fails on called_once_with(q_objects)- qs.filter.call_count == 1--def test_from_global_id_or_error(product):invalid_id = "invalid"message = f"Couldn't resolve id: {invalid_id}."diff --git a/saleor/graphql/utils/filters.py b/saleor/graphql/utils/filters.pyindex 6b450a3cd0..f87170322e 100644--- a/saleor/graphql/utils/filters.py+++ b/saleor/graphql/utils/filters.py@@ -1,40 +1,8 @@-from django.db.models import Qfrom django.utils import timezonefrom ..core.enums import ReportingPeriod-def filter_fields_containing_value(*search_fields: str):- """Create a icontains filters through given fields on a given query set object."""-- def _filter_qs(qs, _, value):- if value:- qs = filter_by_query_param(qs, value, search_fields)- return qs-- return _filter_qs---def filter_by_query_param(queryset, query, search_fields):- """Filter queryset according to given parameters.-- Keyword Arguments:- queryset - queryset to be filtered- query - search string- search_fields - fields considered in filtering-- """- if query:- query_by = {- "{0}__{1}".format(field, "icontains"): query for field in search_fields- }- query_objects = Q()- for q in query_by:- query_objects |= Q(**{q: query_by[q]})- return queryset.filter(query_objects).distinct()- return queryset--def reporting_period_to_date(period):now = timezone.now()if period == ReportingPeriod.TODAY:diff --git a/saleor/graphql/warehouse/filters.py b/saleor/graphql/warehouse/filters.pyindex 989de698f9..501118ce83 100644--- a/saleor/graphql/warehouse/filters.py+++ b/saleor/graphql/warehouse/filters.py@@ -1,10 +1,12 @@import django_filters+from django.db.models import Exists, OuterRef, Q+from ...account.models import Address+from ...product.models import Product, ProductVariantfrom ...warehouse import WarehouseClickAndCollectOptionfrom ...warehouse.models import Stock, Warehousefrom ..core.filters import EnumFilter, GlobalIDMultipleChoiceFilterfrom ..core.types import FilterInputObjectType-from ..utils.filters import filter_by_query_paramfrom ..warehouse.enums import WarehouseClickAndCollectOptionEnum@@ -13,20 +15,20 @@ def prefech_qs_for_filter(qs):def filter_search_warehouse(qs, _, value):- search_fields = [- "name",- "address__company_name",- "email",- "address__street_address_1",- "address__street_address_2",- "address__city",- "address__postal_code",- "address__phone",- ]-if value:- qs = prefech_qs_for_filter(qs)- qs = filter_by_query_param(qs, value, search_fields)+ addresses = Address.objects.filter(+ Q(company_name__ilike=value)+ | Q(street_address_1__ilike=value)+ | Q(street_address_2__ilike=value)+ | Q(city__ilike=value)+ | Q(postal_code__ilike=value)+ | Q(phone__ilike=value)+ ).values("pk")+ qs = qs.filter(+ Q(name__ilike=value)+ | Q(email__ilike=value)+ | Q(Exists(addresses.filter(pk=OuterRef("address_id"))))+ )return qs@@ -45,17 +47,20 @@ def filter_click_and_collect_option(qs, _, value):def filter_search_stock(qs, _, value):- search_fields = [- "product_variant__product__name",- "product_variant__name",- "warehouse__name",- "warehouse__address__company_name",- ]if value:- qs = qs.select_related("product_variant", "warehouse").prefetch_related(- "product_variant__product"+ products = Product.objects.filter(name__ilike=value).values("pk")+ variants = ProductVariant.objects.filter(+ Q(name__ilike=value) | Q(Exists(products.filter(pk=OuterRef("product_id"))))+ ).values("pk")+ addresses = Address.objects.filter(company_name__ilike=value)+ warehouses = Warehouse.objects.filter(+ Q(name__ilike=value)+ | Q(Exists(addresses.filter(id=OuterRef("address_id"))))+ ).values("pk")+ return qs.filter(+ Q(Exists(variants.filter(pk=OuterRef("product_variant_id"))))+ | Q(Exists(warehouses.filter(stock=OuterRef("pk")))))- qs = filter_by_query_param(qs, value, search_fields)return qsdiff --git a/saleor/graphql/warehouse/types.py b/saleor/graphql/warehouse/types.pyindex 5b9d12a55d..f136ad2c6d 100644--- a/saleor/graphql/warehouse/types.py+++ b/saleor/graphql/warehouse/types.py@@ -13,6 +13,7 @@ from ..core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_FIELD, PREVIEW_FEAfrom ..core.fields import ConnectionField, PermissionsFieldfrom ..core.types import ModelObjectType, NonNullListfrom ..meta.types import ObjectWithMetadata+from ..product.dataloaders import ProductVariantByIdLoaderfrom .dataloaders import WarehouseByIdLoaderfrom .enums import WarehouseClickAndCollectOptionEnum@@ -200,8 +201,12 @@ class Stock(ModelObjectType):return None@staticmethod- def resolve_product_variant(root, _info):- return ChannelContext(node=root.product_variant, channel_slug=None)+ def resolve_product_variant(root, info):+ return (+ ProductVariantByIdLoader(info.context)+ .load(root.product_variant_id)+ .then(lambda variant: ChannelContext(node=variant, channel_slug=None))+ )class StockCountableConnection(CountableConnection):