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.
Files changed (68) hide show
  1. tortoise_orm_studio/__init__.py +11 -0
  2. tortoise_orm_studio/adapters/__init__.py +1 -0
  3. tortoise_orm_studio/adapters/aiohttp_adapter.py +31 -0
  4. tortoise_orm_studio/adapters/asgi.py +89 -0
  5. tortoise_orm_studio/adapters/base.py +25 -0
  6. tortoise_orm_studio/adapters/django_adapter.py +84 -0
  7. tortoise_orm_studio/adapters/quart_adapter.py +32 -0
  8. tortoise_orm_studio/adapters/registry.py +39 -0
  9. tortoise_orm_studio/adapters/sanic_adapter.py +39 -0
  10. tortoise_orm_studio/auth.py +34 -0
  11. tortoise_orm_studio/cli.py +41 -0
  12. tortoise_orm_studio/core/__init__.py +1 -0
  13. tortoise_orm_studio/core/aerich.py +86 -0
  14. tortoise_orm_studio/core/ai.py +87 -0
  15. tortoise_orm_studio/core/audit.py +69 -0
  16. tortoise_orm_studio/core/config.py +58 -0
  17. tortoise_orm_studio/core/filters.py +94 -0
  18. tortoise_orm_studio/core/handler.py +249 -0
  19. tortoise_orm_studio/core/http.py +55 -0
  20. tortoise_orm_studio/core/i18n.py +18 -0
  21. tortoise_orm_studio/core/introspect.py +197 -0
  22. tortoise_orm_studio/core/manifest.py +128 -0
  23. tortoise_orm_studio/core/pagination.py +59 -0
  24. tortoise_orm_studio/core/permissions.py +46 -0
  25. tortoise_orm_studio/core/plugins.py +214 -0
  26. tortoise_orm_studio/core/ratelimit.py +32 -0
  27. tortoise_orm_studio/core/scoping.py +23 -0
  28. tortoise_orm_studio/core/serializers.py +61 -0
  29. tortoise_orm_studio/core/service.py +594 -0
  30. tortoise_orm_studio/plugins.py +8 -0
  31. tortoise_orm_studio/static/ALPINE_LICENSE.txt +11 -0
  32. tortoise_orm_studio/static/_types.d.ts +706 -0
  33. tortoise_orm_studio/static/a11y.js +115 -0
  34. tortoise_orm_studio/static/ai.js +66 -0
  35. tortoise_orm_studio/static/alpine.min.js +23 -0
  36. tortoise_orm_studio/static/app.css +514 -0
  37. tortoise_orm_studio/static/app.js +1443 -0
  38. tortoise_orm_studio/static/audit.js +171 -0
  39. tortoise_orm_studio/static/copy-as.js +118 -0
  40. tortoise_orm_studio/static/er-layout.js +227 -0
  41. tortoise_orm_studio/static/er.js +296 -0
  42. tortoise_orm_studio/static/filters.js +114 -0
  43. tortoise_orm_studio/static/i18n.en.js +190 -0
  44. tortoise_orm_studio/static/i18n.js +140 -0
  45. tortoise_orm_studio/static/i18n.zh-CN.js +189 -0
  46. tortoise_orm_studio/static/index.html +515 -0
  47. tortoise_orm_studio/static/inline-edit.js +107 -0
  48. tortoise_orm_studio/static/json-view.js +161 -0
  49. tortoise_orm_studio/static/migrations.js +139 -0
  50. tortoise_orm_studio/static/palette.js +141 -0
  51. tortoise_orm_studio/static/pending.js +240 -0
  52. tortoise_orm_studio/static/pickers.js +230 -0
  53. tortoise_orm_studio/static/playground.js +105 -0
  54. tortoise_orm_studio/static/query-history.js +84 -0
  55. tortoise_orm_studio/static/shortcuts.js +145 -0
  56. tortoise_orm_studio/static/state-hash.js +112 -0
  57. tortoise_orm_studio/static/tabs.js +368 -0
  58. tortoise_orm_studio/static/theme-init.js +33 -0
  59. tortoise_orm_studio/static/theme.js +106 -0
  60. tortoise_orm_studio/static/toasts.js +76 -0
  61. tortoise_orm_studio/static/views.js +70 -0
  62. tortoise_orm_studio/static/widgets.js +345 -0
  63. tortoise_orm_studio/studio.py +51 -0
  64. tortoise_orm_studio-1.0.0.dist-info/METADATA +177 -0
  65. tortoise_orm_studio-1.0.0.dist-info/RECORD +68 -0
  66. tortoise_orm_studio-1.0.0.dist-info/WHEEL +4 -0
  67. tortoise_orm_studio-1.0.0.dist-info/entry_points.txt +2 -0
  68. tortoise_orm_studio-1.0.0.dist-info/licenses/LICENSE +13 -0
