devadmin 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. devadmin/__init__.py +19 -0
  2. devadmin/__main__.py +5 -0
  3. devadmin/adapters/__init__.py +0 -0
  4. devadmin/adapters/base.py +175 -0
  5. devadmin/adapters/tortoise/__init__.py +81 -0
  6. devadmin/adapters/tortoise/introspect.py +209 -0
  7. devadmin/adapters/tortoise/models.py +34 -0
  8. devadmin/adapters/tortoise/queries.py +330 -0
  9. devadmin/adapters/tortoise/related.py +215 -0
  10. devadmin/adapters/tortoise/store.py +156 -0
  11. devadmin/auth/__init__.py +16 -0
  12. devadmin/auth/csrf.py +18 -0
  13. devadmin/auth/ip.py +28 -0
  14. devadmin/auth/login.py +149 -0
  15. devadmin/auth/session.py +94 -0
  16. devadmin/cli.py +314 -0
  17. devadmin/config.py +34 -0
  18. devadmin/core/__init__.py +0 -0
  19. devadmin/core/binding.py +609 -0
  20. devadmin/core/forms.py +475 -0
  21. devadmin/core/listing.py +400 -0
  22. devadmin/core/options.py +99 -0
  23. devadmin/core/paths.py +39 -0
  24. devadmin/core/site.py +288 -0
  25. devadmin/core/values.py +122 -0
  26. devadmin/history/__init__.py +38 -0
  27. devadmin/history/diff.py +109 -0
  28. devadmin/history/encoding.py +120 -0
  29. devadmin/history/records.py +40 -0
  30. devadmin/history/render.py +129 -0
  31. devadmin/history/service.py +256 -0
  32. devadmin/web/__init__.py +0 -0
  33. devadmin/web/app.py +106 -0
  34. devadmin/web/deps.py +275 -0
  35. devadmin/web/guard.py +178 -0
  36. devadmin/web/static/autocomplete.js +231 -0
  37. devadmin/web/static/devadmin.css +1645 -0
  38. devadmin/web/static/devadmin.js +129 -0
  39. devadmin/web/static/htmx.min.js +1 -0
  40. devadmin/web/static/icons/check.svg +1 -0
  41. devadmin/web/static/icons/clock.svg +1 -0
  42. devadmin/web/static/icons/cross.svg +1 -0
  43. devadmin/web/static/icons/down.svg +1 -0
  44. devadmin/web/static/icons/eye.svg +1 -0
  45. devadmin/web/static/icons/lock.svg +1 -0
  46. devadmin/web/static/icons/pencil.svg +1 -0
  47. devadmin/web/static/icons/plus.svg +1 -0
  48. devadmin/web/static/icons/right.svg +1 -0
  49. devadmin/web/static/icons/trash.svg +1 -0
  50. devadmin/web/static/icons/up.svg +1 -0
  51. devadmin/web/templates/_field.html +35 -0
  52. devadmin/web/templates/_history.html +19 -0
  53. devadmin/web/templates/_pagination.html +8 -0
  54. devadmin/web/templates/action_confirm.html +26 -0
  55. devadmin/web/templates/base.html +63 -0
  56. devadmin/web/templates/delete.html +62 -0
  57. devadmin/web/templates/error.html +9 -0
  58. devadmin/web/templates/form.html +34 -0
  59. devadmin/web/templates/history.html +59 -0
  60. devadmin/web/templates/index.html +49 -0
  61. devadmin/web/templates/list.html +88 -0
  62. devadmin/web/templates/login.html +15 -0
  63. devadmin/web/templates/recent.html +25 -0
  64. devadmin/web/views_auth.py +146 -0
  65. devadmin/web/views_delete.py +774 -0
  66. devadmin/web/views_form.py +551 -0
  67. devadmin/web/views_history.py +261 -0
  68. devadmin/web/views_list.py +246 -0
  69. devadmin-0.1.0.dist-info/METADATA +702 -0
  70. devadmin-0.1.0.dist-info/RECORD +73 -0
  71. devadmin-0.1.0.dist-info/WHEEL +4 -0
  72. devadmin-0.1.0.dist-info/entry_points.txt +3 -0
  73. devadmin-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,330 @@
