1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
|
import django
from django.contrib.auth.models import User
from django.contrib.postgres.search import SearchVectorField
from django.db import connections, models
from django.utils import timezone
from psqlextra.models import PostgresPartitionedModel
from psqlextra.types import PostgresPartitioningMethod
import pgtrigger
import pgtrigger.utils
def _get_pg_maj_version(db): # pragma: no cover
connection = connections[db]
if connection.vendor == "postgresql":
with connection.cursor() as cursor:
return pgtrigger.utils.pg_maj_version(cursor)
class Router:
route_app_labels = ["tests"]
def allow_migrate(self, db, app_label, model_name=None, **hints):
"""
Ignore the parititon model for the "other" DB, for non-Postgres DBs,
and for Postgres DBs that are less than version 13
"""
pg_maj_version = _get_pg_maj_version(db)
if model_name == "partitionmodel" and (
db in ("sqlite", "other") or not pg_maj_version or pg_maj_version < 13
):
return False
class PartitionModel(PostgresPartitionedModel):
class PartitioningMeta:
method = PostgresPartitioningMethod.RANGE
key = ["timestamp"]
name = models.TextField()
timestamp = models.DateTimeField()
class Meta:
triggers = [pgtrigger.Protect(name="protect_delete", operation=pgtrigger.Delete)]
class OrderSchema(models.Model):
"""A model that only appears in the "schema1" schema"""
int_field = models.IntegerField()
class ReceiptSchema(models.Model):
"""A model that only appears in the "schema2" schema"""
char_field = models.CharField(max_length=128)
class Meta:
db_table = "table.with.dots"
class SearchModel(models.Model):
body_vector = SearchVectorField()
title_body_vector = SearchVectorField()
title = models.CharField(max_length=128)
body = models.TextField()
class Meta:
triggers = [
pgtrigger.UpdateSearchVector(
name="add_body_to_vector", vector_field="body_vector", document_fields=["body"]
),
pgtrigger.UpdateSearchVector(
name="add_body_title_to_vector",
vector_field="title_body_vector",
document_fields=["body", "title"],
),
]
@pgtrigger.register(
pgtrigger.Protect(name="protect_delete", operation=pgtrigger.Delete),
)
class CustomTableName(models.Model):
int_field = models.IntegerField(null=True, unique=True)
class Meta:
db_table = "order"
class TestModel(models.Model):
int_field = models.IntegerField(null=True, unique=True)
char_field = models.CharField(max_length=128, null=True)
float_field = models.FloatField(null=True)
class Meta:
unique_together = ("int_field", "char_field")
class LogEntry(models.Model):
"""Created when ToLogModel is updated"""
level = models.CharField(max_length=16)
old_field = models.CharField(max_length=16, null=True)
new_field = models.CharField(max_length=16, null=True)
class ToLogModel(models.Model):
"""For testing triggers that log records at statement and row level"""
field = models.CharField(max_length=16)
class Meta:
triggers = [
pgtrigger.Trigger(
name="update_of_statement_test",
level=pgtrigger.Statement,
operation=pgtrigger.UpdateOf("field"),
when=pgtrigger.After,
func=pgtrigger.Func(
f"""
INSERT INTO {LogEntry._meta.db_table}(level)
VALUES ('STATEMENT');
RETURN NULL;
"""
),
),
pgtrigger.Trigger(
name="after_update_statement_test",
level=pgtrigger.Statement,
operation=pgtrigger.Update,
when=pgtrigger.After,
referencing=pgtrigger.Referencing(old="old_values", new="new_values"),
func=f"""
INSERT INTO {LogEntry._meta.db_table}(level, old_field, new_field)
SELECT 'STATEMENT' AS level,
old_values.field AS old_field,
new_values.field AS new_field
FROM old_values
JOIN new_values ON old_values.id = new_values.id;
RETURN NULL;
""",
),
pgtrigger.Trigger(
name="after_update_row_test",
level=pgtrigger.Row,
operation=pgtrigger.Update,
when=pgtrigger.After,
condition=pgtrigger.Q(old__field__df=pgtrigger.F("new__field")),
func=(
f"INSERT INTO {LogEntry._meta.db_table}(level) VALUES ('ROW'); RETURN NULL;"
),
),
]
class CharPk(models.Model):
custom_pk = models.CharField(primary_key=True, max_length=32)
class TestTrigger(models.Model):
"""
For testing triggers
"""
field = models.CharField(max_length=16)
int_field = models.IntegerField(default=0)
dt_field = models.DateTimeField(default=timezone.now)
nullable = models.CharField(null=True, default=None, max_length=16)
fk_field = models.ForeignKey("auth.User", null=True, on_delete=models.CASCADE)
char_pk_fk_field = models.ForeignKey(CharPk, null=True, on_delete=models.CASCADE)
m2m_field = models.ManyToManyField(User, related_name="+")
class Meta:
triggers = [
pgtrigger.Trigger(
name="protect_misc_insert",
when=pgtrigger.Before,
operation=pgtrigger.Insert,
func="RAISE EXCEPTION 'no no no!';",
condition=pgtrigger.Q(new__field="misc_insert"),
),
]
class TestTriggerProxy(TestTrigger):
"""
For testing triggers on proxy models
"""
class Meta:
proxy = True
triggers = [
pgtrigger.Protect(name="protect_delete", operation=pgtrigger.Delete),
]
class TestDefaultThrough(TestTrigger.m2m_field.through):
class Meta:
proxy = True
triggers = [
pgtrigger.Protect(name="protect_it", operation=pgtrigger.Delete),
]
@pgtrigger.register(pgtrigger.SoftDelete(name="soft_delete", field="is_active"))
class SoftDelete(models.Model):
"""
For testing soft deletion. Deletions on this model will set
is_active = False without deleting the model
"""
is_active = models.BooleanField(default=True)
other_field = models.TextField()
class FkToSoftDelete(models.Model):
"""Ensures foreign keys to a soft delete model are deleted"""
ref = models.ForeignKey(SoftDelete, on_delete=models.CASCADE)
if django.VERSION >= (5, 2):
@pgtrigger.register(pgtrigger.SoftDelete(name="soft_delete_composite_pk", field="is_active"))
class SoftDeleteCompositePk(models.Model):
"""
For testing soft deletion with a composite primary key.
"""
id_1 = models.IntegerField()
id_2 = models.IntegerField()
pk = models.CompositePrimaryKey("id_1", "id_2")
is_active = models.BooleanField(default=True)
other_field = models.TextField()
@pgtrigger.register(pgtrigger.SoftDelete(name="soft_delete", field="custom_active"))
class CustomSoftDelete(models.Model):
"""
For testing soft deletion with a custom active field.
This trigger also helps ensure that triggers can have the same names
across multiple models.
"""
custom_active = models.BooleanField(default=True)
other_field = models.TextField()
@pgtrigger.register(
pgtrigger.FSM(
name="fsm",
field="transition",
transitions=[("unpublished", "published"), ("published", "inactive")],
)
)
class FSM(models.Model):
"""Tests valid transitions of a field"""
transition = models.CharField(max_length=32)
class ChangedCondition(models.Model):
"""
For testing changed conditions
"""
field = models.CharField(max_length=16)
int_field = models.IntegerField(default=0)
dt_field = models.DateTimeField(auto_now=True)
nullable = models.CharField(null=True, default=None, max_length=16)
fk_field = models.ForeignKey("auth.User", null=True, on_delete=models.CASCADE)
char_pk_fk_field = models.ForeignKey(CharPk, null=True, on_delete=models.CASCADE)
m2m_field = models.ManyToManyField(User, related_name="+")
class ConcreteChild(ChangedCondition):
child_field = models.CharField(max_length=16)
class AbstractChangedCondition(models.Model):
"""
For testing changed conditions
"""
field = models.CharField(max_length=16)
int_field = models.IntegerField(default=0)
dt_field = models.DateTimeField(auto_now=True)
nullable = models.CharField(null=True, default=None, max_length=16)
fk_field = models.ForeignKey("auth.User", null=True, on_delete=models.CASCADE)
char_pk_fk_field = models.ForeignKey(CharPk, null=True, on_delete=models.CASCADE)
m2m_field = models.ManyToManyField(User, related_name="+")
class Meta:
abstract = True
class AbstractChild(AbstractChangedCondition):
child_field = models.CharField(max_length=16)
|