Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion pghistory/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
import copy
import re
import sys
import warnings
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type, Union

import django
import pgtrigger
import pgtrigger.core
from django.apps import apps
from django.conf import settings
from django.db import connections, models
from django.db.models import sql
from django.db.models.fields.related import RelatedField
Expand Down Expand Up @@ -46,6 +48,26 @@ def quote(self, obj):
_registered_trackers = {}


# avoid default trigger name duplication
def _simplify_trigger_names() -> bool:
"""Return True if simplified trigger names are enabled.

Reads PGHISTORY_SIMPLIFY_TRIGGER_NAMES from Django settings at call time
so that override_settings() works correctly in tests and avoids emitting
a DeprecationWarning at module import time.
"""
enabled = getattr(settings, "PGHISTORY_SIMPLIFY_TRIGGER_NAMES", False)
if not enabled:
warnings.warn(
"Trigger names like 'update_update' are deprecated. "
"Set PGHISTORY_SIMPLIFY_TRIGGER_NAMES=True to enable simplified names. "
"This will become the default in a future release.",
DeprecationWarning,
stacklevel=2,
)
return enabled


class Tracker:
"""For tracking an event when a condition happens on a model."""

Expand Down Expand Up @@ -107,9 +129,20 @@ def __init__(
self.condition = condition if condition is not constants.UNSET else self.condition
self.operation = operation or self.operation
self.row = row or self.row
self.trigger_name = trigger_name or self.trigger_name or f"{self.label}_{self.operation}"
self.level = level if level is not None else self.level

simplify = _simplify_trigger_names()

if trigger_name:
self.trigger_name = trigger_name
elif self.trigger_name:
self.trigger_name = self.trigger_name
else:
if simplify and self.label == self.operation:
self.trigger_name = str(self.operation)
else:
self.trigger_name = f"{self.label}_{self.operation}"

if self.condition is constants.UNSET:
self.condition = pgtrigger.AnyChange() if self.operation == pgtrigger.Update else None

Expand Down
62 changes: 62 additions & 0 deletions pghistory/tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import pytest
from django.apps import apps
from django.db import DatabaseError, models
from django.test.utils import override_settings
from django.utils import timezone

import pghistory
Expand Down Expand Up @@ -879,3 +880,64 @@ def test_conditional_statement_trigger():
first = test_models.CondStatement.objects.order_by("id").first()
test_models.CondStatement.objects.filter(id=first.id).update(id=first.id + 1000, int_field1=-1)
assert test_models.CondStatementEvent.objects.all().count() == 15


@pytest.mark.django_db
def test_warning_when_simplifying_trigger_names_disabled():
import warnings

with override_settings(PGHISTORY_SIMPLIFY_TRIGGER_NAMES=False):
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
# Instantiating UpdateEvent triggers _simplify_trigger_names() internally
pghistory.core.UpdateEvent()

matching = [
w
for w in caught
if issubclass(w.category, DeprecationWarning) and "Trigger names" in str(w.message)
]
assert matching, "Expected a DeprecationWarning about trigger names"


@pytest.mark.django_db
def test_no_warning_when_simplifying_trigger_names_enabled():
import warnings

with override_settings(PGHISTORY_SIMPLIFY_TRIGGER_NAMES=True):
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
pghistory.core.UpdateEvent()

matching = [
w
for w in caught
if issubclass(w.category, DeprecationWarning) and "Trigger names" in str(w.message)
]
assert not matching, "Expected no DeprecationWarning when simplification is enabled"


@pytest.mark.django_db
def test_trigger_name_resolution():
tracker = pghistory.core.UpdateEvent(trigger_name="my_custom_trigger")
assert tracker.trigger_name == "my_custom_trigger"

# already defined
# 1. label == operation → trigger_name = str(operation)
class MyEvent(pghistory.core.UpdateEvent):
trigger_name = "class_level_trigger"

tracker = MyEvent()
assert tracker.trigger_name == "class_level_trigger"

with override_settings(PGHISTORY_SIMPLIFY_TRIGGER_NAMES=True):
tracker = pghistory.core.UpdateEvent() # label="update", operation=Update
assert tracker.trigger_name == str(pgtrigger.Update)

with override_settings(PGHISTORY_SIMPLIFY_TRIGGER_NAMES=False):
import warnings

with warnings.catch_warnings(record=True):
warnings.simplefilter("always")
tracker = pghistory.core.UpdateEvent(label="snapshot") # label != operation
assert tracker.trigger_name == f"snapshot_{pgtrigger.Update}"