"""Create / repair PocketBase collections (idempotent). PB 0.25+ ignores legacy `schema` on create and may leave empty collections (only system `id`). Always verify custom fields exist and PATCH if missing. """ 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: dict[str, Any] = { "name": f["name"], "type": f["type"], "required": bool(f.get("required")), } ftype = f.get("type") if ftype == "select" and "values" in f: item["options"] = { "maxSelect": f.get("maxSelect", 1), "values": f["values"], } elif ftype == "json": max_size = 2_000_000 if isinstance(f.get("options"), dict) and f["options"].get("maxSize"): max_size = int(f["options"]["maxSize"]) elif f.get("maxSize"): max_size = int(f["maxSize"]) item["options"] = {"maxSize": max_size} elif ftype == "text" and f.get("max"): item["options"] = {"min": None, "max": int(f["max"]), "pattern": ""} out.append(item) return out def _field_names(collection: dict[str, Any] | None) -> set[str]: if not collection: return set() fields = collection.get("fields") or collection.get("schema") or [] return { str(f.get("name") or "") for f in fields if f.get("name") and f.get("name") != "id" } def _create_payload(body: dict[str, Any]) -> dict[str, Any]: """Prefer modern `fields` (PB ≥0.23); include legacy `schema` for older US boxes.""" fields = body.get("fields") or [] payload: dict[str, Any] = { "name": body["name"], "type": "base", "listRule": body.get("listRule", ""), "viewRule": body.get("viewRule", ""), "createRule": body.get("createRule", ""), "updateRule": body.get("updateRule", ""), "deleteRule": body.get("deleteRule", ""), "fields": fields, "schema": _legacy_schema(fields), } if body.get("indexes"): payload["indexes"] = body["indexes"] return payload def _sync_fields(client: PocketBaseClient, existing: dict[str, Any], body: dict[str, Any]) -> bool: """PATCH missing custom fields onto an existing collection.""" have = _field_names(existing) want = [f for f in (body.get("fields") or []) if f.get("name")] missing = [f for f in want if f["name"] not in have] if not missing and have: return True # Empty or incomplete → replace with full field list (keeps system id) patch: dict[str, Any] = {"fields": want} if body.get("indexes"): patch["indexes"] = body["indexes"] try: client.request( "PATCH", f"/api/collections/{existing['id']}", admin=True, json=patch, ) log.info( "patched PB collection %s (+%d fields)", body["name"], len(missing) if missing else len(want), ) return True except PocketBaseError as exc: # Older PB: try schema key try: client.request( "PATCH", f"/api/collections/{existing['id']}", admin=True, json={"schema": _legacy_schema(want)}, ) log.info("patched PB collection %s via legacy schema", body["name"]) return True except PocketBaseError as exc2: log.warning("PB patch %s failed: %s / %s", body["name"], exc, exc2) return False def ensure_collection(client: PocketBaseClient, body: dict[str, Any]) -> bool: name = body["name"] existing = client.get_collection(name) if existing: have = _field_names(existing) expected = {f["name"] for f in (body.get("fields") or []) if f.get("name")} if expected and expected.issubset(have): return True return _sync_fields(client, existing, body) payload = _create_payload(body) try: created = client.create_collection(payload) # PB 0.25 may still ignore schema — verify and patch have = _field_names(created) expected = {f["name"] for f in (body.get("fields") or []) if f.get("name")} if expected and not expected.issubset(have): return _sync_fields(client, created, body) log.info("created PB collection %s", name) return True except PocketBaseError as exc_create: # Race: created elsewhere existing = client.get_collection(name) if existing: return _sync_fields(client, existing, body) log.warning("PB create %s failed: %s", name, exc_create) 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