nomadro/apps/api/services/nomadro_pb/ensure.py
Eric b06a14b6aa Ship social admin nested menus with list/detail CRUD, soft-archive UGC, and PocketBase-ready stores.
admin.nomadro.com gets sidebar L1/L2 social ops (paginated lists + entity detail); API adds soft-delete archives/stats and shared nomadro_pb for social/coffee/notify/work.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 16:41:43 +08:00

84 lines
2.2 KiB
Python

"""Create missing PocketBase collections (idempotent)."""
from __future__ import annotations
import logging
from typing import Any
from nomadro_pb.client import PocketBaseClient, PocketBaseError, get_pb
from nomadro_pb.schemas import ALL_COLLECTIONS
log = logging.getLogger("nomadro_pb.ensure")
_ensured = False
def _legacy_schema(fields: list[dict[str, Any]]) -> list[dict[str, Any]]:
out: list[dict[str, Any]] = []
for f in fields:
item = {
"name": f["name"],
"type": f["type"],
"required": bool(f.get("required")),
}
if f["type"] == "select" and "values" in f:
item["options"] = {
"maxSelect": f.get("maxSelect", 1),
"values": f["values"],
}
out.append(item)
return out
def ensure_collection(client: PocketBaseClient, body: dict[str, Any]) -> bool:
name = body["name"]
existing = client.get_collection(name)
if existing:
return True
try:
client.create_collection(body)
log.info("created PB collection %s", name)
return True
except PocketBaseError as exc:
# Older PocketBase: schema instead of fields
legacy = {
"name": name,
"type": "base",
"listRule": None,
"viewRule": None,
"createRule": None,
"updateRule": None,
"deleteRule": None,
"schema": _legacy_schema(body.get("fields") or []),
}
try:
client.create_collection(legacy)
log.info("created PB collection %s (legacy schema)", name)
return True
except PocketBaseError as exc2:
log.warning("PB create %s failed: %s / %s", name, exc, exc2)
return False
def ensure_all_collections(client: PocketBaseClient | None = None) -> dict[str, bool]:
global _ensured
pb = client or get_pb()
results: dict[str, bool] = {}
for body in ALL_COLLECTIONS:
name = body["name"]
try:
results[name] = ensure_collection(pb, body)
except Exception as exc: # pragma: no cover
log.warning("ensure %s: %s", name, exc)
results[name] = False
_ensured = all(results.values()) if results else False
return results
def ensure_once() -> bool:
global _ensured
if _ensured:
return True
results = ensure_all_collections()
ok = all(results.values()) if results else False
_ensured = ok
return ok