tortoise-orm-studio 1.0.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.
- tortoise_orm_studio/__init__.py +11 -0
- tortoise_orm_studio/adapters/__init__.py +1 -0
- tortoise_orm_studio/adapters/aiohttp_adapter.py +31 -0
- tortoise_orm_studio/adapters/asgi.py +89 -0
- tortoise_orm_studio/adapters/base.py +25 -0
- tortoise_orm_studio/adapters/django_adapter.py +84 -0
- tortoise_orm_studio/adapters/quart_adapter.py +32 -0
- tortoise_orm_studio/adapters/registry.py +39 -0
- tortoise_orm_studio/adapters/sanic_adapter.py +39 -0
- tortoise_orm_studio/auth.py +34 -0
- tortoise_orm_studio/cli.py +41 -0
- tortoise_orm_studio/core/__init__.py +1 -0
- tortoise_orm_studio/core/aerich.py +86 -0
- tortoise_orm_studio/core/ai.py +87 -0
- tortoise_orm_studio/core/audit.py +69 -0
- tortoise_orm_studio/core/config.py +58 -0
- tortoise_orm_studio/core/filters.py +94 -0
- tortoise_orm_studio/core/handler.py +249 -0
- tortoise_orm_studio/core/http.py +55 -0
- tortoise_orm_studio/core/i18n.py +18 -0
- tortoise_orm_studio/core/introspect.py +197 -0
- tortoise_orm_studio/core/manifest.py +128 -0
- tortoise_orm_studio/core/pagination.py +59 -0
- tortoise_orm_studio/core/permissions.py +46 -0
- tortoise_orm_studio/core/plugins.py +214 -0
- tortoise_orm_studio/core/ratelimit.py +32 -0
- tortoise_orm_studio/core/scoping.py +23 -0
- tortoise_orm_studio/core/serializers.py +61 -0
- tortoise_orm_studio/core/service.py +594 -0
- tortoise_orm_studio/plugins.py +8 -0
- tortoise_orm_studio/static/ALPINE_LICENSE.txt +11 -0
- tortoise_orm_studio/static/_types.d.ts +706 -0
- tortoise_orm_studio/static/a11y.js +115 -0
- tortoise_orm_studio/static/ai.js +66 -0
- tortoise_orm_studio/static/alpine.min.js +23 -0
- tortoise_orm_studio/static/app.css +514 -0
- tortoise_orm_studio/static/app.js +1443 -0
- tortoise_orm_studio/static/audit.js +171 -0
- tortoise_orm_studio/static/copy-as.js +118 -0
- tortoise_orm_studio/static/er-layout.js +227 -0
- tortoise_orm_studio/static/er.js +296 -0
- tortoise_orm_studio/static/filters.js +114 -0
- tortoise_orm_studio/static/i18n.en.js +190 -0
- tortoise_orm_studio/static/i18n.js +140 -0
- tortoise_orm_studio/static/i18n.zh-CN.js +189 -0
- tortoise_orm_studio/static/index.html +515 -0
- tortoise_orm_studio/static/inline-edit.js +107 -0
- tortoise_orm_studio/static/json-view.js +161 -0
- tortoise_orm_studio/static/migrations.js +139 -0
- tortoise_orm_studio/static/palette.js +141 -0
- tortoise_orm_studio/static/pending.js +240 -0
- tortoise_orm_studio/static/pickers.js +230 -0
- tortoise_orm_studio/static/playground.js +105 -0
- tortoise_orm_studio/static/query-history.js +84 -0
- tortoise_orm_studio/static/shortcuts.js +145 -0
- tortoise_orm_studio/static/state-hash.js +112 -0
- tortoise_orm_studio/static/tabs.js +368 -0
- tortoise_orm_studio/static/theme-init.js +33 -0
- tortoise_orm_studio/static/theme.js +106 -0
- tortoise_orm_studio/static/toasts.js +76 -0
- tortoise_orm_studio/static/views.js +70 -0
- tortoise_orm_studio/static/widgets.js +345 -0
- tortoise_orm_studio/studio.py +51 -0
- tortoise_orm_studio-1.0.0.dist-info/METADATA +177 -0
- tortoise_orm_studio-1.0.0.dist-info/RECORD +68 -0
- tortoise_orm_studio-1.0.0.dist-info/WHEEL +4 -0
- tortoise_orm_studio-1.0.0.dist-info/entry_points.txt +2 -0
- tortoise_orm_studio-1.0.0.dist-info/licenses/LICENSE +13 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Row-level scope hooks applied on EVERY data path.
|
|
2
|
+
|
|
3
|
+
A scope is a callable ``scope(model, action) -> Q | None``. Returning ``None``
|
|
4
|
+
means unrestricted; a Q object is ANDed into every query. The service applies
|
|
5
|
+
it on list/get/related/export/preview/bulk-delete/m2m/create/update/delete so
|
|
6
|
+
there is no unscoped path to bypass it (create/update/delete use `get` checks).
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Any, Callable, Optional
|
|
11
|
+
|
|
12
|
+
Scope = Callable[[Any, str], Any]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Scoping:
|
|
16
|
+
def __init__(self, scope: Optional[Scope] = None):
|
|
17
|
+
self.scope = scope
|
|
18
|
+
|
|
19
|
+
def q(self, model: Any, action: str) -> Any:
|
|
20
|
+
"""Return the Q object to AND into a query, or None for unrestricted."""
|
|
21
|
+
if self.scope is None:
|
|
22
|
+
return None
|
|
23
|
+
return self.scope(model, action)
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Python <-> JSON conversion for every Tortoise field kind."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import base64
|
|
5
|
+
import datetime as dt
|
|
6
|
+
import uuid
|
|
7
|
+
from decimal import Decimal
|
|
8
|
+
from enum import Enum
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def to_json(v: Any) -> Any:
|
|
13
|
+
if isinstance(v, Enum):
|
|
14
|
+
return v.value
|
|
15
|
+
if v is None or isinstance(v, (bool, int, float, str)):
|
|
16
|
+
return v
|
|
17
|
+
if isinstance(v, (dt.datetime, dt.date, dt.time)):
|
|
18
|
+
return v.isoformat()
|
|
19
|
+
if isinstance(v, Decimal):
|
|
20
|
+
return str(v) # keep precision, never float
|
|
21
|
+
if isinstance(v, uuid.UUID):
|
|
22
|
+
return str(v)
|
|
23
|
+
if isinstance(v, (bytes, bytearray)):
|
|
24
|
+
return {"__binary__": base64.b64encode(bytes(v)).decode("ascii")}
|
|
25
|
+
if isinstance(v, dt.timedelta):
|
|
26
|
+
return v.total_seconds()
|
|
27
|
+
if isinstance(v, (list, tuple, set)):
|
|
28
|
+
return [to_json(i) for i in v]
|
|
29
|
+
if isinstance(v, dict):
|
|
30
|
+
return {str(k): to_json(x) for k, x in v.items()}
|
|
31
|
+
return str(v)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _dt(value: str) -> dt.datetime:
|
|
35
|
+
return dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def from_json(kind: str, value: Any, enum_type: Any = None) -> Any:
|
|
39
|
+
if value is None:
|
|
40
|
+
return None
|
|
41
|
+
if kind == "int":
|
|
42
|
+
return int(value)
|
|
43
|
+
if kind == "float":
|
|
44
|
+
return float(value)
|
|
45
|
+
if kind == "decimal":
|
|
46
|
+
return Decimal(str(value))
|
|
47
|
+
if kind == "bool":
|
|
48
|
+
return value.lower() in ("1", "true", "yes") if isinstance(value, str) else bool(value)
|
|
49
|
+
if kind == "uuid":
|
|
50
|
+
return uuid.UUID(str(value))
|
|
51
|
+
if kind == "datetime":
|
|
52
|
+
return _dt(value)
|
|
53
|
+
if kind == "date":
|
|
54
|
+
return dt.date.fromisoformat(value)
|
|
55
|
+
if kind == "time":
|
|
56
|
+
return dt.time.fromisoformat(value)
|
|
57
|
+
if kind == "binary":
|
|
58
|
+
return base64.b64decode(value["__binary__"])
|
|
59
|
+
if kind == "enum":
|
|
60
|
+
return enum_type(value)
|
|
61
|
+
return value # string, text, json
|
|
@@ -0,0 +1,594 @@
|
|
|
1
|
+
"""All database work. Writes go through model.create()/save()/delete() so signals still fire."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import csv
|
|
6
|
+
import datetime as dt
|
|
7
|
+
import io
|
|
8
|
+
import json
|
|
9
|
+
import uuid
|
|
10
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
11
|
+
|
|
12
|
+
from tortoise import connections, transactions
|
|
13
|
+
|
|
14
|
+
from . import introspect as I
|
|
15
|
+
from .config import StudioConfig
|
|
16
|
+
from .filters import build_query
|
|
17
|
+
from .http import StudioError
|
|
18
|
+
from .pagination import cursor_payload, decode_cursor, encode_cursor
|
|
19
|
+
from .permissions import Permissions
|
|
20
|
+
from .scoping import Scoping
|
|
21
|
+
from .serializers import from_json, to_json
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class StudioService:
|
|
25
|
+
def __init__(self, config: StudioConfig):
|
|
26
|
+
self.config = config
|
|
27
|
+
self.permissions = Permissions(config.permissions)
|
|
28
|
+
self.scoping = Scoping(config.scope)
|
|
29
|
+
|
|
30
|
+
# ---------- lookup helpers
|
|
31
|
+
def model(self, key: str) -> type:
|
|
32
|
+
m = I.all_models().get(key)
|
|
33
|
+
if m is None or not self.config.is_allowed(key):
|
|
34
|
+
raise StudioError(404, "unknown_model", f"Unknown model: {key}")
|
|
35
|
+
return m
|
|
36
|
+
|
|
37
|
+
def _ctx(self, key: str, action: str = "read") -> Tuple[type, Dict[str, Any]]:
|
|
38
|
+
m = self.model(key)
|
|
39
|
+
if not self.permissions.allow_model(key, action):
|
|
40
|
+
raise StudioError(404, "unknown_model", f"Unknown model: {key}")
|
|
41
|
+
desc = I.describe(m, self.config)
|
|
42
|
+
# Hidden fields must disappear from schema, rows, filters, sort and
|
|
43
|
+
# export — and from cursors, which are built from the same desc.
|
|
44
|
+
desc["fields"] = self.permissions.visible_fields(key, desc["fields"])
|
|
45
|
+
visible = {f["name"] for f in desc["fields"]}
|
|
46
|
+
desc["relations"] = [r for r in desc["relations"]
|
|
47
|
+
if self.permissions.allow_model(r["model"], "read")]
|
|
48
|
+
desc["filter_paths"] = {
|
|
49
|
+
k: v for k, v in desc["filter_paths"].items()
|
|
50
|
+
if (k.split(".")[0] in visible)
|
|
51
|
+
}
|
|
52
|
+
desc["search_fields"] = [f for f in desc["search_fields"] if f in visible]
|
|
53
|
+
desc["list_display"] = [f for f in desc["list_display"] if f in visible]
|
|
54
|
+
return m, desc
|
|
55
|
+
|
|
56
|
+
def _writable(self) -> None:
|
|
57
|
+
if self.config.read_only:
|
|
58
|
+
raise StudioError(403, "read_only", "Studio is in read-only mode")
|
|
59
|
+
|
|
60
|
+
@staticmethod
|
|
61
|
+
def _db(conn: Optional[str]) -> Any:
|
|
62
|
+
"""Resolve a connection name to its client.
|
|
63
|
+
|
|
64
|
+
A batch passes the live connection yielded by ``in_transaction`` so
|
|
65
|
+
every write joins the same transaction; accept an already-resolved
|
|
66
|
+
client for that path (it is never a user-supplied string).
|
|
67
|
+
"""
|
|
68
|
+
if conn is None:
|
|
69
|
+
return None
|
|
70
|
+
if isinstance(conn, str):
|
|
71
|
+
if conn not in connections.db_config:
|
|
72
|
+
raise StudioError(400, "bad_connection", f"Unknown connection: {conn}")
|
|
73
|
+
return connections.get(conn)
|
|
74
|
+
return conn
|
|
75
|
+
|
|
76
|
+
def _qs(self, model: type, conn: Optional[str], action: str = "read") -> Any:
|
|
77
|
+
db = self._db(conn)
|
|
78
|
+
qs = model.all().using_db(db) if db else model.all()
|
|
79
|
+
q = self.scoping.q(model, action)
|
|
80
|
+
return qs.filter(q) if q is not None else qs
|
|
81
|
+
|
|
82
|
+
@staticmethod
|
|
83
|
+
def _enums(model: type, desc: Dict[str, Any]) -> Dict[str, Any]:
|
|
84
|
+
return {f["name"]: I.enum_type(model, f["name"]) for f in desc["fields"] if f["kind"] == "enum"}
|
|
85
|
+
|
|
86
|
+
def _row(self, obj: Any, desc: Dict[str, Any]) -> Dict[str, Any]:
|
|
87
|
+
"""Serialize one instance. FK/O2O return the target pk in the field slot."""
|
|
88
|
+
row: Dict[str, Any] = {}
|
|
89
|
+
for f in desc["fields"]:
|
|
90
|
+
if f["kind"] in ("fk", "o2o"):
|
|
91
|
+
row[f["name"]] = to_json(getattr(obj, f"{f['name']}_id", None))
|
|
92
|
+
else:
|
|
93
|
+
row[f["name"]] = to_json(getattr(obj, f["name"]))
|
|
94
|
+
row["_pk"] = to_json(obj.pk)
|
|
95
|
+
return row
|
|
96
|
+
|
|
97
|
+
async def _rows_with_display(self, objs: List[Any], desc: Dict[str, Any],
|
|
98
|
+
conn: Optional[str] = None) -> List[Dict[str, Any]]:
|
|
99
|
+
"""Serialize a batch, batch-fetching FK/O2O display values in one query per FK field."""
|
|
100
|
+
rows = [self._row(o, desc) for o in objs]
|
|
101
|
+
fk_fields = [f for f in desc["fields"]
|
|
102
|
+
if f["kind"] in ("fk", "o2o") and f.get("display_field")]
|
|
103
|
+
db = self._db(conn) if conn else None
|
|
104
|
+
for f in fk_fields:
|
|
105
|
+
pks = {r[f["name"]] for r in rows if r.get(f["name"]) is not None}
|
|
106
|
+
if not pks:
|
|
107
|
+
continue
|
|
108
|
+
related_model = I.all_models().get(f["related_model"])
|
|
109
|
+
if related_model is None:
|
|
110
|
+
continue
|
|
111
|
+
pk_attr = f["related_pk"]
|
|
112
|
+
disp_attr = f["display_field"]
|
|
113
|
+
qs = related_model.filter(**{f"{pk_attr}__in": list(pks)})
|
|
114
|
+
if db:
|
|
115
|
+
qs = qs.using_db(db)
|
|
116
|
+
related_objs = await qs
|
|
117
|
+
disp_map = {str(getattr(o, pk_attr)): to_json(getattr(o, disp_attr)) for o in related_objs}
|
|
118
|
+
for r in rows:
|
|
119
|
+
v = r.get(f["name"])
|
|
120
|
+
if v is not None:
|
|
121
|
+
r[f"{f['name']}_display"] = disp_map.get(str(v))
|
|
122
|
+
return rows
|
|
123
|
+
|
|
124
|
+
def _pk(self, desc: Dict[str, Any], raw: Any) -> Any:
|
|
125
|
+
kind = next(f["kind"] for f in desc["fields"] if f["pk"])
|
|
126
|
+
return from_json(kind, raw)
|
|
127
|
+
|
|
128
|
+
async def _get(self, model: type, desc: Dict[str, Any], pk: Any, conn: Optional[str]) -> Any:
|
|
129
|
+
obj = await self._qs(model, conn).get_or_none(pk=self._pk(desc, pk))
|
|
130
|
+
if obj is None:
|
|
131
|
+
raise StudioError(404, "not_found", f"{desc['name']} {pk} not found")
|
|
132
|
+
return obj
|
|
133
|
+
|
|
134
|
+
async def _audit(self, action: str, key: str, pk: Any, before: Any, after: Any, actor: Any,
|
|
135
|
+
events: Optional[List[Dict[str, Any]]] = None) -> None:
|
|
136
|
+
event = {"action": action, "model": key, "pk": to_json(pk), "before": before,
|
|
137
|
+
"after": after, "actor": actor,
|
|
138
|
+
"at": dt.datetime.now(dt.timezone.utc).isoformat()}
|
|
139
|
+
if self.config.scope is not None:
|
|
140
|
+
event["scoped"] = True
|
|
141
|
+
if events is not None:
|
|
142
|
+
# A batch buffers audit events and emits them only after commit.
|
|
143
|
+
events.append(event)
|
|
144
|
+
return
|
|
145
|
+
if self.config.audit:
|
|
146
|
+
await self.config.audit(event)
|
|
147
|
+
|
|
148
|
+
# ---------- schema / meta
|
|
149
|
+
def schema(self) -> Dict[str, Any]:
|
|
150
|
+
models = []
|
|
151
|
+
for k, m in I.all_models().items():
|
|
152
|
+
if not self.config.is_allowed(k) or not self.permissions.allow_model(k, "read"):
|
|
153
|
+
continue
|
|
154
|
+
desc = I.describe(m, self.config)
|
|
155
|
+
desc["fields"] = self.permissions.visible_fields(k, desc["fields"])
|
|
156
|
+
visible = {f["name"] for f in desc["fields"]}
|
|
157
|
+
desc["relations"] = [r for r in desc["relations"]
|
|
158
|
+
if self.permissions.allow_model(r["model"], "read")]
|
|
159
|
+
desc["filter_paths"] = {
|
|
160
|
+
n: p for n, p in desc["filter_paths"].items() if n.split(".")[0] in visible
|
|
161
|
+
}
|
|
162
|
+
desc["search_fields"] = [f for f in desc["search_fields"] if f in visible]
|
|
163
|
+
desc["list_display"] = [f for f in desc["list_display"] if f in visible]
|
|
164
|
+
models.append(desc)
|
|
165
|
+
return {
|
|
166
|
+
"read_only": self.config.read_only,
|
|
167
|
+
"features": {"ai_filter": self.config.ai_filter is not None},
|
|
168
|
+
"models": models,
|
|
169
|
+
"connections": list(connections.db_config),
|
|
170
|
+
"limits": {
|
|
171
|
+
"default_page_size": self.config.default_page_size,
|
|
172
|
+
"max_page_size": self.config.max_page_size,
|
|
173
|
+
"max_bulk": self.config.max_bulk,
|
|
174
|
+
"max_batch": self.config.max_batch,
|
|
175
|
+
"max_export_rows": self.config.max_export_rows,
|
|
176
|
+
},
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
def er(self) -> Dict[str, str]:
|
|
180
|
+
allowed = {k: m for k, m in I.all_models().items() if self.config.is_allowed(k)}
|
|
181
|
+
return {"mermaid": I.er_mermaid(allowed, self.config)}
|
|
182
|
+
|
|
183
|
+
def pydantic(self, key: str) -> Dict[str, str]:
|
|
184
|
+
return {"code": I.pydantic_code(self.model(key))}
|
|
185
|
+
|
|
186
|
+
async def migrations(self) -> Dict[str, Any]:
|
|
187
|
+
from . import aerich
|
|
188
|
+
return await aerich.inspect(self.config.migrations_dir)
|
|
189
|
+
|
|
190
|
+
# ---------- reads
|
|
191
|
+
async def list(self, key: str, page: int, limit: Optional[int], sort: Optional[str],
|
|
192
|
+
filters: List[Dict[str, Any]], search: Optional[str], conn: Optional[str],
|
|
193
|
+
after: Optional[str] = None, before: Optional[str] = None) -> Dict[str, Any]:
|
|
194
|
+
model, desc = self._ctx(key)
|
|
195
|
+
limit = min(max(int(limit or self.config.default_page_size), 1), self.config.max_page_size)
|
|
196
|
+
page = max(int(page), 1)
|
|
197
|
+
built = build_query(desc, self._enums(model, desc), filters, search, sort)
|
|
198
|
+
qs = self._qs(model, conn)
|
|
199
|
+
if built["q"] is not None:
|
|
200
|
+
qs = qs.filter(built["q"])
|
|
201
|
+
total = await qs.count()
|
|
202
|
+
order = built["order"] or [desc["pk"]]
|
|
203
|
+
qs = qs.order_by(*order)
|
|
204
|
+
|
|
205
|
+
# Keyset cursors are decoded with the configured secret. A tampered
|
|
206
|
+
# or malformed token is rejected as a 400 rather than silently paged.
|
|
207
|
+
cursor = after or before
|
|
208
|
+
if cursor:
|
|
209
|
+
payload = decode_cursor(cursor, self.config.cursor_secret)
|
|
210
|
+
if payload is None:
|
|
211
|
+
raise StudioError(400, "bad_cursor", "Invalid or tampered cursor")
|
|
212
|
+
pk = payload.get("pk")
|
|
213
|
+
if pk is not None:
|
|
214
|
+
op = "__gt" if after else "__lt"
|
|
215
|
+
qs = qs.filter(**{desc["pk"] + op: pk})
|
|
216
|
+
|
|
217
|
+
items = await qs.offset((page - 1) * limit if not cursor else 0).limit(limit)
|
|
218
|
+
rows = await self._rows_with_display(items, desc, conn)
|
|
219
|
+
out = {"items": rows, "total": total, "page": page, "limit": limit}
|
|
220
|
+
# Next/prev cursors only reference the pk (always visible) and any
|
|
221
|
+
# visible ordering field — never a hidden field's value.
|
|
222
|
+
visible = {f["name"] for f in desc["fields"]}
|
|
223
|
+
if rows:
|
|
224
|
+
desc["cursor_fields"] = [k.lstrip("-") for k in order if k.lstrip("-") in visible]
|
|
225
|
+
out["next_cursor"] = encode_cursor(cursor_payload(desc, rows[-1], visible),
|
|
226
|
+
self.config.cursor_secret)
|
|
227
|
+
out["prev_cursor"] = encode_cursor(cursor_payload(desc, rows[0], visible),
|
|
228
|
+
self.config.cursor_secret)
|
|
229
|
+
return out
|
|
230
|
+
|
|
231
|
+
async def get(self, key: str, pk: str, conn: Optional[str]) -> Dict[str, Any]:
|
|
232
|
+
model, desc = self._ctx(key)
|
|
233
|
+
obj = await self._get(model, desc, pk, conn)
|
|
234
|
+
rows = await self._rows_with_display([obj], desc, conn)
|
|
235
|
+
return rows[0]
|
|
236
|
+
|
|
237
|
+
async def related(self, key: str, pk: str, rel: str, page: int, limit: Optional[int],
|
|
238
|
+
conn: Optional[str]) -> Dict[str, Any]:
|
|
239
|
+
model, desc = self._ctx(key)
|
|
240
|
+
r = next((x for x in desc["relations"] if x["name"] == rel), None)
|
|
241
|
+
if r is None:
|
|
242
|
+
raise StudioError(404, "unknown_relation", f"Unknown relation: {rel}")
|
|
243
|
+
obj = await self._get(model, desc, pk, conn)
|
|
244
|
+
rmodel, rdesc = self._ctx(r["model"])
|
|
245
|
+
limit = min(max(int(limit or self.config.default_page_size), 1), self.config.max_page_size)
|
|
246
|
+
page = max(int(page), 1)
|
|
247
|
+
if r["type"] in ("fk", "o2o"):
|
|
248
|
+
fk = getattr(obj, r["column"])
|
|
249
|
+
# A `to_field` FK stores the target field's value, not its pk.
|
|
250
|
+
target = r.get("related_pk") or rdesc["pk"]
|
|
251
|
+
one = None if fk is None else await rmodel.get_or_none(**{target: fk})
|
|
252
|
+
items, total = ([one] if one else []), (1 if one else 0)
|
|
253
|
+
else:
|
|
254
|
+
qs = getattr(obj, rel).all() if r["type"] in ("m2m", "backward_fk") else rmodel.filter(**{r["via"]: obj.pk})
|
|
255
|
+
rq = self.scoping.q(rmodel, "read")
|
|
256
|
+
if rq is not None:
|
|
257
|
+
qs = qs.filter(rq)
|
|
258
|
+
total = await qs.count()
|
|
259
|
+
items = await qs.order_by(rdesc["pk"]).offset((page - 1) * limit).limit(limit)
|
|
260
|
+
rows = await self._rows_with_display(items, rdesc, conn)
|
|
261
|
+
return {"model": r["model"], "items": rows, "total": total, "page": page, "limit": limit}
|
|
262
|
+
|
|
263
|
+
async def export(self, key: str, fmt: str, sort: Optional[str], filters: List[Dict[str, Any]],
|
|
264
|
+
search: Optional[str], conn: Optional[str]) -> Tuple[str, bytes]:
|
|
265
|
+
model, desc = self._ctx(key)
|
|
266
|
+
built = build_query(desc, self._enums(model, desc), filters, search, sort)
|
|
267
|
+
qs = self._qs(model, conn)
|
|
268
|
+
if built["q"] is not None:
|
|
269
|
+
qs = qs.filter(built["q"])
|
|
270
|
+
objs = await qs.order_by(*(built["order"] or [desc["pk"]])).limit(self.config.max_export_rows)
|
|
271
|
+
rows = [self._row(o, desc) for o in objs] # exports use pk, not display
|
|
272
|
+
if fmt == "json":
|
|
273
|
+
return "application/json", json.dumps(rows).encode()
|
|
274
|
+
cols = [f["name"] for f in desc["fields"]]
|
|
275
|
+
buf = io.StringIO()
|
|
276
|
+
w = csv.writer(buf)
|
|
277
|
+
w.writerow(cols)
|
|
278
|
+
for row in rows:
|
|
279
|
+
cells = ["" if row[c] is None else (json.dumps(row[c]) if isinstance(row[c], (dict, list)) else str(row[c]))
|
|
280
|
+
for c in cols]
|
|
281
|
+
w.writerow(["'" + c if c[:1] in ("=", "+", "-", "@") else c for c in cells])
|
|
282
|
+
return "text/csv; charset=utf-8", buf.getvalue().encode()
|
|
283
|
+
|
|
284
|
+
def preview(self, key: str, filters: List[Dict[str, Any]], search: Optional[str],
|
|
285
|
+
sort: Optional[str], limit: int) -> Dict[str, Any]:
|
|
286
|
+
model, desc = self._ctx(key)
|
|
287
|
+
built = build_query(desc, self._enums(model, desc), filters, search, sort)
|
|
288
|
+
qs = self._qs(model, None, "read")
|
|
289
|
+
if built["q"] is not None:
|
|
290
|
+
qs = qs.filter(built["q"])
|
|
291
|
+
if built["order"]:
|
|
292
|
+
qs = qs.order_by(*built["order"])
|
|
293
|
+
qs = qs.limit(min(int(limit), self.config.max_page_size))
|
|
294
|
+
code = f"await {desc['name']}.filter({built['code']})" if built["code"] else f"await {desc['name']}.all()"
|
|
295
|
+
if built["order"]:
|
|
296
|
+
code += ".order_by(" + ", ".join(repr(o) for o in built["order"]) + ")"
|
|
297
|
+
code += f".limit({int(limit)})"
|
|
298
|
+
try:
|
|
299
|
+
sql = qs.sql()
|
|
300
|
+
except Exception:
|
|
301
|
+
sql = None
|
|
302
|
+
return {"code": code, "sql": sql}
|
|
303
|
+
|
|
304
|
+
# ---------- audit log
|
|
305
|
+
async def audit_log(self, page: int, limit: Optional[int],
|
|
306
|
+
model: Optional[str], action: Optional[str], actor: Optional[str],
|
|
307
|
+
since: Optional[str], until: Optional[str],
|
|
308
|
+
conn: Optional[str]) -> Dict[str, Any]:
|
|
309
|
+
"""Read the audit log. Returns ``available: false`` if the model isn't registered."""
|
|
310
|
+
from .audit import StudioAudit
|
|
311
|
+
from .serializers import from_json as _fj
|
|
312
|
+
|
|
313
|
+
limit = min(max(int(limit or self.config.default_page_size), 1), self.config.max_page_size)
|
|
314
|
+
page = max(int(page), 1)
|
|
315
|
+
|
|
316
|
+
try:
|
|
317
|
+
qs = StudioAudit.all()
|
|
318
|
+
if conn:
|
|
319
|
+
qs = qs.using_db(self._db(conn))
|
|
320
|
+
if model:
|
|
321
|
+
qs = qs.filter(model=model)
|
|
322
|
+
if action:
|
|
323
|
+
qs = qs.filter(action=action)
|
|
324
|
+
if actor:
|
|
325
|
+
qs = qs.filter(actor=actor)
|
|
326
|
+
if since:
|
|
327
|
+
qs = qs.filter(at__gte=_fj("datetime", since))
|
|
328
|
+
if until:
|
|
329
|
+
qs = qs.filter(at__lte=_fj("datetime", until))
|
|
330
|
+
total = await qs.count()
|
|
331
|
+
objs = await qs.order_by("-at").offset((page - 1) * limit).limit(limit)
|
|
332
|
+
except Exception:
|
|
333
|
+
# Model not registered, table doesn't exist, or DB down
|
|
334
|
+
return {"available": False, "items": [], "total": 0, "page": page, "limit": limit}
|
|
335
|
+
|
|
336
|
+
return {
|
|
337
|
+
"available": True,
|
|
338
|
+
"items": [self._audit_row(o) for o in objs],
|
|
339
|
+
"total": total,
|
|
340
|
+
"page": page,
|
|
341
|
+
"limit": limit,
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
def _audit_row(self, o: Any) -> Dict[str, Any]:
|
|
345
|
+
return {
|
|
346
|
+
"id": o.id,
|
|
347
|
+
"action": o.action,
|
|
348
|
+
"model": o.model,
|
|
349
|
+
"pk": o.object_pk, # user-facing "pk"; ORM field renamed to avoid .pk alias
|
|
350
|
+
"before": o.before,
|
|
351
|
+
"after": o.after,
|
|
352
|
+
"actor": o.actor,
|
|
353
|
+
"at": to_json(o.at),
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
# ---------- writes
|
|
357
|
+
def _display_suffixes(self, desc: Dict[str, Any]) -> set:
|
|
358
|
+
return {f"{f['name']}_display" for f in desc["fields"] if f["kind"] in ("fk", "o2o")}
|
|
359
|
+
|
|
360
|
+
def _coerce(self, model: type, desc: Dict[str, Any], data: Dict[str, Any], creating: bool) -> Dict[str, Any]:
|
|
361
|
+
allowed = self.permissions.writable_fields(
|
|
362
|
+
I.model_key(model), desc["fields"])
|
|
363
|
+
by_name = {f["name"]: f for f in desc["fields"]}
|
|
364
|
+
computed = self._display_suffixes(desc)
|
|
365
|
+
out: Dict[str, Any] = {}
|
|
366
|
+
for k, v in data.items():
|
|
367
|
+
if k in computed:
|
|
368
|
+
continue # server-side computed, never stored
|
|
369
|
+
f = by_name.get(k)
|
|
370
|
+
if f is None:
|
|
371
|
+
raise StudioError(400, "unknown_field", f"Unknown field: {k}")
|
|
372
|
+
if k not in allowed:
|
|
373
|
+
raise StudioError(403, "field_forbidden", f"Cannot write field: {k}")
|
|
374
|
+
if f["readonly"] or (f["pk"] and not creating):
|
|
375
|
+
raise StudioError(400, "readonly_field", f"Field is read-only: {k}")
|
|
376
|
+
if f["kind"] in ("fk", "o2o"):
|
|
377
|
+
if v is None and not f["null"]:
|
|
378
|
+
raise StudioError(400, "bad_request", f"{k} is required")
|
|
379
|
+
out[f"{k}_id"] = None if v is None else from_json(f["pk_kind"], v)
|
|
380
|
+
else:
|
|
381
|
+
out[k] = from_json(f["kind"], v, I.enum_type(model, k) if f["kind"] == "enum" else None)
|
|
382
|
+
return out
|
|
383
|
+
|
|
384
|
+
async def _validate_fk(self, desc: Dict[str, Any], coerced: Dict[str, Any],
|
|
385
|
+
conn: Optional[str] = None) -> None:
|
|
386
|
+
for f in desc["fields"]:
|
|
387
|
+
if f["kind"] not in ("fk", "o2o"):
|
|
388
|
+
continue
|
|
389
|
+
key = f"{f['name']}_id"
|
|
390
|
+
if key not in coerced or coerced[key] is None:
|
|
391
|
+
continue
|
|
392
|
+
try:
|
|
393
|
+
related_model = self.model(f["related_model"])
|
|
394
|
+
except StudioError:
|
|
395
|
+
continue
|
|
396
|
+
qs = related_model.filter(**{f["related_pk"]: coerced[key]})
|
|
397
|
+
db = self._db(conn)
|
|
398
|
+
if db:
|
|
399
|
+
qs = qs.using_db(db)
|
|
400
|
+
target = await qs.first()
|
|
401
|
+
if target is None:
|
|
402
|
+
raise StudioError(404, "not_found", f"{f['related_model']} {coerced[key]} not found")
|
|
403
|
+
|
|
404
|
+
async def create(self, key: str, data: Dict[str, Any], conn: Optional[str], actor: Any,
|
|
405
|
+
events: Optional[List[Dict[str, Any]]] = None) -> Dict[str, Any]:
|
|
406
|
+
self._writable()
|
|
407
|
+
model, desc = self._ctx(key)
|
|
408
|
+
coerced = self._coerce(model, desc, data, True)
|
|
409
|
+
await self._validate_fk(desc, coerced, conn)
|
|
410
|
+
obj = await model.create(using_db=self._db(conn), **coerced)
|
|
411
|
+
rows = await self._rows_with_display([obj], desc, conn)
|
|
412
|
+
row = rows[0]
|
|
413
|
+
await self._audit("create", key, obj.pk, None, row, actor, events)
|
|
414
|
+
return row
|
|
415
|
+
|
|
416
|
+
async def update(self, key: str, pk: str, data: Dict[str, Any], conn: Optional[str], actor: Any,
|
|
417
|
+
expected: Optional[Dict[str, Any]] = None,
|
|
418
|
+
events: Optional[List[Dict[str, Any]]] = None) -> Dict[str, Any]:
|
|
419
|
+
self._writable()
|
|
420
|
+
model, desc = self._ctx(key)
|
|
421
|
+
obj = await self._get(model, desc, pk, conn)
|
|
422
|
+
before = (await self._rows_with_display([obj], desc, conn))[0]
|
|
423
|
+
if expected is not None:
|
|
424
|
+
for field, value in expected.items():
|
|
425
|
+
if field not in before:
|
|
426
|
+
raise StudioError(400, "bad_request", f"Unknown expected field: {field}")
|
|
427
|
+
if before[field] != value:
|
|
428
|
+
raise StudioError(409, "conflict", f"Row changed: {field}")
|
|
429
|
+
coerced = self._coerce(model, desc, data, False)
|
|
430
|
+
await self._validate_fk(desc, coerced, conn)
|
|
431
|
+
obj.update_from_dict(coerced)
|
|
432
|
+
await obj.save(using_db=self._db(conn))
|
|
433
|
+
after = (await self._rows_with_display([obj], desc, conn))[0]
|
|
434
|
+
await self._audit("update", key, obj.pk, before, after, actor, events)
|
|
435
|
+
return after
|
|
436
|
+
|
|
437
|
+
async def delete(self, key: str, pk: str, conn: Optional[str], actor: Any,
|
|
438
|
+
events: Optional[List[Dict[str, Any]]] = None) -> None:
|
|
439
|
+
self._writable()
|
|
440
|
+
model, desc = self._ctx(key)
|
|
441
|
+
obj = await self._get(model, desc, pk, conn)
|
|
442
|
+
before = self._row(obj, desc)
|
|
443
|
+
await obj.delete(using_db=self._db(conn))
|
|
444
|
+
await self._audit("delete", key, pk, before, None, actor, events)
|
|
445
|
+
|
|
446
|
+
async def bulk_delete(self, key: str, ids: List[Any], conn: Optional[str], actor: Any) -> int:
|
|
447
|
+
self._writable()
|
|
448
|
+
if len(ids) > self.config.max_bulk:
|
|
449
|
+
raise StudioError(400, "too_many", f"At most {self.config.max_bulk} rows per request")
|
|
450
|
+
for pk in ids:
|
|
451
|
+
await self.delete(key, str(pk), conn, actor)
|
|
452
|
+
return len(ids)
|
|
453
|
+
|
|
454
|
+
async def m2m(self, key: str, pk: str, rel: str, ids: List[Any], add: bool,
|
|
455
|
+
conn: Optional[str], actor: Any,
|
|
456
|
+
events: Optional[List[Dict[str, Any]]] = None) -> Dict[str, Any]:
|
|
457
|
+
self._writable()
|
|
458
|
+
model, desc = self._ctx(key)
|
|
459
|
+
r = next((x for x in desc["relations"] if x["name"] == rel and x["type"] == "m2m"), None)
|
|
460
|
+
if r is None:
|
|
461
|
+
raise StudioError(400, "not_m2m", f"{rel} is not a many-to-many relation")
|
|
462
|
+
obj = await self._get(model, desc, pk, conn)
|
|
463
|
+
rmodel, rdesc = self._ctx(r["model"])
|
|
464
|
+
targets = []
|
|
465
|
+
for i in ids:
|
|
466
|
+
t = await self._qs(rmodel, conn, "read").get_or_none(pk=self._pk(rdesc, i))
|
|
467
|
+
if t is None:
|
|
468
|
+
raise StudioError(404, "not_found", f"{rdesc['name']} {i} not found")
|
|
469
|
+
targets.append(t)
|
|
470
|
+
manager = getattr(obj, rel)
|
|
471
|
+
db = self._db(conn)
|
|
472
|
+
await (manager.add(*targets, using_db=db) if add else manager.remove(*targets, using_db=db))
|
|
473
|
+
await self._audit("m2m_add" if add else "m2m_remove", key, obj.pk, None,
|
|
474
|
+
{"relation": rel, "ids": ids}, actor, events)
|
|
475
|
+
return {"ok": True, "count": len(targets)}
|
|
476
|
+
|
|
477
|
+
# ---------- v0.5.0: atomic batch
|
|
478
|
+
_BATCH_OPS = {"create", "update", "delete", "m2m_add", "m2m_remove"}
|
|
479
|
+
|
|
480
|
+
@staticmethod
|
|
481
|
+
def _conn_name(conn: Optional[str]) -> str:
|
|
482
|
+
"""Treat the default connection and an unspecified one as the same."""
|
|
483
|
+
return conn or "default"
|
|
484
|
+
|
|
485
|
+
def _check_batch(self, operations: Any, conn: Optional[str]) -> None:
|
|
486
|
+
self._writable()
|
|
487
|
+
if not isinstance(operations, list):
|
|
488
|
+
raise StudioError(400, "bad_request", "operations must be a JSON list")
|
|
489
|
+
if len(operations) > self.config.max_batch:
|
|
490
|
+
raise StudioError(400, "too_many",
|
|
491
|
+
f"At most {self.config.max_batch} operations per batch")
|
|
492
|
+
batch_conn = self._conn_name(conn)
|
|
493
|
+
# Validate connection names and shapes before opening a transaction, so
|
|
494
|
+
# a malformed body fails fast and never touches the database.
|
|
495
|
+
self._db(conn)
|
|
496
|
+
for i, op in enumerate(operations):
|
|
497
|
+
if not isinstance(op, dict):
|
|
498
|
+
raise StudioError(400, "bad_request", "each operation must be an object",
|
|
499
|
+
detail={"index": i})
|
|
500
|
+
if self._conn_name(op.get("connection")) != batch_conn:
|
|
501
|
+
raise StudioError(400, "bad_connection",
|
|
502
|
+
"all operations in a batch must use one connection",
|
|
503
|
+
detail={"index": i})
|
|
504
|
+
name = op.get("op")
|
|
505
|
+
if name not in self._BATCH_OPS:
|
|
506
|
+
raise StudioError(400, "bad_request", f"Unknown batch operation: {name}",
|
|
507
|
+
detail={"index": i})
|
|
508
|
+
if not isinstance(op.get("model"), str):
|
|
509
|
+
raise StudioError(400, "bad_request", "operation.model is required",
|
|
510
|
+
detail={"index": i})
|
|
511
|
+
required = {
|
|
512
|
+
"create": ("data",),
|
|
513
|
+
"update": ("pk", "data"),
|
|
514
|
+
"delete": ("pk",),
|
|
515
|
+
"m2m_add": ("pk", "rel", "ids"),
|
|
516
|
+
"m2m_remove": ("pk", "rel", "ids"),
|
|
517
|
+
}[name]
|
|
518
|
+
for field in required:
|
|
519
|
+
if field not in op:
|
|
520
|
+
raise StudioError(400, "bad_request", f"operation.{field} is required",
|
|
521
|
+
detail={"index": i})
|
|
522
|
+
|
|
523
|
+
async def batch(self, operations: Any, conn: Optional[str], actor: Any,
|
|
524
|
+
batch_id: Optional[str] = None) -> Dict[str, Any]:
|
|
525
|
+
"""Run an ordered list of writes in one transaction, all-or-nothing.
|
|
526
|
+
|
|
527
|
+
Atomicity requires the database/driver to support transactions; SQLite,
|
|
528
|
+
Postgres and MySQL all do when the driver is configured normally. Every
|
|
529
|
+
operation reuses the single-row methods (so permissions, scope, typed
|
|
530
|
+
coercion and signals are identical); audit events are buffered and
|
|
531
|
+
emitted only after a successful commit, sharing one ``batch_id``.
|
|
532
|
+
"""
|
|
533
|
+
self._check_batch(operations, conn)
|
|
534
|
+
batch_id = batch_id or uuid.uuid4().hex
|
|
535
|
+
events: List[Dict[str, Any]] = []
|
|
536
|
+
results: List[Dict[str, Any]] = []
|
|
537
|
+
|
|
538
|
+
async with transactions.in_transaction(conn) as tx:
|
|
539
|
+
for i, op in enumerate(operations):
|
|
540
|
+
name = op["op"]
|
|
541
|
+
try:
|
|
542
|
+
if name == "create":
|
|
543
|
+
result = await self.create(op["model"], op["data"], tx, actor, events)
|
|
544
|
+
elif name == "update":
|
|
545
|
+
result = await self.update(op["model"], str(op["pk"]), op["data"], tx,
|
|
546
|
+
actor, op.get("expected"), events)
|
|
547
|
+
elif name == "delete":
|
|
548
|
+
await self.delete(op["model"], str(op["pk"]), tx, actor, events)
|
|
549
|
+
result = {"deleted": 1}
|
|
550
|
+
else: # m2m_add / m2m_remove
|
|
551
|
+
result = await self.m2m(op["model"], str(op["pk"]), op["rel"],
|
|
552
|
+
op["ids"], name == "m2m_add", tx, actor, events)
|
|
553
|
+
except StudioError as e:
|
|
554
|
+
raise StudioError(e.status, e.code, f"Operation {i}: {e.message}",
|
|
555
|
+
headers=e.headers,
|
|
556
|
+
detail={**e.detail, "index": i, "operation": i}) from e
|
|
557
|
+
results.append({"index": i, "op": name, "result": result})
|
|
558
|
+
|
|
559
|
+
# Only reached after the transaction committed: a rolled-back batch
|
|
560
|
+
# leaves no audit trail at all.
|
|
561
|
+
for event in events:
|
|
562
|
+
event["batch_id"] = batch_id
|
|
563
|
+
if self.config.audit:
|
|
564
|
+
await self.config.audit(event)
|
|
565
|
+
return {"batch_id": batch_id, "count": len(operations), "results": results}
|
|
566
|
+
|
|
567
|
+
# ---------- v0.5.0: optional AI filter hook
|
|
568
|
+
async def ai_filter(self, key: str, text: Any) -> Dict[str, Any]:
|
|
569
|
+
"""Ask the host-supplied hook for filters, then whitelist the answer.
|
|
570
|
+
|
|
571
|
+
The returned filters are for the UI to show as reviewable chips; they
|
|
572
|
+
are never applied here. A missing hook, timeout, hook error or bad
|
|
573
|
+
output all map to clear errors with no row data in the response.
|
|
574
|
+
"""
|
|
575
|
+
if self.config.ai_filter is None:
|
|
576
|
+
raise StudioError(404, "not_available", "AI filter hook is not configured")
|
|
577
|
+
model, desc = self._ctx(key) # permission/exclude already applied
|
|
578
|
+
from .ai import build_prompt, parse_response
|
|
579
|
+
prompt = build_prompt(desc, str(text or ""), "filter", self.config.ai_max_prompt)
|
|
580
|
+
try:
|
|
581
|
+
raw = await asyncio.wait_for(
|
|
582
|
+
self.config.ai_filter(prompt, "filter"), timeout=self.config.ai_timeout)
|
|
583
|
+
except asyncio.TimeoutError as e:
|
|
584
|
+
raise StudioError(504, "ai_timeout", "AI filter timed out") from e
|
|
585
|
+
except Exception as e:
|
|
586
|
+
raise StudioError(502, "ai_error", f"AI filter failed: {e}") from e
|
|
587
|
+
filters = parse_response(raw, desc, self._enums(model, desc))
|
|
588
|
+
return {"filters": filters, "text": str(text or "")}
|
|
589
|
+
|
|
590
|
+
def ai_prompt(self, key: str, text: Any) -> Dict[str, str]:
|
|
591
|
+
"""Return the exact prompt (no call) - useful for hosts/tests."""
|
|
592
|
+
model, desc = self._ctx(key)
|
|
593
|
+
from .ai import build_prompt
|
|
594
|
+
return {"prompt": build_prompt(desc, str(text or ""), "filter", self.config.ai_max_prompt)}
|