1
+ from collections.abc import Mapping
2
+ from decimal import DecimalException
3
+ from typing import Any
4
+
5
+ from pypika_tortoise import Table
6
+ from pypika_tortoise.functions import Function
7
+ from tortoise.exceptions import ValidationError
8
+ from tortoise.expressions import Q, Subquery
9
+ from tortoise.fields import DecimalField
10
+ from tortoise.models import Model
11
+ from tortoise.queryset import QuerySet
12
+ from tortoise.signals import Signals
13
+
14
+ from devadmin.adapters.base import Choice, FieldInfo, FieldType, Filter, Order, Query, RejectedValue
15
+ from devadmin.adapters.tortoise.introspect import describe, field_type, parse_pk, repr_of
16
+
17
+ _REJECTED_FILTER_VALUE = "a filter or search value is not acceptable for its field"
18
+
19
+ _LOOKUP_SUFFIXES = {
20
+ "eq": "",
21
+ "iexact": "__iexact",
22
+ "istartswith": "__istartswith",
23
+ "icontains": "__icontains",
24
+ "isnull": "__isnull",
25
+ "in": "__in",
26
+ }
27
+
28
+
29
+ def _fields(model: type[Model]) -> dict[str, FieldInfo]:
30
+ return {info.name: info for info in describe(model)}
31
+
32
+
33
+ def _resolve(model: type[Model], path: str) -> tuple[str, bool]:
34
+ segments = path.split("__")
35
+ current = model
36
+ parts = []
37
+ to_many = False
38
+ for index, segment in enumerate(segments):
39
+ info = _fields(current).get(segment)
40
+ if info is None:
41
+ raise ValueError(f"unknown field {segment!r} in path {path!r}")
42
+ field = current._meta.fields_map[segment]
43
+ last = index == len(segments) - 1
44
+ if info.type is FieldType.FK:
45
+ if last:
46
+ parts.append(field.source_field)
47
+ else:
48
+ parts.append(segment)
49
+ current = field.related_model
50
+ elif info.type is FieldType.M2M:
51
+ to_many = True
52
+ parts.append(segment)
53
+ current = field.related_model
54
+ if last:
55
+ parts.append(current._meta.pk_attr)
56
+ elif last:
57
+ parts.append(segment)
58
+ else:
59
+ raise ValueError(f"{segment!r} in path {path!r} is not a relation")
60
+ return "__".join(parts), to_many
61
+
62
+
63
+ def _condition(model: type[Model], flt: Filter) -> tuple[Q, bool]:
64
+ if flt.op not in _LOOKUP_SUFFIXES:
65
+ raise ValueError(f"unknown filter op {flt.op!r}")
66
+ lookup, to_many = _resolve(model, flt.path)
67
+ return Q(**{lookup + _LOOKUP_SUFFIXES[flt.op]: flt.value}), to_many
68
+
69
+
70
+ def _ordering(model: type[Model], order: Order) -> str:
71
+ lookup, to_many = _resolve(model, order.path)
72
+ if to_many:
73
+ raise ValueError(f"cannot order by {order.path!r}: it crosses a to-many relation")
74
+ return ("-" if order.descending else "") + lookup
75
+
76
+
77
+ def _join(model: type[Model], path: str) -> str:
78
+ current = model
79
+ for segment in path.split("__"):
80
+ info = _fields(current).get(segment)
81
+ if info is None or info.type is not FieldType.FK:
82
+ raise ValueError(f"{segment!r} in join {path!r} is not a foreign key")
83
+ current = current._meta.fields_map[segment].related_model
84
+ return path
85
+
86
+
87
+ def _filtered(model: type[Model], query: Query) -> QuerySet:
88
+ queryset = model.all()
89
+ to_many = False
90
+ for flt in query.filters:
91
+ condition, crosses = _condition(model, flt)
92
+ queryset = queryset.filter(condition)
93
+ to_many = to_many or crosses
94
+ for group in query.search:
95
+ if not group:
96
+ continue
97
+ conditions = []
98
+ for flt in group:
99
+ condition, crosses = _condition(model, flt)
100
+ conditions.append(condition)
101
+ to_many = to_many or crosses
102
+ queryset = queryset.filter(Q(*conditions, join_type="OR"))
103
+ if not to_many:
104
+ return queryset
105
+ key = model._meta.pk_attr
106
+ return model.filter(**{f"{key}__in": Subquery(queryset.values(key))})
107
+
108
+
109
+ async def query(model: type[Model], query: Query, offset: int, limit: int) -> list[Any]:
110
+ try:
111
+ queryset = _filtered(model, query)
112
+ orderings = [_ordering(model, order) for order in query.ordering]
113
+ joins = [_join(model, path) for path in query.joins]
114
+ if orderings:
115
+ queryset = queryset.order_by(*orderings)
116
+ if joins:
117
+ queryset = queryset.select_related(*joins)
118
+ return await queryset.offset(offset).limit(limit)
119
+ except ValidationError:
120
+ raise RejectedValue(_REJECTED_FILTER_VALUE) from None
121
+
122
+
123
+ async def count(model: type[Model], query: Query) -> int:
124
+ try:
125
+ return await _filtered(model, query).count()
126
+ except ValidationError:
127
+ raise RejectedValue(_REJECTED_FILTER_VALUE) from None
128
+
129
+
130
+ async def estimate_count(model: type[Model]) -> int | None:
131
+ connection = model._meta.db
132
+ if connection.capabilities.dialect != "postgres":
133
+ return None
134
+ pg_class = Table("pg_class")
135
+ statement = (
136
+ connection.query_class.from_(pg_class)
137
+ .select(pg_class.reltuples)
138
+ .where(pg_class.relname == model._meta.db_table)
139
+ )
140
+ if model._meta.schema:
141
+ pg_namespace = Table("pg_namespace")
142
+ statement = (
143
+ statement.join(pg_namespace)
144
+ .on(pg_namespace.oid == pg_class.relnamespace)
145
+ .where(pg_namespace.nspname == model._meta.schema)
146
+ )
147
+ else:
148
+ statement = statement.where(Function("pg_table_is_visible", pg_class.oid))
149
+ rows = await connection.execute_query_dict(*statement.get_parameterized_sql())
150
+ if not rows or rows[0]["reltuples"] < 0:
151
+ return None
152
+ return int(rows[0]["reltuples"])
153
+
154
+
155
+ async def get(model: type[Model], pk: Any) -> Any | None:
156
+ return await model.get_or_none(**{model._meta.pk_attr: pk})
157
+
158
+
159
+ def _attributes(model: type[Model], data: dict[str, Any], allow_pk: bool) -> dict[str, tuple[str, Any]]:
160
+ fields = _fields(model)
161
+ attributes = {}
162
+ for name, value in data.items():
163
+ info = fields.get(name)
164
+ if info is None or not info.editable:
165
+ raise ValueError(f"{name!r} is not a writable field of {model.__name__}")
166
+ if info.pk and not allow_pk:
167
+ raise ValueError(f"the primary key {name!r} of {model.__name__} cannot be changed")
168
+ attribute = model._meta.fields_map[name].source_field if info.type is FieldType.FK else name
169
+ attributes[name] = (attribute, value)
170
+ for name, (_, value) in attributes.items():
171
+ if value is None and not fields[name].nullable:
172
+ raise RejectedValue(f"{fields[name].label} is required")
173
+ return attributes
174
+
175
+
176
+ def _json_names(model: type[Model]) -> set[str]:
177
+ return {name for name, field in model._meta.fields_map.items() if field_type(field) is FieldType.JSON}
178
+
179
+
180
+ def _json_texts(obj: Model, names: set[str]) -> dict[str, tuple[str, str]]:
181
+ texts = {}
182
+ for name in names:
183
+ value = getattr(obj, name, None)
184
+ if isinstance(value, str):
185
+ texts[name] = (obj._meta.fields_map[name].encoder(value), value)
186
+ return texts
187
+
188
+
189
+ def _saves_other_columns(model: type[Model]) -> bool:
190
+ for klass in model.__mro__:
191
+ if klass is Model:
192
+ break
193
+ if "save" in vars(klass):
194
+ return True
195
+ listeners = getattr(model, "_listeners", None)
196
+ if not isinstance(listeners, Mapping):
197
+ return True
198
+ pre_save = listeners.get(Signals.pre_save, {})
199
+ if not isinstance(pre_save, Mapping):
200
+ return True
201
+ return bool(pre_save.get(model))
202
+
203
+
204
+ def _auto_now_names(model: type[Model]) -> list[str]:
205
+ return [name for name, field in model._meta.fields_map.items() if getattr(field, "auto_now", False)]
206
+
207
+
208
+ def _out_of_range(model: type[Model], values: Mapping[str, Any]) -> str | None:
209
+ for name, value in values.items():
210
+ field = model._meta.fields_map.get(name)
211
+ if not isinstance(field, DecimalField) or value is None:
212
+ continue
213
+ try:
214
+ field.to_python_value(value)
215
+ except DecimalException:
216
+ labels = {info.name: info.label for info in describe(model)}
217
+ return f"{labels.get(name, name)} is out of range"
218
+ return None
219
+
220
+
221
+ def _check_numbers(model: type[Model], values: Mapping[str, Any]) -> None:
222
+ message = _out_of_range(model, values)
223
+ if message is not None:
224
+ raise RejectedValue(message)
225
+
226
+
227
+ async def _save(obj: Model, texts: dict[str, tuple[str, str]], update_fields: list[str] | None = None) -> None:
228
+ for name, (text, _) in texts.items():
229
+ setattr(obj, name, text)
230
+ try:
231
+ if update_fields is None:
232
+ await obj.save()
233
+ else:
234
+ await obj.save(update_fields=update_fields)
235
+ finally:
236
+ for name, (_, value) in texts.items():
237
+ setattr(obj, name, value)
238
+
239
+
240
+ async def create(model: type[Model], data: dict[str, Any]) -> Any:
241
+ attributes = _attributes(model, data, allow_pk=True)
242
+ json_names = _json_names(model)
243
+ strings = {name for name, (_, value) in attributes.items() if name in json_names and isinstance(value, str)}
244
+ written = {name: value for name, (_, value) in attributes.items()}
245
+ _check_numbers(model, written)
246
+ obj = model(**{attribute: value for name, (attribute, value) in attributes.items() if name not in strings})
247
+ for name in strings:
248
+ setattr(obj, name, attributes[name][1])
249
+ await _save(obj, _json_texts(obj, strings))
250
+ for name in json_names - attributes.keys():
251
+ value = getattr(obj, name, None)
252
+ if isinstance(value, str):
253
+ setattr(obj, name, obj._meta.fields_map[name].to_python_value(value))
254
+ return obj
255
+
256
+
257
+ async def update(obj: Model, data: dict[str, Any]) -> Any:
258
+ if not data:
259
+ return obj
260
+ model = type(obj)
261
+ attributes = _attributes(model, data, allow_pk=False)
262
+ values = {name: value for name, (_, value) in attributes.items()}
263
+ _check_numbers(model, values)
264
+ relations = obj._meta.fk_fields | obj._meta.o2o_fields
265
+ for name, (attribute, value) in attributes.items():
266
+ setattr(obj, attribute, value)
267
+ if name in relations and hasattr(obj, f"_{name}"):
268
+ delattr(obj, f"_{name}")
269
+ if _saves_other_columns(model):
270
+ await _save(obj, _json_texts(obj, _json_names(model)))
271
+ return obj
272
+ written = [attribute for attribute, _ in attributes.values()]
273
+ update_fields = list(dict.fromkeys([*written, *_auto_now_names(model)]))
274
+ await _save(obj, _json_texts(obj, _json_names(model) & attributes.keys()), update_fields)
275
+ return obj
276
+
277
+
278
+ async def delete(obj: Model) -> None:
279
+ await obj.delete()
280
+
281
+
282
+ def _fk_field(model: type[Model], name: str) -> Any:
283
+ info = _fields(model).get(name)
284
+ if info is None or info.type is not FieldType.FK:
285
+ raise ValueError(f"{name!r} is not a foreign key of {model.__name__}")
286
+ return model._meta.fields_map[name]
287
+
288
+
289
+ async def related_choices(model: type[Model], field: str, term: str, limit: int) -> list[Choice]:
290
+ relation = _fk_field(model, field)
291
+ target = relation.related_model
292
+ key = target._meta.pk_attr
293
+ queryset = target.all()
294
+ if term:
295
+ conditions = [
296
+ Q(**{f"{info.name}__istartswith": term})
297
+ for info in describe(target)
298
+ if info.type is FieldType.STR and info.unique
299
+ ]
300
+ try:
301
+ conditions.append(Q(**{key: parse_pk(target, term)}))
302
+ except ValueError:
303
+ pass
304
+ if not conditions:
305
+ return []
306
+ queryset = queryset.filter(Q(*conditions, join_type="OR"))
307
+ rows = await queryset.order_by(key).limit(limit)
308
+ return [Choice(pk=getattr(row, relation.to_field), label=repr_of(row)) for row in rows]
309
+
310
+
311
+ async def fk_reprs(obj: Model) -> dict[str, str]:
312
+ model = type(obj)
313
+ wanted: dict[type[Model], dict[str, dict[Any, list[str]]]] = {}
314
+ for info in describe(model):
315
+ if info.type is not FieldType.FK:
316
+ continue
317
+ relation = model._meta.fields_map[info.name]
318
+ value = getattr(obj, relation.source_field)
319
+ if value is None:
320
+ continue
321
+ by_key = wanted.setdefault(relation.related_model, {})
322
+ by_key.setdefault(relation.to_field, {}).setdefault(value, []).append(info.name)
323
+ reprs = {}
324
+ for target, by_key in wanted.items():
325
+ condition = Q(*[Q(**{f"{key}__in": list(values)}) for key, values in by_key.items()], join_type="OR")
326
+ for row in await target.filter(condition):
327
+ for key, values in by_key.items():
328
+ for name in values.get(getattr(row, key), []):
329
+ reprs[name] = repr_of(row)
330
+ return reprs
@@ -0,0 +1,215 @@
1
+ from collections.abc import Iterable
2
+ from typing import Any
3
+
4
+ from pypika_tortoise import Criterion, Table
5
+ from pypika_tortoise.functions import Count
6
+ from tortoise import Tortoise
7
+ from tortoise.expressions import F, Q
8
+ from tortoise.fields.base import OnDelete
9
+ from tortoise.fields.relational import ForeignKeyFieldInstance, ManyToManyFieldInstance
10
+ from tortoise.models import Model
11
+ from tortoise.queryset import QuerySet
12
+
13
+ from devadmin.adapters.base import M2MLinks, RelatedRow, RelatedRows
14
+ from devadmin.adapters.tortoise.introspect import _key_field, model_key, repr_of, to_dict
15
+
16
+ MAX_BLOCKING_ROWS = 100
17
+
18
+ _CASCADING = {OnDelete.CASCADE}
19
+ _UNLINKING = {OnDelete.SET_NULL, OnDelete.SET_DEFAULT}
20
+ _BLOCKING = {OnDelete.RESTRICT, OnDelete.NO_ACTION}
21
+
22
+ Rows = dict[type[Model], dict[Any, Model]]
23
+ NulledFields = dict[tuple[type[Model], Any], str]
24
+
25
+
26
+ def _references(target: type[Model], rules: set[OnDelete]) -> list[tuple[type[Model], ForeignKeyFieldInstance]]:
27
+ return [
28
+ (model, field)
29
+ for models in Tortoise.apps.values()
30
+ for model in models.values()
31
+ for field in model._meta.fields_map.values()
32
+ if isinstance(field, ForeignKeyFieldInstance)
33
+ and field.related_model is target
34
+ and field.source_field in model._meta.fields_db_projection
35
+ and field.db_constraint
36
+ and field.on_delete in rules
37
+ ]
38
+
39
+
40
+ def _add(rows: Rows, row: Model) -> None:
41
+ rows.setdefault(type(row), {})[row.pk] = row
42
+
43
+
44
+ def _keys(model: type[Model], *groups: Rows) -> set[Any]:
45
+ return {pk for group in groups for pk in group.get(model, {})}
46
+
47
+
48
+ def _count(rows: Rows) -> int:
49
+ return sum(len(by_pk) for by_pk in rows.values())
50
+
51
+
52
+ def _stored_attribute(field: ForeignKeyFieldInstance) -> str:
53
+ referenced = field.to_field_instance
54
+ if isinstance(referenced, ForeignKeyFieldInstance):
55
+ return referenced.source_field
56
+ return field.to_field
57
+
58
+
59
+ def referenced_value(parent: Model, field: ForeignKeyFieldInstance) -> Any:
60
+ return getattr(parent, _stored_attribute(field))
61
+
62
+
63
+ def _referencing(
64
+ model: type[Model], field: ForeignKeyFieldInstance, parents: Iterable[Model], exclude: set[Any]
65
+ ) -> QuerySet | None:
66
+ values = list(dict.fromkeys(referenced_value(parent, field) for parent in parents))
67
+ values = [value for value in values if value is not None]
68
+ if not values:
69
+ return None
70
+ queryset = model.filter(**{f"{field.source_field}__in": values})
71
+ if exclude:
72
+ queryset = queryset.exclude(**{f"{model._meta.pk_attr}__in": list(exclude)})
73
+ return queryset
74
+
75
+
76
+ async def _fetch(
77
+ model: type[Model], field: ForeignKeyFieldInstance, parents: Iterable[Model], exclude: set[Any], limit: int
78
+ ) -> list[Model]:
79
+ queryset = _referencing(model, field, parents, exclude)
80
+ return [] if queryset is None else await queryset.limit(limit)
81
+
82
+
83
+ async def _cascade(removed: Rows, cascaded: Rows, limit: int) -> bool:
84
+ pending = [row for by_pk in removed.values() for row in by_pk.values()]
85
+ while pending:
86
+ target = type(pending[0])
87
+ batch = [row for row in pending if type(row) is target]
88
+ pending = [row for row in pending if type(row) is not target]
89
+ for model, field in _references(target, _CASCADING):
90
+ rows = await _fetch(model, field, batch, _keys(model, removed), limit + 1 - _count(cascaded))
91
+ for row in rows:
92
+ _add(removed, row)
93
+ _add(cascaded, row)
94
+ pending.append(row)
95
+ if _count(cascaded) > limit:
96
+ return True
97
+ return False
98
+
99
+
100
+ async def _block(removed: Rows, blocking: Rows) -> None:
101
+ for target, parents in removed.items():
102
+ for model, field in _references(target, _BLOCKING):
103
+ room = MAX_BLOCKING_ROWS - _count(blocking)
104
+ if room <= 0:
105
+ return
106
+ queryset = _referencing(model, field, parents.values(), _keys(model, blocking))
107
+ if queryset is None:
108
+ continue
109
+ if model is target:
110
+ stored = _stored_attribute(field)
111
+ elsewhere = ~Q(**{field.source_field: F(stored)})
112
+ queryset = queryset.filter(Q(elsewhere, Q(**{f"{stored}__isnull": True}), join_type="OR"))
113
+ for row in await queryset.order_by(model._meta.pk_attr).limit(room):
114
+ _add(blocking, row)
115
+
116
+
117
+ async def _unlink(removed: Rows, blocking: Rows, nulled: Rows, nulled_fields: NulledFields, limit: int) -> bool:
118
+ for target, parents in removed.items():
119
+ for model, field in _references(target, _UNLINKING):
120
+ exclude = _keys(model, removed, blocking, nulled)
121
+ for row in await _fetch(model, field, parents.values(), exclude, limit + 1 - _count(nulled)):
122
+ _add(nulled, row)
123
+ nulled_fields[(model, row.pk)] = field.model_field_name
124
+ if _count(nulled) > limit:
125
+ return True
126
+ return False
127
+
128
+
129
+ def _without(rows: Rows, other: Rows) -> Rows:
130
+ return {
131
+ model: {pk: row for pk, row in by_pk.items() if pk not in other.get(model, {})}
132
+ for model, by_pk in rows.items()
133
+ }
134
+
135
+
136
+ def _related_rows(rows: Rows, nulled_fields: NulledFields | None = None) -> list[RelatedRow]:
137
+ related = [
138
+ RelatedRow(
139
+ model_key=model_key(model),
140
+ pk=row.pk,
141
+ repr=repr_of(row),
142
+ raw=to_dict(row),
143
+ nulled_field=nulled_fields[(model, row.pk)] if nulled_fields is not None else None,
144
+ )
145
+ for model, by_pk in rows.items()
146
+ for row in by_pk.values()
147
+ ]
148
+ return sorted(related, key=lambda item: (item.model_key, item.pk))
149
+
150
+
151
+ async def collect_related(objs: list[Model], limit: int) -> RelatedRows:
152
+ removed: Rows = {}
153
+ for obj in objs:
154
+ _add(removed, obj)
155
+ cascaded: Rows = {}
156
+ blocking: Rows = {}
157
+ nulled: Rows = {}
158
+ nulled_fields: NulledFields = {}
159
+ truncated = await _cascade(removed, cascaded, limit)
160
+ if not truncated:
161
+ await _block(removed, blocking)
162
+ truncated = await _unlink(removed, blocking, nulled, nulled_fields, limit - _count(cascaded))
163
+ return RelatedRows(
164
+ cascaded=_related_rows(_without(cascaded, blocking)),
165
+ nulled=_related_rows(nulled, nulled_fields),
166
+ blocking=_related_rows(blocking),
167
+ truncated=truncated,
168
+ )
169
+
170
+
171
+ def _stored_keys(model: type[Model], pks: list[Any]) -> list[Any]:
172
+ key = _key_field(model)
173
+ return list(dict.fromkeys(key.to_db_value(pk, model) for pk in pks))
174
+
175
+
176
+ def _link_count_statement(model: type[Model], field: ManyToManyFieldInstance, own: list[Any], other: list[Any]) -> Any:
177
+ table = Table(field.through)
178
+ conditions = []
179
+ if own:
180
+ conditions.append(table[field.backward_key].isin(own))
181
+ if other:
182
+ conditions.append(table[field.forward_key].isin(other))
183
+ return model._meta.db.query_class.from_(table).select(Count("*").as_("count")).where(Criterion.any(conditions))
184
+
185
+
186
+ def _removed_with_its_ends(field: ManyToManyFieldInstance) -> bool:
187
+ return bool(field.db_constraint) and field.on_delete == OnDelete.CASCADE
188
+
189
+
190
+ async def _count_links(model: type[Model], field: ManyToManyFieldInstance, own: list[Any], other: list[Any]) -> int:
191
+ statement = _link_count_statement(model, field, own, other)
192
+ rows = await model._meta.db.execute_query_dict(*statement.get_parameterized_sql())
193
+ return int(rows[0]["count"])
194
+
195
+
196
+ async def m2m_links(objs: list[Model]) -> list[M2MLinks]:
197
+ pks: dict[type[Model], list[Any]] = {}
198
+ for obj in objs:
199
+ pks.setdefault(type(obj), []).append(obj.pk)
200
+ links = []
201
+ for models in Tortoise.apps.values():
202
+ for model in models.values():
203
+ for name in model._meta.m2m_fields:
204
+ field = model._meta.fields_map[name]
205
+ if field._generated or not _removed_with_its_ends(field):
206
+ continue
207
+ other_model = field.related_model
208
+ own = _stored_keys(model, pks.get(model, []))
209
+ other = _stored_keys(other_model, pks.get(other_model, []))
210
+ if not own and not other:
211
+ continue
212
+ count = await _count_links(model, field, own, other)
213
+ if count:
214
+ links.append(M2MLinks(model_key(model), name, model_key(other_model), count))
215
+ return sorted(links, key=lambda link: (link.model_key, link.field))
@@ -0,0 +1,156 @@
1
+ from collections import defaultdict
2
+ from datetime import datetime
3
+ from typing import Any
4
+
5
+ from tortoise import connections, timezone
6
+ from tortoise.backends.base.client import BaseDBAsyncClient
7
+ from tortoise.expressions import Subquery
8
+ from tortoise.transactions import in_transaction
9
+
10
+ from devadmin.adapters.tortoise.models import DevadminAction, DevadminChange
11
+ from devadmin.history.records import (
12
+ ACTION_KINDS,
13
+ ACTION_SOURCES,
14
+ CHANGE_OPS,
15
+ ActionRecord,
16
+ ChangeRecord,
17
+ HistoryEntry,
18
+ )
19
+
20
+ TEXT_LENGTH = 255
21
+ ACTOR_ID_LENGTH = 64
22
+ IP_LENGTH = 45
23
+
24
+
25
+ class TortoiseHistoryStore:
26
+ def __init__(self, connection_name: str | None = None) -> None:
27
+ self.connection_name = connection_name
28
+
29
+ def _connection_name(self) -> str | None:
30
+ return self.connection_name or DevadminAction._meta.default_connection
31
+
32
+ async def insert(self, action: ActionRecord, changes: list[ChangeRecord]) -> int:
33
+ action_row = _action_row(action)
34
+ change_rows = [_change_row(change) for change in changes]
35
+ async with in_transaction(self._connection_name()) as connection:
36
+ saved = await DevadminAction.create(using_db=connection, **action_row)
37
+ if change_rows:
38
+ await DevadminChange.bulk_create(
39
+ [DevadminChange(action_id=saved.id, **row) for row in change_rows], using_db=connection
40
+ )
41
+ return saved.id
42
+
43
+ async def object_history(
44
+ self, model_key: str, object_pk: str, offset: int, limit: int
45
+ ) -> list[HistoryEntry]:
46
+ connection = connections.get(self._connection_name())
47
+ touched = DevadminChange.filter(model_key=model_key, object_pk=object_pk).values("action_id")
48
+ actions = (
49
+ await DevadminAction.filter(id__in=Subquery(touched))
50
+ .using_db(connection)
51
+ .order_by("-id")
52
+ .offset(offset)
53
+ .limit(limit)
54
+ )
55
+ return await _entries(connection, actions, {"model_key": model_key, "object_pk": object_pk})
56
+
57
+ async def recent(self, offset: int, limit: int) -> list[HistoryEntry]:
58
+ connection = connections.get(self._connection_name())
59
+ actions = await DevadminAction.all().using_db(connection).order_by("-id").offset(offset).limit(limit)
60
+ return await _entries(connection, actions, {})
61
+
62
+ async def purge(self, older_than: datetime, batch: int = 500) -> int:
63
+ if older_than.utcoffset() is None:
64
+ raise ValueError("older_than must be an aware datetime")
65
+ if batch < 1:
66
+ raise ValueError("batch must be at least 1")
67
+ cutoff = older_than.astimezone(timezone.now().tzinfo)
68
+ removed = 0
69
+ while True:
70
+ async with in_transaction(self._connection_name()) as connection:
71
+ ids = (
72
+ await DevadminAction.filter(created_at__lt=cutoff)
73
+ .using_db(connection)
74
+ .order_by("id")
75
+ .limit(batch)
76
+ .values_list("id", flat=True)
77
+ )
78
+ if ids:
79
+ await DevadminChange.filter(action_id__in=ids).using_db(connection).delete()
80
+ await DevadminAction.filter(id__in=ids).using_db(connection).delete()
81
+ removed += len(ids)
82
+ if len(ids) < batch:
83
+ return removed
84
+
85
+
86
+ async def _entries(
87
+ connection: BaseDBAsyncClient, actions: list[DevadminAction], only: dict[str, str]
88
+ ) -> list[HistoryEntry]:
89
+ if not actions:
90
+ return []
91
+ rows = (
92
+ await DevadminChange.filter(action_id__in=[action.id for action in actions], **only)
93
+ .using_db(connection)
94
+ .order_by("id")
95
+ )
96
+ changes: dict[int, list[ChangeRecord]] = defaultdict(list)
97
+ for row in rows:
98
+ changes[row.action_id].append(
99
+ ChangeRecord(
100
+ model_key=row.model_key,
101
+ object_pk=row.object_pk,
102
+ object_repr=row.object_repr,
103
+ op=row.op,
104
+ changes=row.changes,
105
+ snapshot=row.snapshot,
106
+ field_labels=row.field_labels,
107
+ )
108
+ )
109
+ return [
110
+ HistoryEntry(
111
+ action_id=action.id,
112
+ created_at=action.created_at,
113
+ actor_repr=action.actor_repr,
114
+ kind=action.kind,
115
+ summary=action.summary,
116
+ source=action.source,
117
+ changes=changes[action.id],
118
+ )
119
+ for action in actions
120
+ ]
121
+
122
+
123
+ def _bounded(value: str | None, length: int, name: str) -> str | None:
124
+ if value is not None and len(value) > length:
125
+ raise ValueError(f"{name} is longer than {length} characters")
126
+ return value
127
+
128
+
129
+ def _action_row(action: ActionRecord) -> dict[str, Any]:
130
+ if action.kind not in ACTION_KINDS:
131
+ raise ValueError(f"unknown action kind {action.kind!r}")
132
+ if action.source not in ACTION_SOURCES:
133
+ raise ValueError(f"unknown action source {action.source!r}")
134
+ return {
135
+ "actor_id": _bounded(action.actor_id, ACTOR_ID_LENGTH, "actor_id"),
136
+ "actor_repr": action.actor_repr[:TEXT_LENGTH],
137
+ "kind": action.kind,
138
+ "summary": action.summary,
139
+ "source": action.source,
140
+ "ip": _bounded(action.ip, IP_LENGTH, "ip"),
141
+ "meta": action.meta if action.meta is not None else {},
142
+ }
143
+
144
+
145
+ def _change_row(change: ChangeRecord) -> dict[str, Any]:
146
+ if change.op not in CHANGE_OPS:
147
+ raise ValueError(f"unknown change op {change.op!r}")
148
+ return {
149
+ "model_key": _bounded(change.model_key, TEXT_LENGTH, "model_key"),
150
+ "object_pk": _bounded(change.object_pk, TEXT_LENGTH, "object_pk"),
151
+ "object_repr": change.object_repr[:TEXT_LENGTH],
152
+ "op": change.op,
153
+ "changes": change.changes,
154
+ "snapshot": change.snapshot,
155
+ "field_labels": change.field_labels,
156
+ }