Skip to content

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

Fix ORM crash when generating hundreds of search vector in SQL (#10261) (#10282)

Mika43765a4c1fc0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 704209eed2..d9e0e0ba54 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -50,6 +50,33 @@ All notable, unreleased changes to this project will be documented in this file.
- `get_taxes_for_checkout`
- `get_taxes_for_order`
+# 3.5.4 [Unreleased]
+- Fix ORM crash when generating hundreds of search vector in SQL - #10261 by @NyanKiyoshi
+
+# 3.5.3 [Released]
+- Use custom search vector in order search - #10247 by @fowczarek
+- Optimize filtering attributes by dates - #10199 by @tomaszszymanski129
+
+# 3.5.2 [Released]
+- Fix stock allocation for order with global collection point - #10225 by @IKarbowiak
+- Fix stock validation and allocation for order with local collection point - #10218 @IKarbowiak
+- Fix returning GraphQL IDs in the `SALE_TOGGLE` webhook - #10227 by @IKarbowiak
+
+# 3.5.1 [Released]
+- Fix inconsistent beat scheduling and compatibility with db scheduler - #10185 by @NyanKiyoshi<br/>
+ This fixes the following bugs:
+ - `tick()` could decide to never schedule anything else than `send-sale-toggle-notifications` if `send-sale-toggle-notifications` doesn't return `is_due = False` (stuck forever until beat restart or a `is_due = True`)
+ - `tick()` was sometimes scheduling other schedulers such as observability to be ran every 5m instead of every 20s
+ - `is_due()` from `send-sale-toggle-notifications` was being invoked every 5s on django-celery-beat instead of every 60s
+ - `send-sale-toggle-notifications` would crash on django-celery-beat with `Cannot convert schedule type <saleor.core.schedules.sale_webhook_schedule object at 0x7fabfdaacb20> to model`
+
+ Usage:
+ - Database backend: `celery --app saleor.celeryconf:app beat --scheduler saleor.schedulers.schedulers.DatabaseScheduler`
+ - Shelve backend: `celery --app saleor.celeryconf:app beat --scheduler saleor.schedulers.schedulers.PersistentScheduler`
+- Fix problem with updating draft order with active avalara - #10183 by @IKarbowiak
+- Fix stock validation and allocation for order with local collection point - #10218 by @IKarbowiak
+- Fix stock allocation for order with global collection point - #10225 by @IKarbowiak
+
# 3.5.0
### GraphQL API
diff --git a/saleor/account/search.py b/saleor/account/search.py
index a3c4cd3352..6213328591 100644
--- a/saleor/account/search.py
+++ b/saleor/account/search.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, List
from django.db.models import Q, Value, prefetch_related_objects
@@ -64,42 +64,46 @@ def generate_address_search_document_value(address: "Address"):
def generate_address_search_vector_value(
address: "Address", weight: str = "A"
-) -> NoValidationSearchVector:
- search_vector = NoValidationSearchVector(
- Value(address.first_name),
- Value(address.last_name),
- Value(address.street_address_1),
- Value(address.country.name),
- Value(address.country.code),
- weight=weight,
- )
+) -> List[NoValidationSearchVector]:
+ search_vectors = [
+ NoValidationSearchVector(
+ Value(address.first_name),
+ Value(address.last_name),
+ Value(address.street_address_1),
+ Value(address.country.name),
+ Value(address.country.code),
+ weight=weight,
+ )
+ ]
if address.company_name:
- search_vector += NoValidationSearchVector(
- Value(address.company_name), weight=weight
+ search_vectors.append(
+ NoValidationSearchVector(Value(address.company_name), weight=weight)
)
if address.country_area:
- search_vector += NoValidationSearchVector(
- Value(address.country_area), weight=weight
+ search_vectors.append(
+ NoValidationSearchVector(Value(address.country_area), weight=weight)
)
if address.city:
- search_vector += NoValidationSearchVector(Value(address.city), weight=weight)
+ search_vectors.append(
+ NoValidationSearchVector(Value(address.city), weight=weight)
+ )
if address.city_area:
- search_vector += NoValidationSearchVector(
- Value(address.city_area), weight=weight
+ search_vectors.append(
+ NoValidationSearchVector(Value(address.city_area), weight=weight)
)
if address.street_address_2:
- search_vector += NoValidationSearchVector(
- Value(address.street_address_2), weight=weight
+ search_vectors.append(
+ NoValidationSearchVector(Value(address.street_address_2), weight=weight)
)
if address.postal_code:
- search_vector += NoValidationSearchVector(
- Value(address.postal_code), weight=weight
+ search_vectors.append(
+ NoValidationSearchVector(Value(address.postal_code), weight=weight)
)
if address.phone:
- search_vector += NoValidationSearchVector(
- Value(address.phone.as_e164), weight=weight
+ search_vectors.append(
+ NoValidationSearchVector(Value(address.phone.as_e164), weight=weight)
)
- return search_vector
+ return search_vectors
def search_users(qs, value):
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 55548795a9..2a65fc2339 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -23,6 +23,7 @@ from ..account.utils import store_user_address
from ..checkout import calculations
from ..checkout.error_codes import CheckoutErrorCode
from ..core.exceptions import GiftCardNotApplicable, InsufficientStock
+from ..core.postgres import FlatConcat
from ..core.taxes import TaxError, zero_taxed_money
from ..core.tracing import traced_atomic_transaction
from ..core.utils.url import validate_storefront_url
@@ -565,7 +566,7 @@ def _create_order(
order.private_metadata = checkout.private_metadata
update_order_charge_data(order, with_save=False)
update_order_authorize_data(order, with_save=False)
- order.search_vector = prepare_order_search_vector_value(order)
+ order.search_vector = FlatConcat(*prepare_order_search_vector_value(order))
order.save()
order_info = OrderInfo(
@@ -1098,7 +1099,7 @@ def _create_order_from_checkout(
update_order_authorize_data(order, with_save=False)
# order search
- order.search_vector = prepare_order_search_vector_value(order)
+ order.search_vector = FlatConcat(*prepare_order_search_vector_value(order))
order.save()
# post create actions
diff --git a/saleor/core/postgres.py b/saleor/core/postgres.py
index b2efd3d9cc..51ba5534d1 100644
--- a/saleor/core/postgres.py
+++ b/saleor/core/postgres.py
@@ -1,8 +1,11 @@
+from typing import List, Optional, Union
+
from django.contrib.postgres.search import (
CombinedSearchVector,
SearchVector,
SearchVectorCombinable,
)
+from django.db.models import Expression
class NoValidationSearchVectorCombinable(SearchVectorCombinable):
@@ -35,3 +38,72 @@ class NoValidationSearchVector(SearchVector, NoValidationSearchVectorCombinable)
This class is only safe to use with expressions that do not contain aggregation
and/or over clause.
"""
+
+
+class FlatConcat(Expression):
+ """Generate a SQL statements for expressions to be concatenated.
+
+ This replaces the logic of Django ORM from recursive ``as_sql()`` and
+ ``resolve_expression()`` from some functions such as ``SearchVector``.
+
+ The function ``django.db.models.functions.text.Concat`` is recursive thus
+ will crash when setting hundreds of expressions to be concatenated.
+ """
+
+ function = None
+ template = "(%(expressions)s)"
+ arg_joiner = "||"
+
+ contains_aggregate = False
+ contains_over_clause = False
+
+ def __init__(self, *expressions, output_field=None):
+ super().__init__(output_field=output_field)
+ self.source_expressions: List[SearchVector] = self._parse_expressions(
+ *expressions
+ )
+
+ def __repr__(self):
+ args = self.arg_joiner.join(str(arg) for arg in self.source_expressions)
+ return f"{self.__class__.__name__}({args})"
+
+ def __add__(self, other):
+ if not isinstance(other, FlatConcat):
+ raise TypeError(
+ f"Cannot combine FlatSearchVectorCombinable with other "
+ f"instances types, got {other!r}."
+ )
+ return FlatConcat(*self.source_expressions + other.source_expressions)
+
+ def get_source_expressions(self):
+ return self.source_expressions
+
+ def set_source_expressions(self, exprs):
+ self.source_expressions = exprs
+
+ def copy(self):
+ copy = super().copy()
+ copy.source_expressions = self.source_expressions[:]
+ return copy
+
+ def resolve_expression(
+ self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
+ ):
+ c = self.copy()
+ c.is_summary = summarize
+ for pos, arg in enumerate(c.source_expressions):
+ c.source_expressions[pos] = arg.resolve_expression(
+ query, allow_joins, reuse, summarize, for_save
+ )
+ return c
+
+ def as_sql(self, compiler, connection, **_extra_context):
+ connection.ops.check_expression_support(self)
+ sql_parts: List[str] = []
+ params: List[Optional[Union[str, int]]] = []
+ for arg in self.source_expressions:
+ arg_sql, arg_params = compiler.compile(arg)
+ sql_parts.append(arg_sql)
+ params.extend(arg_params)
+ data = {"expressions": self.arg_joiner.join(sql_parts)}
+ return self.template % data, params
diff --git a/saleor/core/search_tasks.py b/saleor/core/search_tasks.py
index b1464d66fe..fe9834a349 100644
--- a/saleor/core/search_tasks.py
+++ b/saleor/core/search_tasks.py
@@ -12,6 +12,7 @@ from ..product.search import (
PRODUCT_FIELDS_TO_PREFETCH,
prepare_product_search_vector_value,
)
+from .postgres import FlatConcat
task_logger = get_task_logger(__name__)
@@ -128,8 +129,8 @@ def set_search_vector_values(
):
Model = instances[0]._meta.model
for instance in instances:
- instance.search_vector = prepare_search_vector_func(
- instance, already_prefetched=True
+ instance.search_vector = FlatConcat(
+ *prepare_search_vector_func(instance, already_prefetched=True)
)
Model.objects.bulk_update(instances, ["search_vector"])
diff --git a/saleor/core/tests/test_postgresql_search.py b/saleor/core/tests/test_postgresql_search.py
index 9c6b3fecc6..75cd58e6b1 100644
--- a/saleor/core/tests/test_postgresql_search.py
+++ b/saleor/core/tests/test_postgresql_search.py
@@ -7,6 +7,7 @@ from ...account.models import Address
from ...product.models import Product, ProductChannelListing
from ...product.search import search_products
from ...tests.utils import dummy_editorjs
+from ..postgres import FlatConcat
PRODUCTS = [
("Arabica Coffee", "The best grains in galactic"),
@@ -78,3 +79,23 @@ def gen_address_for_user(first_name, last_name):
postal_code="53-601",
country="PL",
)
+
+
+def test_combined_flat_search_vector():
+ """Ensure two FlatConcat can be combined into one object"""
+ flat_vector_1 = FlatConcat(
+ SearchVector(Value("value1"), weight="A"),
+ SearchVector(Value("value2"), weight="C"),
+ )
+ flat_vector_2 = FlatConcat(
+ SearchVector(Value("value3"), weight="A"),
+ SearchVector(Value("value4"), weight="C"),
+ )
+
+ combined_flat_vector = flat_vector_1 + flat_vector_2
+ assert combined_flat_vector.get_source_expressions() == [
+ SearchVector(Value("value1"), weight="A"),
+ SearchVector(Value("value2"), weight="C"),
+ SearchVector(Value("value3"), weight="A"),
+ SearchVector(Value("value4"), weight="C"),
+ ]
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index d35eaa8e0a..7cc5a3a70e 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -93,6 +93,7 @@ from ...shipping.models import (
from ...warehouse import WarehouseClickAndCollectOption
from ...warehouse.management import increase_stock
from ...warehouse.models import PreorderAllocation, Stock, Warehouse
+from ..postgres import FlatConcat
fake = Factory.create()
fake.seed(0)
@@ -834,7 +835,7 @@ def create_fake_order(discounts, max_order_lines=5, create_preorder_lines=False)
for line in order.lines.all():
weight += line.variant.get_weight()
order.weight = weight
- order.search_vector = prepare_order_search_vector_value(order)
+ order.search_vector = FlatConcat(*prepare_order_search_vector_value(order))
order.save()
create_fake_payment(order=order)
diff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.py
index 329f51787c..473fe56eb2 100644
--- a/saleor/graphql/order/mutations/draft_order_complete.py
+++ b/saleor/graphql/order/mutations/draft_order_complete.py
@@ -5,6 +5,7 @@ from django.db import transaction
from ....account.models import User
from ....core.exceptions import InsufficientStock
from ....core.permissions import OrderPermissions
+from ....core.postgres import FlatConcat
from ....core.taxes import zero_taxed_money
from ....core.tracing import traced_atomic_transaction
from ....order import OrderStatus, models
@@ -85,7 +86,7 @@ class DraftOrderComplete(BaseMutation):
order.shipping_address.delete()
order.shipping_address = None
- order.search_vector = prepare_order_search_vector_value(order)
+ order.search_vector = FlatConcat(*prepare_order_search_vector_value(order))
order.save()
channel = order.channel
diff --git a/saleor/graphql/order/mutations/order_update.py b/saleor/graphql/order/mutations/order_update.py
index 79834f1c32..d248b13e1e 100644
--- a/saleor/graphql/order/mutations/order_update.py
+++ b/saleor/graphql/order/mutations/order_update.py
@@ -4,6 +4,7 @@ from django.db import transaction
from ....account.models import User
from ....core.permissions import OrderPermissions
+from ....core.postgres import FlatConcat
from ....core.tracing import traced_atomic_transaction
from ....order import OrderStatus, models
from ....order.error_codes import OrderErrorCode
@@ -77,7 +78,9 @@ class OrderUpdate(DraftOrderCreate):
if instance.user_email:
user = User.objects.filter(email=instance.user_email).first()
instance.user = user
- instance.search_vector = prepare_order_search_vector_value(instance)
+ instance.search_vector = FlatConcat(
+ *prepare_order_search_vector_value(instance)
+ )
if cls.should_invalidate_prices(instance, cleaned_input, False):
invalidate_order_prices(instance)
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index 4eba1e3e20..6fa89b1493 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -23,6 +23,7 @@ from ....checkout import AddressType
from ....checkout.utils import PRIVATE_META_APP_SHIPPING_ID
from ....core.anonymize import obfuscate_email
from ....core.notify_events import NotifyEventType
+from ....core.postgres import FlatConcat
from ....core.prices import quantize_price
from ....core.taxes import TaxError, zero_taxed_money
from ....discount.models import OrderDiscount, VoucherChannelListing
@@ -9082,7 +9083,7 @@ def test_orders_query_with_filter_search(
tax_rate=Decimal("0.23"),
)
for order in orders:
- order.search_vector = prepare_order_search_vector_value(order)
+ order.search_vector = FlatConcat(*prepare_order_search_vector_value(order))
Order.objects.bulk_update(orders, ["search_vector"])
variables = {"filter": orders_filter}
@@ -9124,7 +9125,7 @@ def test_orders_query_with_filter_search_by_global_payment_id(
payment = Payment.objects.create(order=order_with_payment)
global_id = graphene.Node.to_global_id("Payment", payment.pk)
for order in orders:
- order.search_vector = prepare_order_search_vector_value(order)
+ order.search_vector = FlatConcat(*prepare_order_search_vector_value(order))
Order.objects.bulk_update(orders, ["search_vector"])
variables = {"filter": {"search": global_id}}
@@ -9480,8 +9481,7 @@ def test_draft_orders_query_with_filter_search(
]
)
for order in orders:
- order.search_vector = prepare_order_search_vector_value(order)
- print(">>>", order.search_vector)
+ order.search_vector = FlatConcat(*prepare_order_search_vector_value(order))
Order.objects.bulk_update(orders, ["search_vector"])
variables = {"filter": draft_orders_filter}
diff --git a/saleor/graphql/order/tests/test_pagination.py b/saleor/graphql/order/tests/test_pagination.py
index 5fe943fc0f..2566ac6b4a 100644
--- a/saleor/graphql/order/tests/test_pagination.py
+++ b/saleor/graphql/order/tests/test_pagination.py
@@ -6,6 +6,7 @@ import pytest
from freezegun import freeze_time
from prices import Money, TaxedMoney
+from ....core.postgres import FlatConcat
from ....discount.models import OrderDiscount
from ....order.models import Order, OrderStatus
from ....order.search import (
@@ -36,7 +37,7 @@ def orders_for_pagination(db, channel_USD):
)
for order in orders:
- order.search_vector = prepare_order_search_vector_value(order)
+ order.search_vector = FlatConcat(*prepare_order_search_vector_value(order))
Order.objects.bulk_update(orders, ["search_vector"])
return orders
@@ -455,7 +456,7 @@ def test_orders_query_pagination_with_filter_search(
)
for order in orders:
- order.search_vector = prepare_order_search_vector_value(order)
+ order.search_vector = FlatConcat(*prepare_order_search_vector_value(order))
Order.objects.bulk_update(orders, ["search_vector"])
after = None
@@ -537,7 +538,7 @@ def test_draft_orders_query_pagination_with_filter_search(
)
for order in orders:
- order.search_vector = prepare_order_search_vector_value(order)
+ order.search_vector = FlatConcat(*prepare_order_search_vector_value(order))
Order.objects.bulk_update(orders, ["search_vector"])
page_size = 2
diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.py
index b136b9304c..e0943edfe9 100644
--- a/saleor/graphql/product/bulk_mutations/products.py
+++ b/saleor/graphql/product/bulk_mutations/products.py
@@ -12,6 +12,7 @@ from graphene.types import InputObjectType
from ....attribute import AttributeInputType
from ....attribute import models as attribute_models
from ....core.permissions import ProductPermissions, ProductTypePermissions
+from ....core.postgres import FlatConcat
from ....core.tracing import traced_atomic_transaction
from ....order import events as order_events
from ....order import models as order_models
@@ -643,7 +644,9 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):
pk__in=product_pks, default_variant__isnull=True
)
for product in products:
- product.search_vector = prepare_product_search_vector_value(product)
+ product.search_vector = FlatConcat(
+ *prepare_product_search_vector_value(product)
+ )
product.default_variant = product.variants.first()
product.save(
update_fields=[
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index fc4a06eb0c..5457bc3e95 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -25,6 +25,7 @@ from prices import Money, TaxedMoney
from ....attribute import AttributeInputType, AttributeType
from ....attribute.models import Attribute, AttributeValue
from ....attribute.utils import associate_attribute_values_to_instance
+from ....core.postgres import FlatConcat
from ....core.taxes import TaxType
from ....core.units import MeasurementUnits, WeightUnits
from ....order import OrderEvents, OrderStatus
@@ -2830,7 +2831,7 @@ def test_products_query_with_filter_category_and_search(
product.save()
for pr in [product, second_product]:
- pr.search_vector = prepare_product_search_vector_value(pr)
+ pr.search_vector = FlatConcat(*prepare_product_search_vector_value(pr))
Product.objects.bulk_update([product, second_product], ["search_vector"])
category_id = graphene.Node.to_global_id("Category", category.id)
@@ -2962,7 +2963,9 @@ def test_products_query_with_filter(
channel=channel_USD,
is_published=False,
)
- second_product.search_vector = prepare_product_search_vector_value(second_product)
+ second_product.search_vector = FlatConcat(
+ *prepare_product_search_vector_value(second_product)
+ )
second_product.save(update_fields=["search_vector"])
variables = {"filter": products_filter, "channel": channel_USD.slug}
staff_api_client.user.user_permissions.add(permission_manage_products)
@@ -3073,8 +3076,8 @@ def test_products_query_with_filter_search_by_dropdown_attribute_value(
product_with_dropdown_attr.refresh_from_db()
- product_with_dropdown_attr.search_vector = prepare_product_search_vector_value(
- product_with_dropdown_attr
+ product_with_dropdown_attr.search_vector = FlatConcat(
+ *prepare_product_search_vector_value(product_with_dropdown_attr)
)
product_with_dropdown_attr.save(update_fields=["search_document", "search_vector"])
@@ -3136,8 +3139,8 @@ def test_products_query_with_filter_search_by_multiselect_attribute_value(
product_with_multiselect_attr.refresh_from_db()
- product_with_multiselect_attr.search_vector = prepare_product_search_vector_value(
- product_with_multiselect_attr
+ product_with_multiselect_attr.search_vector = FlatConcat(
+ *prepare_product_search_vector_value(product_with_multiselect_attr)
)
product_with_multiselect_attr.save(update_fields=["search_vector"])
@@ -3184,8 +3187,8 @@ def test_products_query_with_filter_search_by_rich_text_attribute(
product_with_rich_text_attr.refresh_from_db()
- product_with_rich_text_attr.search_vector = prepare_product_search_vector_value(
- product_with_rich_text_attr
+ product_with_rich_text_attr.search_vector = FlatConcat(
+ *prepare_product_search_vector_value(product_with_rich_text_attr)
)
product_with_rich_text_attr.save(update_fields=["search_vector"])
@@ -3232,8 +3235,8 @@ def test_products_query_with_filter_search_by_plain_text_attribute(
product_with_plain_text_attr.refresh_from_db()
- product_with_plain_text_attr.search_vector = prepare_product_search_vector_value(
- product_with_plain_text_attr
+ product_with_plain_text_attr.search_vector = FlatConcat(
+ *prepare_product_search_vector_value(product_with_plain_text_attr)
)
product_with_plain_text_attr.save(update_fields=["search_vector"])
@@ -3283,8 +3286,8 @@ def test_products_query_with_filter_search_by_numeric_attribute_value(
product_with_numeric_attr.refresh_from_db()
- product_with_numeric_attr.search_vector = prepare_product_search_vector_value(
- product_with_numeric_attr
+ product_with_numeric_attr.search_vector = FlatConcat(
+ *prepare_product_search_vector_value(product_with_numeric_attr)
)
product_with_numeric_attr.save(update_fields=["search_vector"])
@@ -3330,8 +3333,8 @@ def test_products_query_with_filter_search_by_numeric_attribute_value_without_un
product_with_numeric_attr.refresh_from_db()
- product_with_numeric_attr.search_vector = prepare_product_search_vector_value(
- product_with_numeric_attr
+ product_with_numeric_attr.search_vector = FlatConcat(
+ *prepare_product_search_vector_value(product_with_numeric_attr)
)
product_with_numeric_attr.save(update_fields=["search_vector"])
@@ -3378,8 +3381,8 @@ def test_products_query_with_filter_search_by_date_attribute_value(
product_with_date_attr.refresh_from_db()
- product_with_date_attr.search_vector = prepare_product_search_vector_value(
- product_with_date_attr
+ product_with_date_attr.search_vector = FlatConcat(
+ *prepare_product_search_vector_value(product_with_date_attr)
)
product_with_date_attr.save(update_fields=["search_vector"])
@@ -3426,8 +3429,8 @@ def test_products_query_with_filter_search_by_date_time_attribute_value(
product_with_date_time_attr.refresh_from_db()
- product_with_date_time_attr.search_vector = prepare_product_search_vector_value(
- product_with_date_time_attr
+ product_with_date_time_attr.search_vector = FlatConcat(
+ *prepare_product_search_vector_value(product_with_date_time_attr)
)
product_with_date_time_attr.save(update_fields=["search_vector"])
@@ -5326,7 +5329,7 @@ def test_search_product_by_description_and_name(
product_list.append(product)
for prod in product_list:
- prod.search_vector = prepare_product_search_vector_value(prod)
+ prod.search_vector = FlatConcat(*prepare_product_search_vector_value(prod))
Product.objects.bulk_update(
product_list,
@@ -5379,7 +5382,7 @@ def test_search_product_by_description_and_name_without_sort_by(
product_list.append(product)
for prod in product_list:
- prod.search_vector = prepare_product_search_vector_value(prod)
+ prod.search_vector = FlatConcat(*prepare_product_search_vector_value(prod))
Product.objects.bulk_update(
product_list,
@@ -5416,7 +5419,7 @@ def test_search_product_by_description_and_name_and_use_cursor(
product_list.append(product)
for prod in product_list:
- prod.search_vector = prepare_product_search_vector_value(prod)
+ prod.search_vector = FlatConcat(*prepare_product_search_vector_value(prod))
Product.objects.bulk_update(
product_list,
diff --git a/saleor/order/search.py b/saleor/order/search.py
index c80d1a019a..e34be381d9 100644
--- a/saleor/order/search.py
+++ b/saleor/order/search.py
@@ -1,13 +1,11 @@
-from functools import reduce
-from operator import add
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING, List
import graphene
from django.contrib.postgres.search import SearchQuery, SearchRank
from django.db.models import F, Q, Value, prefetch_related_objects
from ..account.search import generate_address_search_vector_value
-from ..core.postgres import NoValidationSearchVector
+from ..core.postgres import FlatConcat, NoValidationSearchVector
if TYPE_CHECKING:
from django.db.models import QuerySet
@@ -16,12 +14,14 @@ if TYPE_CHECKING:
def update_order_search_vector(order: "Order", *, save: bool = True):
- order.search_vector = prepare_order_search_vector_value(order)
+ order.search_vector = FlatConcat(*prepare_order_search_vector_value(order))
if save:
order.save(update_fields=["search_vector", "updated_at"])
-def prepare_order_search_vector_value(order: "Order", *, already_prefetched=False):
+def prepare_order_search_vector_value(
+ order: "Order", *, already_prefetched=False
+) -> List[NoValidationSearchVector]:
if not already_prefetched:
prefetch_related_objects(
[order],
@@ -32,51 +32,52 @@ def prepare_order_search_vector_value(order: "Order", *, already_prefetched=Fals
"discounts",
"lines",
)
- search_vector = NoValidationSearchVector(
- Value(str(order.number)), config="simple", weight="A"
- )
+ search_vectors = [
+ NoValidationSearchVector(Value(str(order.number)), config="simple", weight="A")
+ ]
if order.user_email:
- search_vector += NoValidationSearchVector(
- Value(order.user_email), config="simple", weight="A"
+ search_vectors.append(
+ NoValidationSearchVector(
+ Value(order.user_email), config="simple", weight="A"
+ )
)
if order.user:
- search_vector += NoValidationSearchVector(
- Value(order.user.email), config="simple", weight="A"
+ search_vectors.append(
+ NoValidationSearchVector(
+ Value(order.user.email), config="simple", weight="A"
+ )
)
if order.user.first_name:
- search_vector += NoValidationSearchVector(
- Value(order.user.first_name), config="simple", weight="A"
+ search_vectors.append(
+ NoValidationSearchVector(
+ Value(order.user.first_name), config="simple", weight="A"
+ )
)
if order.user.last_name:
- search_vector += NoValidationSearchVector(
- Value(order.user.last_name), config="simple", weight="A"
+ search_vectors.append(
+ NoValidationSearchVector(
+ Value(order.user.last_name), config="simple", weight="A"
+ )
)
if order.billing_address:
- search_vector += generate_address_search_vector_value(
+ search_vectors += generate_address_search_vector_value(
order.billing_address, weight="B"
)
if order.shipping_address:
- search_vector += generate_address_search_vector_value(
+ search_vectors += generate_address_search_vector_value(
order.shipping_address, weight="B"
)
- payment_vector = generate_order_payments_search_vector_value(order)
- if payment_vector:
- search_vector += payment_vector
- discount_vector = generate_order_discounts_search_vector_value(order)
- if discount_vector:
- search_vector += discount_vector
- line_vector = generate_order_lines_search_vector_value(order)
- if line_vector:
- search_vector += line_vector
-
- return search_vector
+ search_vectors += generate_order_payments_search_vector_value(order)
+ search_vectors += generate_order_discounts_search_vector_value(order)
+ search_vectors += generate_order_lines_search_vector_value(order)
+ return search_vectors
def generate_order_payments_search_vector_value(
order: "Order",
-) -> Optional[NoValidationSearchVector]:
+) -> List[NoValidationSearchVector]:
payment_vectors = []
for payment in order.payments.all():
payment_vectors.append(
@@ -94,18 +95,12 @@ def generate_order_payments_search_vector_value(
weight="D",
)
)
-
- if not payment_vectors:
- return None
-
- search_vector = reduce(add, payment_vectors)
-
- return search_vector
+ return payment_vectors
def generate_order_discounts_search_vector_value(
order: "Order",
-) -> Optional[NoValidationSearchVector]:
+) -> List[NoValidationSearchVector]:
discount_vectors = []
for discount in order.discounts.all():
if discount.name:
@@ -124,18 +119,12 @@ def generate_order_discounts_search_vector_value(
weight="D",
)
)
-
- if not discount_vectors:
- return None
-
- search_vector = reduce(add, discount_vectors)
-
- return search_vector
+ return discount_vectors
def generate_order_lines_search_vector_value(
order: "Order",
-) -> Optional[NoValidationSearchVector]:
+) -> List[NoValidationSearchVector]:
line_vectors = []
for line in order.lines.all():
if line.product_sku:
@@ -178,13 +167,7 @@ def generate_order_lines_search_vector_value(
weight="C",
)
)
-
- if not line_vectors:
- return None
-
- search_vector = reduce(add, line_vectors)
-
- return search_vector
+ return line_vectors
def search_orders(qs: "QuerySet[Order]", value) -> "QuerySet[Order]":
diff --git a/saleor/plugins/anonymize/plugin.py b/saleor/plugins/anonymize/plugin.py
index b19594937e..f89d8da0e9 100644
--- a/saleor/plugins/anonymize/plugin.py
+++ b/saleor/plugins/anonymize/plugin.py
@@ -6,6 +6,7 @@ from faker import Faker
from ...account import search
from ...core.anonymize import obfuscate_address
+from ...core.postgres import FlatConcat
from ...order.search import prepare_order_search_vector_value
from ..base_plugin import BasePlugin
from . import obfuscate_order
@@ -48,7 +49,7 @@ class AnonymizePlugin(BasePlugin):
def order_created(self, order: "Order", previous_value: Any):
order = obfuscate_order(order)
- order.search_vector = prepare_order_search_vector_value(order)
+ order.search_vector = FlatConcat(*prepare_order_search_vector_value(order))
order.save()
def customer_created(self, customer: "User", previous_value: Any) -> Any:
diff --git a/saleor/product/search.py b/saleor/product/search.py
index 2a3b0f869e..6d6a909281 100644
--- a/saleor/product/search.py
+++ b/saleor/product/search.py
@@ -1,22 +1,16 @@
-from functools import reduce
-from operator import add
-from typing import TYPE_CHECKING, Optional, Union
+from typing import TYPE_CHECKING, List
from django.contrib.postgres.search import SearchQuery, SearchRank
from django.db.models import F, Q, Value, prefetch_related_objects
from ..attribute import AttributeInputType
-from ..core.postgres import NoValidationSearchVector
+from ..core.postgres import FlatConcat, NoValidationSearchVector
from ..core.utils.editorjs import clean_editor_js
from .models import Product
if TYPE_CHECKING:
from django.db.models import QuerySet
- from ..attribute.models import AssignedProductAttribute, AssignedVariantAttribute
-
-ASSIGNED_ATTRIBUTE_TYPE = Union["AssignedProductAttribute", "AssignedVariantAttribute"]
-
PRODUCT_SEARCH_FIELDS = ["name", "description_plaintext"]
PRODUCT_FIELDS_TO_PREFETCH = [
"variants__attributes__values",
@@ -44,46 +38,40 @@ def update_products_search_vector(products: "QuerySet"):
prefetch_related_objects(products_batch, *PRODUCT_FIELDS_TO_PREFETCH)
for product in products_batch:
- product.search_vector = prepare_product_search_vector_value(
- product, already_prefetched=True
+ product.search_vector = FlatConcat(
+ *prepare_product_search_vector_value(product, already_prefetched=True)
)
Product.objects.bulk_update(products_batch, ["search_vector", "updated_at"])
def update_product_search_vector(product: "Product"):
- product.search_vector = prepare_product_search_vector_value(product)
+ product.search_vector = FlatConcat(*prepare_product_search_vector_value(product))
product.save(update_fields=["search_vector", "updated_at"])
def prepare_product_search_vector_value(
product: "Product", *, already_prefetched=False
-) -> NoValidationSearchVector:
+) -> List[NoValidationSearchVector]:
if not already_prefetched:
prefetch_related_objects([product], *PRODUCT_FIELDS_TO_PREFETCH)
- search_vector = NoValidationSearchVector(
- Value(product.name), config="simple", weight="A"
- ) + NoValidationSearchVector(
- Value(product.description_plaintext), config="simple", weight="C"
- )
- attributes_vector = generate_attributes_search_vector_value(
- product.attributes.all()
- )
- if attributes_vector:
- search_vector += attributes_vector
- variants_vector = generate_variants_search_vector_value(product)
- if variants_vector:
- search_vector += variants_vector
-
- return search_vector
+ search_vectors = [
+ NoValidationSearchVector(Value(product.name), config="simple", weight="A"),
+ NoValidationSearchVector(
+ Value(product.description_plaintext), config="simple", weight="C"
+ ),
+ *generate_attributes_search_vector_value(product.attributes.all()),
+ *generate_variants_search_vector_value(product),
+ ]
+ return search_vectors
def generate_variants_search_vector_value(
product: "Product",
-) -> Optional[NoValidationSearchVector]:
+) -> List[NoValidationSearchVector]:
variants = list(product.variants.all())
- variant_vectors = [
+ search_vectors = [
NoValidationSearchVector(
Value(variant.sku), Value(variant.name), config="simple", weight="A"
)
@@ -92,68 +80,69 @@ def generate_variants_search_vector_value(
for variant in variants
if variant.sku or variant.name
]
-
- if not variant_vectors:
- return None
-
- search_vector = reduce(add, variant_vectors)
-
- for variant in variants:
- attribute_vector = generate_attributes_search_vector_value(
- variant.attributes.all()
- )
- if attribute_vector:
- search_vector += attribute_vector
-
- return search_vector
+ if search_vectors:
+ for variant in variants:
+ search_vectors += generate_attributes_search_vector_value(
+ variant.attributes.all()
+ )
+ return search_vectors
def generate_attributes_search_vector_value(
assigned_attributes: "QuerySet",
-) -> Optional[NoValidationSearchVector]:
+) -> List[NoValidationSearchVector]:
"""Prepare `search_vector` value for assigned attributes.
Method should received assigned attributes with prefetched `values`
and `assignment__attribute`.
"""
- search_vector = None
+ search_vectors = []
for assigned_attribute in assigned_attributes:
attribute = assigned_attribute.assignment.attribute
input_type = attribute.input_type
values = assigned_attribute.values.all()
- values_list = []
if input_type in [AttributeInputType.DROPDOWN, AttributeInputType.MULTISELECT]:
- values_list = [value.name for value in values]
+ search_vectors += [
+ NoValidationSearchVector(Value(value.name), config="simple", weight="B")
+ for value in values
+ ]
elif input_type == AttributeInputType.RICH_TEXT:
- values_list = [
- clean_editor_js(value.rich_text, to_string=True) for value in values
+ search_vectors += [
+ NoValidationSearchVector(
+ Value(clean_editor_js(value.rich_text, to_string=True)),
+ config="simple",
+ weight="B",
+ )
+ for value in values
]
elif input_type == AttributeInputType.PLAIN_TEXT:
- values_list = [value.plain_text for value in values]
+ search_vectors += [
+ NoValidationSearchVector(
+ Value(value.plain_text), config="simple", weight="B"
+ )
+ for value in values
+ ]
elif input_type == AttributeInputType.NUMERIC:
unit = attribute.unit
- values_list = [
- value.name + " " + unit if unit else value.name for value in values
+ search_vectors += [
+ NoValidationSearchVector(
+ Value(value.name + " " + unit if unit else value.name),
+ config="simple",
+ weight="B",
+ )
+ for value in values
]
elif input_type in [AttributeInputType.DATE, AttributeInputType.DATE_TIME]:
- values_list = [
- value.date_time.strftime("%Y-%m-%d %H:%M:%S") for value in values
+ search_vectors += [
+ NoValidationSearchVector(
+ Value(value.date_time.strftime("%Y-%m-%d %H:%M:%S")),
+ config="simple",
+ weight="B",
+ )
+ for value in values
]
-
- if values_list:
- new_vector = reduce(
- add,
- (
- NoValidationSearchVector(Value(v), config="simple", weight="B")
- for v in values_list
- ),
- )
- if search_vector is not None:
- search_vector += new_vector
- else:
- search_vector = new_vector
- return search_vector
+ return search_vectors
def search_products(qs, value):
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index a9ad4f03dc..307dd684b0 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -44,6 +44,7 @@ from ..checkout.utils import add_variant_to_checkout, add_voucher_to_checkout
from ..core import EventDeliveryStatus, JobStatus
from ..core.models import EventDelivery, EventDeliveryAttempt, EventPayload
from ..core.payments import PaymentInterface
+from ..core.postgres import FlatConcat
from ..core.taxes import zero_money
from ..core.units import MeasurementUnits
from ..core.utils.editorjs import clean_editor_js
@@ -904,7 +905,7 @@ def order(customer_user, channel_USD):
@pytest.fixture
def order_with_search_vector_value(order):
- order.search_vector = prepare_order_search_vector_value(order)
+ order.search_vector = FlatConcat(*prepare_order_search_vector_value(order))
order.save(update_fields=["search_vector"])
return order
@@ -2302,7 +2303,7 @@ def product_with_two_variants(product_type, category, warehouse, channel_USD):
for variant in variants
]
)
- product.search_vector = prepare_product_search_vector_value(product)
+ product.search_vector = FlatConcat(*prepare_product_search_vector_value(product))
product.save(update_fields=["search_vector"])
return product
@@ -2518,7 +2519,7 @@ def product_with_default_variant(
)
Stock.objects.create(warehouse=warehouse, product_variant=variant, quantity=100)
- product.search_vector = prepare_product_search_vector_value(product)
+ product.search_vector = FlatConcat(*prepare_product_search_vector_value(product))
product.save(update_fields=["search_vector"])
return product
@@ -2932,7 +2933,9 @@ def product_list(product_type, category, warehouse, channel_USD, channel_PLN):
for product in products:
associate_attribute_values_to_instance(product, product_attr, attr_value)
- product.search_vector = prepare_product_search_vector_value(product)
+ product.search_vector = FlatConcat(
+ *prepare_product_search_vector_value(product)
+ )
Product.objects.bulk_update(products, ["search_vector"])
@@ -5889,7 +5892,7 @@ def allocations(order_list, stock, channel_USD):
)
for order in order_list:
- order.search_vector = prepare_order_search_vector_value(order)
+ order.search_vector = FlatConcat(*prepare_order_search_vector_value(order))
Order.objects.bulk_update(order_list, ["search_vector"])
return Allocation.objects.bulk_create(