@@ -0,0 +1,11 @@
1
+ from .auth import basic_auth, bearer_token
2
+ from .core.http import StudioError, StudioRequest, StudioResponse
3
+ from .core.plugins import PluginAction, PluginRoute, StudioPlugin
4
+ from .studio import Studio
5
+
6
+ __all__ = [
7
+ "Studio", "StudioRequest", "StudioResponse", "StudioError",
8
+ "StudioPlugin", "PluginRoute", "PluginAction",
9
+ "basic_auth", "bearer_token",
10
+ ]
11
+ __version__ = "1.0.0"
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,31 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from aiohttp import web
6
+
7
+ from ..core.http import StudioRequest, StudioResponse
8
+ from .base import BaseAdapter
9
+
10
+
11
+ class AiohttpAdapter(BaseAdapter):
12
+ async def to_request(self, request: web.Request) -> StudioRequest:
13
+ return StudioRequest(
14
+ method=request.method, path="/" + request.match_info.get("tail", ""),
15
+ query={k: request.query.getall(k) for k in set(request.query.keys())},
16
+ headers={k.lower(): v for k, v in request.headers.items()},
17
+ body=await request.read(), client=request.remote, raw=request)
18
+
19
+ def to_response(self, res: StudioResponse) -> web.Response:
20
+ return web.Response(status=res.status, headers=res.headers, body=res.body)
21
+
22
+ def install(self, app: web.Application) -> None:
23
+ async def slash(request: web.Request) -> web.Response:
24
+ raise web.HTTPFound(self.prefix + "/")
25
+
26
+ app.router.add_route("GET", self.prefix, slash)
27
+ app.router.add_route("*", self.prefix + "/{tail:.*}", self.__call__)
28
+
29
+
30
+ def install(app: Any, studio: Any, prefix: str = "/studio", **_: Any) -> None:
31
+ AiohttpAdapter(studio, prefix).install(app)
@@ -0,0 +1,89 @@
1
+ """Pure ASGI app: works unchanged under FastAPI, Starlette, Litestar, Quart (via mount), uvicorn, etc."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any, Dict, List, Optional
5
+ from urllib.parse import parse_qs
6
+
7
+ from tortoise import Tortoise, connections
8
+
9
+ from ..core.http import StudioRequest
10
+
11
+
12
+ class StudioASGI:
13
+ def __init__(self, studio: Any, tortoise_config: Optional[dict] = None):
14
+ self.studio, self.tortoise_config = studio, tortoise_config
15
+
16
+ async def __call__(self, scope: Dict[str, Any], receive: Any, send: Any) -> None:
17
+ if scope["type"] == "lifespan":
18
+ return await self._lifespan(receive, send)
19
+ if scope["type"] != "http":
20
+ return
21
+ body, more = b"", True
22
+ while more:
23
+ msg = await receive()
24
+ body += msg.get("body", b"")
25
+ more = msg.get("more_body", False)
26
+ path, root = scope.get("path", "/"), scope.get("root_path", "")
27
+ if root and path.startswith(root): # newer Starlette keeps the full path
28
+ path = path[len(root):]
29
+ client = scope.get("client")
30
+ req = StudioRequest(
31
+ method=scope["method"], path=path or "/",
32
+ query=parse_qs(scope.get("query_string", b"").decode("latin-1")),
33
+ headers={k.decode("latin-1").lower(): v.decode("latin-1") for k, v in scope.get("headers", [])},
34
+ body=body, client=client[0] if client else None, raw=scope)
35
+ res = await self.studio.handle(req)
36
+ headers: List[Any] = [(k.encode("latin-1"), v.encode("latin-1")) for k, v in res.headers.items()]
37
+ headers.append((b"content-length", str(len(res.body)).encode()))
38
+ await send({"type": "http.response.start", "status": res.status, "headers": headers})
39
+ await send({"type": "http.response.body", "body": res.body})
40
+
41
+ async def _lifespan(self, receive: Any, send: Any) -> None:
42
+ while True:
43
+ msg = await receive()
44
+ if msg["type"] == "lifespan.startup":
45
+ try:
46
+ if self.tortoise_config:
47
+ try: # Tortoise 1.x keeps state per task; the lifespan task != the request tasks
48
+ await Tortoise.init(config=self.tortoise_config, _enable_global_fallback=True)
49
+ except TypeError: # older Tortoise has no such option (and no such problem)
50
+ await Tortoise.init(config=self.tortoise_config)
51
+ await send({"type": "lifespan.startup.complete"})
52
+ except Exception as exc:
53
+ await send({"type": "lifespan.startup.failed", "message": str(exc)})
54
+ return
55
+ elif msg["type"] == "lifespan.shutdown":
56
+ if self.tortoise_config:
57
+ await connections.close_all()
58
+ await send({"type": "lifespan.shutdown.complete"})
59
+ return
60
+
61
+
62
+ def install_starlette(app: Any, studio: Any, prefix: str = "/studio", **_: Any) -> None:
63
+ """FastAPI and Starlette."""
64
+ app.mount("/" + prefix.strip("/"), studio.asgi(), name="tortoise_orm_studio")
65
+
66
+
67
+ def install_litestar(app: Any, studio: Any, prefix: str = "/studio", **_: Any) -> None:
68
+ from litestar import asgi
69
+ asgi_app = studio.asgi()
70
+
71
+ # `copy_scope=True` is supported by Litestar >= 2.11; older releases can
72
+ # still mount Studio, they just share the scope dict with us (we replace
73
+ # it rather than mutating it, so either way is safe).
74
+ try:
75
+ mount = asgi("/" + prefix.strip("/"), is_mount=True, copy_scope=True)
76
+ except TypeError: # pragma: no cover - old Litestar
77
+ mount = asgi("/" + prefix.strip("/"), is_mount=True)
78
+
79
+ @mount
80
+ async def tortoise_orm_studio(scope: Any, receive: Any, send: Any) -> None:
81
+ # Litestar's mount handler appends a "/" to nested paths (e.g.
82
+ # /studio/api/schema reaches us as /api/schema/). Studio routes are
83
+ # exact, so strip the synthetic slash at the adapter boundary.
84
+ path = scope.get("path", "")
85
+ if path and path != "/" and path.endswith("/"):
86
+ scope = dict(scope, path=path.rstrip("/"))
87
+ await asgi_app(scope, receive, send)
88
+
89
+ app.register(tortoise_orm_studio)
@@ -0,0 +1,25 @@
1
+ """Subclass BaseAdapter to support ANY framework. Implement three small methods."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any
5
+
6
+ from ..core.http import StudioRequest, StudioResponse
7
+
8
+
9
+ class BaseAdapter:
10
+ methods = ("GET", "POST", "PATCH", "DELETE")
11
+
12
+ def __init__(self, studio: Any, prefix: str = "/studio"):
13
+ self.studio, self.prefix = studio, "/" + prefix.strip("/")
14
+
15
+ async def to_request(self, native: Any) -> StudioRequest: # 1. framework request -> StudioRequest
16
+ raise NotImplementedError
17
+
18
+ def to_response(self, res: StudioResponse) -> Any: # 2. StudioResponse -> framework response
19
+ raise NotImplementedError
20
+
21
+ def install(self, app: Any) -> None: # 3. register routes on the framework
22
+ raise NotImplementedError
23
+
24
+ async def __call__(self, native: Any) -> Any: # every route handler delegates here
25
+ return self.to_response(await self.studio.handle(await self.to_request(native)))
@@ -0,0 +1,84 @@
1
+ """
2
+ Django integration for tortoise-orm-studio.
3
+
4
+ Requires Django 4.1+ running under ASGI (async views). WSGI is not supported
5
+ because the Studio core is async.
6
+
7
+ Django has no ``app.mount()`` — add URL patterns to your project's ``urls.py``::
8
+
9
+ from tortoise_orm_studio import Studio
10
+ from tortoise_orm_studio.adapters.django_adapter import urls
11
+
12
+ studio = Studio(read_only=False, auth=basic_auth("admin", "secret"))
13
+ urlpatterns = [
14
+ *urls(studio, prefix="studio"),
15
+ # ...your other patterns
16
+ ]
17
+
18
+ Run under ``daphne``, ``uvicorn``, or Django's ASGI development server.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ from typing import Any
23
+ from urllib.parse import parse_qs
24
+
25
+ from ..core.http import StudioRequest
26
+
27
+
28
+ def make_view(studio: Any):
29
+ """Return an async Django view that delegates to Studio.
30
+
31
+ The view reads only what the core needs: method, path, query, headers,
32
+ body, remote address. It writes back exactly what StudioResponse carries.
33
+ """
34
+
35
+ async def studio_view(request, tail: str = ""):
36
+ from django.http import HttpResponse
37
+
38
+ req = StudioRequest(
39
+ method=request.method,
40
+ path="/" + (tail or ""),
41
+ query=dict(parse_qs(request.META.get("QUERY_STRING", ""))),
42
+ headers={k.lower(): v for k, v in request.headers.items()},
43
+ body=request.body,
44
+ client=request.META.get("REMOTE_ADDR"),
45
+ raw=request,
46
+ )
47
+ res = await studio.handle(req)
48
+ return HttpResponse(
49
+ res.body,
50
+ status=res.status,
51
+ headers=res.headers,
52
+ content_type=None,
53
+ )
54
+
55
+ studio_view.__name__ = "tortoise_orm_studio_view"
56
+ studio_view.__doc__ = "Async Django view — delegates to Studio.handle()."
57
+ return studio_view
58
+
59
+
60
+ def urls(studio: Any, prefix: str = "studio") -> list:
61
+ """Return Django URL patterns for Studio.
62
+
63
+ Two patterns cover both the bare mount (``/studio/``) and every nested
64
+ path (``/studio/api/health``, ``/studio/static/app.js``, ...).
65
+ """
66
+ from django.urls import path, re_path
67
+
68
+ p = prefix.strip("/")
69
+ view = make_view(studio)
70
+ return [
71
+ path(f"{p}/", view),
72
+ re_path(rf"^{p}/(?P<tail>.+)$", view),
73
+ ]
74
+
75
+
76
+ def install(app: Any, studio: Any, prefix: str = "/studio", **_: Any) -> None:
77
+ """Django has no ``app.mount()`` — the installer exists only to raise help."""
78
+ raise NotImplementedError(
79
+ "Django does not support studio.mount(app, 'django'). Instead, in your "
80
+ "project's urls.py:\n\n"
81
+ " from tortoise_orm_studio.adapters.django_adapter import urls\n"
82
+ f" urlpatterns = [*urls(studio, prefix={prefix.strip('/')!r}), ...]\n\n"
83
+ "Requires Django 4.1+ running under ASGI (daphne / uvicorn / runserver --async)."
84
+ )
@@ -0,0 +1,32 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from ..core.http import StudioRequest, StudioResponse
6
+ from .base import BaseAdapter
7
+
8
+
9
+ class QuartAdapter(BaseAdapter):
10
+ async def to_request(self, native: Any) -> StudioRequest:
11
+ from quart import request
12
+ return StudioRequest(
13
+ method=request.method, path="/" + (native or ""),
14
+ query={k: request.args.getlist(k) for k in request.args.keys()},
15
+ headers={k.lower(): v for k, v in request.headers.items()},
16
+ body=await request.get_data(), client=request.remote_addr, raw=request)
17
+
18
+ def to_response(self, res: StudioResponse) -> Any:
19
+ from quart import Response
20
+ return Response(res.body, status=res.status, headers=res.headers)
21
+
22
+ def install(self, app: Any) -> None:
23
+ async def view(tail: str = "") -> Any:
24
+ return await self(tail)
25
+
26
+ m = list(self.methods)
27
+ app.add_url_rule(self.prefix + "/", endpoint="studio_root", view_func=view, methods=m)
28
+ app.add_url_rule(self.prefix + "/<path:tail>", endpoint="studio_tail", view_func=view, methods=m)
29
+
30
+
31
+ def install(app: Any, studio: Any, prefix: str = "/studio", **_: Any) -> None:
32
+ QuartAdapter(studio, prefix).install(app)
@@ -0,0 +1,39 @@
1
+ """Finds installers by name: built-ins first, then third-party plugins (entry points), then register()."""
2
+ from __future__ import annotations
3
+
4
+ import importlib
5
+ from importlib.metadata import entry_points
6
+ from typing import Any, Callable, Dict
7
+
8
+ Installer = Callable[..., None] # (app, studio, **kwargs) -> None
9
+ GROUP = "tortoise_orm_studio.adapters"
10
+ _CUSTOM: Dict[str, Installer] = {}
11
+ _BUILTIN = {
12
+ "fastapi": "tortoise_orm_studio.adapters.asgi:install_starlette",
13
+ "starlette": "tortoise_orm_studio.adapters.asgi:install_starlette",
14
+ "litestar": "tortoise_orm_studio.adapters.asgi:install_litestar",
15
+ "aiohttp": "tortoise_orm_studio.adapters.aiohttp_adapter:install",
16
+ "sanic": "tortoise_orm_studio.adapters.sanic_adapter:install",
17
+ "quart": "tortoise_orm_studio.adapters.quart_adapter:install",
18
+ "django": "tortoise_orm_studio.adapters.django_adapter:install",
19
+ }
20
+
21
+
22
+ def register(name: str, installer: Installer) -> None:
23
+ _CUSTOM[name.lower()] = installer
24
+
25
+
26
+ def get_installer(name: str) -> Installer:
27
+ name = name.lower()
28
+ if name in _CUSTOM:
29
+ return _CUSTOM[name]
30
+ if name in _BUILTIN:
31
+ module, func = _BUILTIN[name].split(":")
32
+ return getattr(importlib.import_module(module), func)
33
+ eps: Any = entry_points()
34
+ group = eps.select(group=GROUP) if hasattr(eps, "select") else eps.get(GROUP, [])
35
+ for ep in group:
36
+ if ep.name.lower() == name:
37
+ return ep.load()
38
+ raise LookupError(f"No tortoise-orm-studio adapter named {name!r}. "
39
+ f"Write one with BaseAdapter and call registry.register().")
@@ -0,0 +1,39 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from sanic import response
6
+
7
+ from ..core.http import StudioRequest, StudioResponse
8
+ from .base import BaseAdapter
9
+
10
+
11
+ class SanicAdapter(BaseAdapter):
12
+ async def to_request(self, request: Any) -> StudioRequest:
13
+ return StudioRequest(
14
+ method=request.method, path="/" + (request.match_info.get("tail") or ""),
15
+ query={k: list(v) for k, v in request.args.items()},
16
+ headers={k.lower(): v for k, v in request.headers.items()},
17
+ body=request.body, client=request.ip, raw=request)
18
+
19
+ def to_response(self, res: StudioResponse) -> Any:
20
+ return response.raw(res.body, status=res.status, headers=res.headers)
21
+
22
+ def install(self, app: Any) -> None:
23
+ methods = list(self.methods)
24
+
25
+ # Sanic passes route parameters as keyword arguments. Forwarding `tail`
26
+ # into BaseAdapter.__call__(native) raises TypeError on every request,
27
+ # so the wrappers consume it; to_request() still reads match_info.
28
+ async def root(request: Any) -> Any:
29
+ return await self(request)
30
+
31
+ async def tail(request: Any, tail: str = "") -> Any:
32
+ return await self(request)
33
+
34
+ app.add_route(root, self.prefix + "/", methods=methods, name="studio_root")
35
+ app.add_route(tail, self.prefix + "/<tail:path>", methods=methods, name="studio_tail")
36
+
37
+
38
+ def install(app: Any, studio: Any, prefix: str = "/studio", **_: Any) -> None:
39
+ SanicAdapter(studio, prefix).install(app)
@@ -0,0 +1,34 @@
1
+ """Ready-made auth hooks. An auth hook is any callable: (StudioRequest) -> bool | awaitable[bool]."""
2
+ from __future__ import annotations
3
+
4
+ import base64
5
+ import hmac
6
+ from typing import Callable
7
+
8
+ from .core.http import StudioRequest
9
+
10
+
11
+ def basic_auth(username: str, password: str) -> Callable[[StudioRequest], bool]:
12
+ user_b, pass_b = username.encode(), password.encode()
13
+
14
+ def check(req: StudioRequest) -> bool:
15
+ header = req.headers.get("authorization", "")
16
+ if not header.lower().startswith("basic "):
17
+ return False
18
+ try:
19
+ u, _, p = base64.b64decode(header[6:]).partition(b":")
20
+ except Exception:
21
+ return False
22
+ return hmac.compare_digest(u, user_b) & hmac.compare_digest(p, pass_b)
23
+
24
+ return check
25
+
26
+
27
+ def bearer_token(token: str) -> Callable[[StudioRequest], bool]:
28
+ expected = token.encode()
29
+
30
+ def check(req: StudioRequest) -> bool:
31
+ header = req.headers.get("authorization", "")
32
+ return header.lower().startswith("bearer ") and hmac.compare_digest(header[7:].encode(), expected)
33
+
34
+ return check
@@ -0,0 +1,41 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import importlib
5
+ import os
6
+ import sys
7
+ from typing import Any
8
+
9
+ from .auth import basic_auth
10
+ from .core.handler import LOOPBACK
11
+ from .studio import Studio
12
+
13
+
14
+ def load_config(path: str) -> Any:
15
+ """'settings.TORTOISE_ORM' or 'settings:TORTOISE_ORM' -> the dict."""
16
+ module, _, attr = path.replace(":", ".").rpartition(".")
17
+ sys.path.insert(0, os.getcwd())
18
+ return getattr(importlib.import_module(module), attr)
19
+
20
+
21
+ def main(argv: Any = None) -> None:
22
+ p = argparse.ArgumentParser(prog="tortoise-orm-studio", description="Browse and edit Tortoise ORM data.")
23
+ p.add_argument("--config", required=True, help="dotted path to your TORTOISE_ORM dict")
24
+ p.add_argument("--host", default="127.0.0.1")
25
+ p.add_argument("--port", type=int, default=5555)
26
+ p.add_argument("--write", action="store_true", help="enable create/edit/delete (default: read-only)")
27
+ p.add_argument("--password", help="HTTP Basic password (user: studio); required for non-local hosts")
28
+ args = p.parse_args(argv)
29
+ if args.host not in LOOPBACK and not args.password:
30
+ p.error("binding to a non-local host requires --password")
31
+ studio = Studio(read_only=not args.write, auth=basic_auth("studio", args.password) if args.password else None)
32
+ try:
33
+ import uvicorn
34
+ except ImportError:
35
+ p.error("uvicorn is required: pip install 'tortoise-orm-studio[cli]'")
36
+ print(f"Tortoise ORM Studio: http://{args.host}:{args.port} ({'read-write' if args.write else 'read-only'})")
37
+ uvicorn.run(studio.asgi(tortoise_config=load_config(args.config)), host=args.host, port=args.port)
38
+
39
+
40
+ if __name__ == "__main__":
41
+ main()
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,86 @@
1
+ """Aerich migration inspection — read-only.
2
+
3
+ Aerich stores applied migrations in a table named ``aerich`` (``app, version``)
4
+ and migration files as ``{migrations_dir}/{app}/{version}.sql``. This module
5
+ reads both and returns a unified view: which migrations are applied, which
6
+ are present on disk but not applied (pending), and where the files live.
7
+
8
+ Best-effort: if the migrations directory can't be found, ``migrations_dir``
9
+ is null and ``pending`` is empty — the panel still shows applied rows.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import pathlib
14
+ from typing import Any, Dict, List, Optional
15
+
16
+ from tortoise import connections
17
+
18
+ _CANDIDATE_DIRS = ("migrations", "./migrations", "aerich/migrations", "db/migrations")
19
+
20
+
21
+ def _find_migrations_dir(explicit: Optional[str]) -> Optional[pathlib.Path]:
22
+ if explicit:
23
+ p = pathlib.Path(explicit)
24
+ return p if p.is_dir() else None
25
+ for candidate in _CANDIDATE_DIRS:
26
+ p = pathlib.Path(candidate)
27
+ if p.is_dir():
28
+ return p
29
+ return None
30
+
31
+
32
+ def _pending(applied: List[Dict[str, Any]], migrations_dir: pathlib.Path) -> List[Dict[str, Any]]:
33
+ applied_set = {(row["app"], str(row["version"])) for row in applied}
34
+ pending: List[Dict[str, Any]] = []
35
+ for app_dir in sorted(migrations_dir.iterdir()):
36
+ if not app_dir.is_dir():
37
+ continue
38
+ app = app_dir.name
39
+ for sql_file in sorted(app_dir.glob("*.sql")):
40
+ version = sql_file.stem
41
+ if (app, version) not in applied_set:
42
+ pending.append({
43
+ "app": app,
44
+ "version": version,
45
+ "file": sql_file.name,
46
+ })
47
+ return pending
48
+
49
+
50
+ async def inspect(migrations_dir: Optional[str] = None) -> Dict[str, Any]:
51
+ """Return applied + pending migrations for the active connection.
52
+
53
+ Shape:
54
+ {
55
+ "available": bool, # aerich table exists in at least one DB
56
+ "connection": str | None, # which connection has it
57
+ "applied": [{app, version}],
58
+ "migrations_dir": str | None, # resolved absolute path, or null
59
+ "pending": [{app, version, file}],
60
+ }
61
+ """
62
+ applied: List[Dict[str, Any]] = []
63
+ connection_name: Optional[str] = None
64
+
65
+ for name in list(connections.db_config):
66
+ try:
67
+ rows = await connections.get(name).execute_query_dict(
68
+ "SELECT app, version FROM aerich ORDER BY id")
69
+ applied = rows
70
+ connection_name = name
71
+ break
72
+ except Exception:
73
+ continue
74
+
75
+ resolved = _find_migrations_dir(migrations_dir)
76
+ pending: List[Dict[str, Any]] = []
77
+ if resolved is not None:
78
+ pending = _pending(applied, resolved)
79
+
80
+ return {
81
+ "available": bool(applied),
82
+ "connection": connection_name,
83
+ "applied": applied,
84
+ "migrations_dir": str(resolved.resolve()) if resolved else None,
85
+ "pending": pending,
86
+ }
@@ -0,0 +1,87 @@
1
+ """Optional AI filter hook: prompt building + strict, untrusted output parsing.
2
+
3
+ Studio ships NO model, key or AI dependency. The host supplies an async
4
+ callable ``(prompt, task) -> str``. Everything the model returns is treated as
5
+ untrusted text: it is parsed as strict JSON and then run through the SAME
6
+ whitelist as manual filters via :func:`filters.build_query`. No row data ever
7
+ enters the prompt, and no model output is executed as SQL or code.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import re
13
+ from typing import Any, Dict, List
14
+
15
+ from .filters import OPS, TEXT_KINDS, build_query
16
+ from .http import StudioError
17
+
18
+ _FENCE = re.compile(r"^\s*```(?:json)?\s*(.*?)\s*```\s*$", re.S | re.I)
19
+
20
+
21
+ def build_prompt(desc: Dict[str, Any], text: str, task: str = "filter",
22
+ max_chars: int = 2000) -> str:
23
+ """Describe the *visible* schema and ask for JSON filters.
24
+
25
+ ``desc`` must already be permission-filtered by ``StudioService._ctx``:
26
+ hidden fields (exclude / permissions) are absent here, so their names
27
+ never reach the model. No row values are included.
28
+ """
29
+ lines = [
30
+ f"Task: {task}",
31
+ "Return ONLY a JSON array of objects with keys: field, op, value.",
32
+ "No prose, no markdown, no explanation.",
33
+ f"Allowed operators: {', '.join(sorted(OPS))}.",
34
+ f"Text operators ({', '.join(sorted(TEXT_KINDS))} fields only): "
35
+ f"{', '.join(sorted(TEXT_KINDS))}.",
36
+ f"Model: {desc.get('key', '')}",
37
+ "Fields (name: kind):",
38
+ ]
39
+ for f in desc.get("fields", []):
40
+ if f.get("pk"):
41
+ continue # the pk is always visible; no need to advertise it
42
+ choices = f.get("choices") or []
43
+ suffix = f" choices={choices}" if choices else ""
44
+ lines.append(f" - {f['name']}: {f['kind']}{suffix}")
45
+ for path, info in (desc.get("filter_paths") or {}).items():
46
+ if info.get("traversal"):
47
+ lines.append(f" - {path}: {info.get('kind')} (related field)")
48
+ clean = str(text or "")[:max_chars]
49
+ lines += ["User request:", clean, "Filters:"]
50
+ return "\n".join(lines)
51
+
52
+
53
+ def parse_response(raw: Any, desc: Dict[str, Any], enums: Dict[str, Any]) -> List[Dict[str, Any]]:
54
+ """Parse model text into manual-filter-shaped objects, or 400 bad_ai_output.
55
+
56
+ Code fences are stripped. The decoded value must be a list of objects with
57
+ only the keys ``field``, ``op`` and ``value``; every field/operator/value is
58
+ then validated by ``build_query`` (the manual filter whitelist).
59
+ """
60
+ text = raw if isinstance(raw, str) else ""
61
+ fence = _FENCE.match(text)
62
+ if fence:
63
+ text = fence.group(1)
64
+ try:
65
+ data = json.loads(text)
66
+ except (ValueError, TypeError) as e:
67
+ raise StudioError(400, "bad_ai_output", "AI returned invalid JSON") from e
68
+ if not isinstance(data, list):
69
+ raise StudioError(400, "bad_ai_output", "AI output must be a JSON list")
70
+ out: List[Dict[str, Any]] = []
71
+ for item in data:
72
+ if not isinstance(item, dict):
73
+ raise StudioError(400, "bad_ai_output", "Each AI filter must be an object")
74
+ extra = set(item) - {"field", "op", "value"}
75
+ if extra:
76
+ raise StudioError(400, "bad_ai_output", f"Unexpected AI filter keys: {sorted(extra)}")
77
+ field, op, value = item.get("field"), item.get("op", "eq"), item.get("value")
78
+ if not isinstance(field, str) or not isinstance(op, str):
79
+ raise StudioError(400, "bad_ai_output", "AI filter field/op must be strings")
80
+ if len(field) > 200 or len(op) > 32:
81
+ raise StudioError(400, "bad_ai_output", "AI filter field/op is too long")
82
+ out.append({"field": field, "op": op, "value": value})
83
+ try:
84
+ build_query(desc, enums, out, None, None)
85
+ except StudioError as e:
86
+ raise StudioError(400, "bad_ai_output", f"AI filter rejected: {e.message}") from e
87
+ return out