mirror of
https://github.com/pretix/pretix.git
synced 2026-11-23 03:21:55 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7961c000d7 |
No files matched your search
@@ -24,6 +24,7 @@ import uuid
|
||||
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
from django.db import models
|
||||
from django.db.models.constants import LOOKUP_SEP
|
||||
from django.db.models.signals import post_delete
|
||||
from django.dispatch import receiver
|
||||
from django.urls import reverse
|
||||
@@ -244,3 +245,49 @@ class LoggedModel(models.Model, LoggingMixin):
|
||||
return LogEntry.objects.filter(
|
||||
content_type=self.logs_content_type, object_id=self.pk
|
||||
).select_related('user', 'event', 'event__organizer', 'oauth_application', 'api_token', 'device')
|
||||
|
||||
|
||||
class LockModel:
|
||||
def refresh_for_update(self, fields=None, using=None, **kwargs):
|
||||
"""
|
||||
Like refresh_from_db(), but with select_for_update().
|
||||
See also https://code.djangoproject.com/ticket/28344
|
||||
"""
|
||||
if fields is not None:
|
||||
if not fields:
|
||||
return
|
||||
if any(LOOKUP_SEP in f for f in fields):
|
||||
raise ValueError(
|
||||
'Found "%s" in fields argument. Relations and transforms '
|
||||
'are not allowed in fields.' % LOOKUP_SEP)
|
||||
|
||||
hints = {'instance': self}
|
||||
db_instance_qs = self.__class__._base_manager.db_manager(using, hints=hints).filter(pk=self.pk).select_for_update(**kwargs)
|
||||
|
||||
# Use provided fields, if not set then reload all non-deferred fields.
|
||||
deferred_fields = self.get_deferred_fields()
|
||||
if fields is not None:
|
||||
fields = list(fields)
|
||||
db_instance_qs = db_instance_qs.only(*fields)
|
||||
elif deferred_fields:
|
||||
fields = [f.attname for f in self._meta.concrete_fields
|
||||
if f.attname not in deferred_fields]
|
||||
db_instance_qs = db_instance_qs.only(*fields)
|
||||
|
||||
db_instance = db_instance_qs.get()
|
||||
non_loaded_fields = db_instance.get_deferred_fields()
|
||||
for field in self._meta.concrete_fields:
|
||||
if field.attname in non_loaded_fields:
|
||||
# This field wasn't refreshed - skip ahead.
|
||||
continue
|
||||
setattr(self, field.attname, getattr(db_instance, field.attname))
|
||||
# Clear cached foreign keys.
|
||||
if field.is_relation and field.is_cached(self):
|
||||
field.delete_cached_value(self)
|
||||
|
||||
# Clear cached relations.
|
||||
for field in self._meta.related_objects:
|
||||
if field.is_cached(self):
|
||||
field.delete_cached_value(self)
|
||||
|
||||
self._state.db = db_instance._state.db
|
||||
@@ -93,7 +93,7 @@ from ...testutils.middleware import debugflags_var
|
||||
from ._transactions import (
|
||||
_fail, _transactions_mark_order_clean, _transactions_mark_order_dirty,
|
||||
)
|
||||
from .base import LoggedModel
|
||||
from .base import LockModel, LoggedModel
|
||||
from .event import Event, SubEvent
|
||||
from .items import Item, ItemVariation, Question, QuestionOption, Quota
|
||||
|
||||
@@ -136,7 +136,7 @@ class OrderQuerySet(models.QuerySet):
|
||||
return order
|
||||
|
||||
|
||||
class Order(LoggedModel):
|
||||
class Order(LockModel, LoggedModel):
|
||||
"""
|
||||
An order is created when a user clicks 'buy' on his cart. It holds
|
||||
several OrderPositions and is connected to a user. It has an
|
||||
|
||||
@@ -28,6 +28,7 @@ from django.db import DatabaseError, connection
|
||||
from django.utils.timezone import now
|
||||
|
||||
from pretix.base.models import Event, Membership, Quota, Seat, Voucher
|
||||
from pretix.helpers import OF_SELF
|
||||
from pretix.testutils.middleware import debugflags_var
|
||||
|
||||
logger = logging.getLogger('pretix.base.locking')
|
||||
@@ -119,7 +120,7 @@ def lock_objects(objects, *, shared_lock_objects=None, replace_exclusive_with_sh
|
||||
|
||||
else:
|
||||
for model, instances in groupby(objects, key=lambda o: type(o)):
|
||||
model.objects.select_for_update().filter(pk__in=[o.pk for o in instances])
|
||||
model.objects.select_for_update(of=OF_SELF).filter(pk__in=[o.pk for o in instances])
|
||||
|
||||
|
||||
class NoLockManager:
|
||||
|
||||
@@ -30,6 +30,8 @@ class PretixHelpersConfig(AppConfig):
|
||||
from .monkeypatching import monkeypatch_all_at_ready
|
||||
monkeypatch_all_at_ready()
|
||||
|
||||
from .database import guard_select_for_update # noqa
|
||||
|
||||
# Ensure reportlab does not make any calls to the internet or the local disk
|
||||
from reportlab import rl_config
|
||||
rl_config.trustedHosts = []
|
||||
|
||||
@@ -20,22 +20,32 @@
|
||||
# <https://www.gnu.org/licenses/>.
|
||||
#
|
||||
import contextlib
|
||||
import logging
|
||||
import re
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.postgres.indexes import BrinIndex
|
||||
from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured
|
||||
from django.db import connection, transaction
|
||||
from django.db.backends.signals import connection_created
|
||||
from django.db.models import (
|
||||
Aggregate, Expression, F, Field, Func, IntegerField, JSONField, Lookup,
|
||||
OrderBy, Value,
|
||||
)
|
||||
from django.dispatch import receiver
|
||||
from django.utils.functional import lazy
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DummyRollbackException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class UnsafeSQLQueryException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def rolledback_transaction():
|
||||
"""
|
||||
@@ -324,3 +334,21 @@ class UnixTimestamp(Func):
|
||||
|
||||
def as_sqlite(self, compiler, connection):
|
||||
return self.as_sql(compiler, connection, template="CAST(strftime('%%%%s', datetime(%(expressions)s)) AS INT)")
|
||||
|
||||
|
||||
REGEX = re.compile(r'FOR (NO KEY )?UPDATE(?! OF)')
|
||||
|
||||
|
||||
def query_wrapper_select_for_update(execute, sql, params, many, context):
|
||||
if REGEX.search(sql) and "JOIN" in sql:
|
||||
if settings.DEBUG:
|
||||
raise UnsafeSQLQueryException("Never use 'FOR UPDATE' without 'OF' if query causes any JOINs")
|
||||
else:
|
||||
logger.warning("SQL used 'FOR UPDATE' without 'OF' if query causes any JOINs", stack_info=True)
|
||||
return execute(sql, params, many, context)
|
||||
|
||||
|
||||
@receiver(connection_created)
|
||||
def guard_select_for_update(sender, connection, **kwargs):
|
||||
if query_wrapper_select_for_update not in connection.execute_wrappers:
|
||||
connection.execute_wrappers.append(query_wrapper_select_for_update)
|
||||
@@ -0,0 +1,94 @@
|
||||
#
|
||||
# This file is part of pretix (Community Edition).
|
||||
#
|
||||
# Copyright (C) 2014-2020 Raphael Michel and contributors
|
||||
# Copyright (C) 2020-today pretix GmbH and contributors
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
|
||||
# Public License as published by the Free Software Foundation in version 3 of the License.
|
||||
#
|
||||
# ADDITIONAL TERMS APPLY: Pursuant to Section 7 of the GNU Affero General Public License, additional terms are
|
||||
# applicable granting you additional permissions and placing additional restrictions on your usage of this software.
|
||||
# Please refer to the pretix LICENSE file to obtain the full terms applicable to this work. If you did not receive
|
||||
# this file, see <https://pretix.eu/about/en/license>.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
|
||||
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
|
||||
# details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License along with this program. If not, see
|
||||
# <https://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
import pytest
|
||||
from django.conf import settings
|
||||
from django.test import override_settings
|
||||
from django_scopes import scope, scopes_disabled
|
||||
|
||||
from pretix.base.models import Organizer
|
||||
from pretix.base.models.orders import Order, OrderPayment
|
||||
from pretix.helpers import OF_SELF, UnsafeSQLQueryException
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def pg_only():
|
||||
if 'postgres' not in settings.DATABASES['default']['ENGINE']:
|
||||
pytest.skip("Test only runs on PostgreSQL")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def organizer():
|
||||
return Organizer.objects.create(name="Dummy", slug="dummy")
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@override_settings(DEBUG=True)
|
||||
def test_fail_on_debug(pg_only, organizer):
|
||||
with scope(organizer=organizer):
|
||||
with pytest.raises(UnsafeSQLQueryException):
|
||||
list(OrderPayment.objects.select_for_update()) # join added by django-scopes
|
||||
with pytest.raises(UnsafeSQLQueryException):
|
||||
list(Order.objects.select_related("event").select_for_update())
|
||||
with pytest.raises(UnsafeSQLQueryException):
|
||||
list(Order.objects.filter(event__slug="test").select_for_update())
|
||||
with pytest.raises(UnsafeSQLQueryException):
|
||||
list(Order.objects.filter(event__slug="test").select_for_update(no_key=True))
|
||||
with pytest.raises(UnsafeSQLQueryException):
|
||||
list(Order.objects.filter(event__slug="test").select_for_update(nowait=True))
|
||||
with pytest.raises(UnsafeSQLQueryException):
|
||||
list(Order.objects.filter(event__slug="test").select_for_update(skip_locked=True))
|
||||
with pytest.raises(UnsafeSQLQueryException):
|
||||
list(Order.objects.filter(event__slug="test").select_for_update(nowait=True, no_key=True))
|
||||
with pytest.raises(UnsafeSQLQueryException):
|
||||
list(Order.objects.filter(event__slug="test").select_for_update(skip_locked=True, no_key=True))
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@override_settings(DEBUG=True)
|
||||
def test_ok_with_of(pg_only, organizer):
|
||||
with scope(organizer=organizer):
|
||||
list(OrderPayment.objects.select_for_update(of=OF_SELF)) # join added by django-scopes
|
||||
list(Order.objects.select_related("event").select_for_update(of=OF_SELF))
|
||||
list(Order.objects.filter(event__slug="test").select_for_update(of=OF_SELF))
|
||||
list(Order.objects.filter(event__slug="test").select_for_update(of=OF_SELF, no_key=True))
|
||||
list(Order.objects.filter(event__slug="test").select_for_update(of=OF_SELF, nowait=True))
|
||||
list(Order.objects.filter(event__slug="test").select_for_update(of=OF_SELF, skip_locked=True))
|
||||
list(Order.objects.filter(event__slug="test").select_for_update(of=OF_SELF, nowait=True, no_key=True))
|
||||
list(Order.objects.filter(event__slug="test").select_for_update(of=OF_SELF, skip_locked=True, no_key=True))
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@override_settings(DEBUG=True)
|
||||
def test_ok_without_join(pg_only, organizer):
|
||||
with scope(organizer=organizer):
|
||||
assert list(Order.objects.select_for_update()) == []
|
||||
with scopes_disabled():
|
||||
assert list(OrderPayment.objects.select_for_update()) == []
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@override_settings(DEBUG=False)
|
||||
def test_fail_silently_without_debug(pg_only, organizer):
|
||||
with scope(organizer=organizer):
|
||||
list(OrderPayment.objects.select_for_update()) # join added by django-scopes
|
||||
list(Order.objects.select_related("event").select_for_update())
|
||||
Reference in new issue
Block a user