Skip to content

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

Catch update_fields did not affect any rows errors and return response with message (#9225)

l3str4ngee85f83b4c7ef
diff --git a/.isort.cfg b/.isort.cfg
index a07b817657..5e5f561ac0 100644
--- a/.isort.cfg
+++ b/.isort.cfg
@@ -1,2 +1,2 @@
[settings]
-known_third_party = Adyen,PIL,authorizenet,babel,boto3,botocore,braintree,celery,cryptography,dateutil,dj_database_url,dj_email_url,django,django_cache_url,django_countries,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,faker,freezegun,google,google_measurement_protocol,graphene,graphql,graphql_relay,html2text,html_to_draftjs,i18naddress,jaeger_client,jwt,kombu,lxml,markdown,measurement,micawber,mptt,oauthlib,openpyxl,opentracing,petl,phonenumber_field,phonenumbers,pkg_resources,posuto,prices,promise,pybars,pytest,pythonjsonlogger,pytimeparse,pytz,razorpay,requests,sendgrid,sentry_sdk,storages,stripe,urllib3,uvicorn,versatileimagefield,weasyprint
+known_third_party = Adyen,PIL,authorizenet,babel,before_after,boto3,botocore,braintree,celery,cryptography,dateutil,dj_database_url,dj_email_url,django,django_cache_url,django_countries,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,faker,freezegun,google,google_measurement_protocol,graphene,graphql,graphql_relay,html2text,html_to_draftjs,i18naddress,jaeger_client,jwt,kombu,lxml,markdown,measurement,micawber,mptt,oauthlib,openpyxl,opentracing,petl,phonenumber_field,phonenumbers,pkg_resources,posuto,prices,promise,pybars,pytest,pythonjsonlogger,pytimeparse,pytz,razorpay,requests,sendgrid,sentry_sdk,storages,stripe,urllib3,uvicorn,versatileimagefield,weasyprint
diff --git a/requirements_dev.txt b/requirements_dev.txt
index 246e836448..8000f0a422 100644
--- a/requirements_dev.txt
+++ b/requirements_dev.txt
@@ -10,6 +10,7 @@ authorizenet==1.1.4
babel==2.9.1; (python_version >= "2.7" and python_full_version < "3.0.0") or (python_full_version >= "3.4.0")
beautifulsoup4==4.7.1
beautifultable==0.7.0
+before-after==1.0.1
billiard==3.6.4.0; python_version >= "3.7"
black==22.1.0; python_full_version >= "3.6.2"
boto3==1.21.22; python_version >= "3.6"
diff --git a/saleor/core/error_codes.py b/saleor/core/error_codes.py
index e0fcda3cd6..f5e6458534 100644
--- a/saleor/core/error_codes.py
+++ b/saleor/core/error_codes.py
@@ -16,6 +16,7 @@ class MetadataErrorCode(Enum):
INVALID = "invalid"
NOT_FOUND = "not_found"
REQUIRED = "required"
+ NOT_UPDATED = "not_updated"
class TranslationErrorCode(Enum):
diff --git a/saleor/graphql/meta/mutations.py b/saleor/graphql/meta/mutations.py
index 04a90d31f0..d4a1fdaa87 100644
--- a/saleor/graphql/meta/mutations.py
+++ b/saleor/graphql/meta/mutations.py
@@ -1,7 +1,9 @@
+import logging
from typing import List
import graphene
from django.core.exceptions import FieldDoesNotExist, ValidationError
+from django.db import DatabaseError
from graphql.error.base import GraphQLError
from ...checkout import models as checkout_models
@@ -22,6 +24,8 @@ from .extra_methods import MODEL_EXTRA_METHODS, MODEL_EXTRA_PREFETCH
from .permissions import PRIVATE_META_PERMISSION_MAP, PUBLIC_META_PERMISSION_MAP
from .types import ObjectWithMetadata
+logger = logging.getLogger(__name__)
+
def _save_instance(instance, metadata_field: str):
fields = [metadata_field]
@@ -32,7 +36,25 @@ def _save_instance(instance, metadata_field: str):
except FieldDoesNotExist:
pass
- instance.save(update_fields=fields)
+ try:
+ instance.save(update_fields=fields)
+ except DatabaseError as e:
+ msg = (
+ "Cannot update metadata for instance: %s. "
+ "Updating not existing object. "
+ "Details: %s.",
+ instance,
+ str(e),
+ )
+ logger.warning(msg)
+ raise ValidationError(
+ {
+ "metadata": ValidationError(
+ msg,
+ code=MetadataErrorCode.NOT_FOUND.value,
+ )
+ }
+ )
class MetadataPermissionOptions(graphene.types.mutation.MutationOptions):
@@ -72,6 +94,7 @@ class BaseMetadataMutation(BaseMutation):
# ShippingMethodType represents the ShippingMethod model
if type_name == "ShippingMethodType":
qs = shipping_models.ShippingMethod.objects
+
return cls.get_node_or_error(info, object_id, qs=qs)
except GraphQLError as e:
if instance := cls.get_instance_by_token(object_id, qs):
@@ -260,6 +283,7 @@ class UpdateMetadata(BaseMetadataMutation):
items = {data.key: data.value for data in metadata_list}
instance.store_value_in_metadata(items=items)
_save_instance(instance, "metadata")
+
return cls.success_response(instance)
diff --git a/saleor/graphql/meta/tests/test_meta_mutations.py b/saleor/graphql/meta/tests/test_meta_mutations.py
index f499e75882..3aae0c55a4 100644
--- a/saleor/graphql/meta/tests/test_meta_mutations.py
+++ b/saleor/graphql/meta/tests/test_meta_mutations.py
@@ -1,10 +1,13 @@
import base64
from unittest.mock import patch
+import before_after
import graphene
import pytest
from django.core.exceptions import ValidationError
+from django.db import transaction
+from ....checkout.models import Checkout
from ....core.error_codes import MetadataErrorCode
from ....core.models import ModelWithMetadata
from ....invoice.models import Invoice
@@ -52,6 +55,7 @@ def execute_update_public_metadata_for_item(
item_type,
key=PUBLIC_KEY,
value=PUBLIC_VALUE,
+ ignore_errors=False,
):
variables = {
"id": item_id,
@@ -63,7 +67,7 @@ def execute_update_public_metadata_for_item(
variables,
permissions=[permissions] if permissions else None,
)
- response = get_graphql_content(response)
+ response = get_graphql_content(response, ignore_errors=ignore_errors)
return response
@@ -753,6 +757,34 @@ def test_update_public_metadata_for_item(api_client, checkout):
)
[email protected]_db(transaction=True)
+def test_update_public_metadata_for_item_on_deleted_instance(api_client, checkout):
+ checkout.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
+ checkout.save(update_fields=["metadata"])
+
+ def delete_checkout_object(*args, **kwargs):
+ with transaction.atomic():
+ Checkout.objects.filter(pk=checkout.pk).delete()
+
+ with before_after.before(
+ "saleor.graphql.meta.mutations._save_instance", delete_checkout_object
+ ):
+ response = execute_update_public_metadata_for_item(
+ api_client,
+ None,
+ checkout.token,
+ "Checkout",
+ value="NewMetaValue",
+ ignore_errors=True,
+ )
+
+ assert not Checkout.objects.filter(pk=checkout.pk).first()
+ assert (
+ response["data"]["updateMetadata"]["errors"][0]["code"]
+ == MetadataErrorCode.NOT_FOUND.name
+ )
+
+
def test_update_public_metadata_for_non_exist_item(
staff_api_client, permission_manage_payments
):
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index 69cec23144..4f88fc3d22 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -73,6 +73,7 @@ from ..utils import (
get_draft_order_lines_data_for_variants,
get_used_attribute_values_for_variant,
get_used_variants_attribute_values,
+ update_ordered_media,
)
@@ -1620,9 +1621,7 @@ class ProductMediaReorder(BaseMutation):
)
ordered_media.append(media)
- for order, media in enumerate(ordered_media):
- media.sort_order = order
- media.save(update_fields=["sort_order"])
+ update_ordered_media(ordered_media)
info.context.plugins.product_updated(product)
product = ChannelContext(node=product, channel_slug=None)
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index fdf7cafd47..d6eac63c3e 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -5,10 +5,12 @@ from decimal import Decimal
from unittest import mock
from unittest.mock import ANY, Mock, patch
+import before_after
import graphene
import pytest
import pytz
from django.core.exceptions import ValidationError
+from django.db import transaction
from django.db.models import Sum
from django.utils import timezone
from django.utils.dateparse import parse_datetime
@@ -9815,6 +9817,52 @@ def test_reorder_media(
product_updated_mock.assert_called_once_with(product)
[email protected]_db(transaction=True)
+def test_reorder_not_existing_media(
+ staff_api_client,
+ product_with_images,
+ permission_manage_products,
+):
+ query = """
+ mutation reorderMedia($product_id: ID!, $media_ids: [ID]!) {
+ productMediaReorder(productId: $product_id, mediaIds: $media_ids) {
+ product {
+ id
+ }
+ errors{
+ field
+ code
+ message
+ }
+ }
+ }
+ """
+ product = product_with_images
+ media = product.media.all()
+ media_0 = media[0]
+ media_1 = media[1]
+ media_0_id = graphene.Node.to_global_id("ProductMedia", media_0.id)
+ media_1_id = graphene.Node.to_global_id("ProductMedia", media_1.id)
+ product_id = graphene.Node.to_global_id("Product", product.id)
+
+ def delete_media(*args, **kwargs):
+ with transaction.atomic():
+ media.delete()
+
+ with before_after.before(
+ "saleor.graphql.product.mutations.products.update_ordered_media", delete_media
+ ):
+ variables = {"product_id": product_id, "media_ids": [media_1_id, media_0_id]}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ response = get_graphql_content(response, ignore_errors=True)
+ assert (
+ response["data"]["productMediaReorder"]["errors"][0]["code"]
+ == ProductErrorCode.NOT_FOUND.name
+ )
+
+
ASSIGN_VARIANT_QUERY = """
mutation assignVariantMediaMutation($variantId: ID!, $mediaId: ID!) {
variantMediaAssign(variantId: $variantId, mediaId: $mediaId) {
diff --git a/saleor/graphql/product/utils.py b/saleor/graphql/product/utils.py
index f55ebc40ab..134ab0c289 100644
--- a/saleor/graphql/product/utils.py
+++ b/saleor/graphql/product/utils.py
@@ -3,18 +3,24 @@ from typing import TYPE_CHECKING, Dict, Iterable, List, Optional
import graphene
from django.core.exceptions import ValidationError
+from django.db import DatabaseError, transaction
from django.db.utils import IntegrityError
from ...core.tracing import traced_atomic_transaction
from ...order import OrderStatus
from ...order import models as order_models
from ...warehouse.models import Stock
+from ..core.enums import ProductErrorCode
if TYPE_CHECKING:
from django.db.models import QuerySet
from ...product.models import ProductVariant
+import logging
+
+logger = logging.getLogger(__name__)
+
def get_used_attribute_values_for_variant(variant):
"""Create a dict of attributes values for variant.
@@ -111,3 +117,27 @@ def clean_variant_sku(sku: Optional[str]) -> Optional[str]:
if sku:
return sku.strip() or None
return None
+
+
+def update_ordered_media(ordered_media):
+ errors = defaultdict(list)
+ with transaction.atomic():
+ for order, media in enumerate(ordered_media):
+ media.sort_order = order
+ try:
+ media.save(update_fields=["sort_order"])
+ except DatabaseError as e:
+ msg = (
+ "Cannot update media for instance: %s. "
+ "Updating not existing object. "
+ "Details: %s.",
+ media,
+ str(e),
+ )
+ logger.warning(msg)
+ errors["media"].append(
+ ValidationError(msg, code=ProductErrorCode.NOT_FOUND.value)
+ )
+
+ if errors:
+ raise ValidationError(errors)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index baf81c55b0..7559a7e537 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -3863,6 +3863,7 @@ enum MetadataErrorCode {
INVALID
NOT_FOUND
REQUIRED
+ NOT_UPDATED
}
input MetadataFilter {