Download backend/common/postgrest_errors.py from isold23/MeloonTop: direct link, hf CLI and curl.
- Browser
- Download file 8.39 kB
-
https://huggingface.co/spaces/isold23/MeloonTop/resolve/main/backend/common/postgrest_errors.py
- Command line
-
hf download hf://spaces/isold23/MeloonTop/backend/common/postgrest_errors.py
-
curl -L -o postgrest_errors.py https://huggingface.co/spaces/isold23/MeloonTop/resolve/main/backend/common/postgrest_errors.py
8.39 kB
| """Translate PostgREST failures into actionable HTTP responses. | |
| Supabase answers REST calls with a JSON error envelope whose ``code`` field | |
| says *why* a query failed. Without a translation layer every one of those | |
| reasons collapses into an opaque ``500 Internal Server Error``: the frontend | |
| only learns "something broke" and the operator learns nothing at all, which | |
| made the DB-behind-code failures in this project take far longer to diagnose | |
| than they should have. | |
| Registering the handler below keeps the reason visible on the wire: | |
| ============= ================================================== ======= | |
| PostgREST Meaning HTTP | |
| ============= ================================================== ======= | |
| ``PGRST205`` table missing from the schema cache 500 | |
| ``PGRST204`` column missing from the schema cache 500 | |
| ``PGRST116`` ``.single()`` matched zero rows 404 | |
| ``22P02`` value cannot be cast (e.g. a non-UUID user id) 404 | |
| other unchanged 500 | |
| ============= ================================================== ======= | |
| The two "missing from the schema cache" cases stay ``5xx`` on purpose: they are | |
| *our* fault (the deployed database is older than the code), not the caller's, | |
| and the live smoke tool treats ``5xx`` as a blocker. Silently degrading them to | |
| ``404`` would hide a real outage. What changes is that the body now names the | |
| missing object and the migration script that fixes it. | |
| """ | |
| from __future__ import annotations | |
| import re | |
| from typing import Any, Dict, Optional, Tuple | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.responses import JSONResponse | |
| from common.logging_config import get_logger | |
| logger = get_logger(__name__) | |
| try: # pragma: no cover - postgrest ships with the supabase client | |
| from postgrest.exceptions import APIError | |
| except ImportError: # pragma: no cover | |
| APIError = None # type: ignore[assignment] | |
| MISSING_TABLE = "PGRST205" | |
| MISSING_COLUMN = "PGRST204" | |
| NO_ROWS = "PGRST116" | |
| INVALID_CAST = "22P02" | |
| RLS_DENIED = "42501" | |
| FOREIGN_KEY = "23503" | |
| NOT_NULL = "23502" | |
| UNIQUE_VIOLATION = "23505" | |
| MIGRATION_SCRIPT = "backend/migrations/20261002_deploy_all.sql" | |
| RLS_SCRIPT = "backend/migrations/20261002b_rls_policies.sql" | |
| # PostgREST quotes the object it is complaining about, but the quote style | |
| # varies by error: PGRST205 uses single quotes | |
| # (``Could not find the table 'public.exam_user_downloads' ...``) while 42501 | |
| # uses double quotes | |
| # (``new row violates row-level security policy for table "exam_profile"``). | |
| _QUOTED_OBJECT = re.compile(r"['\"]([^'\"]+)['\"]") | |
| def _quoted_object(message: Optional[str]) -> Optional[str]: | |
| """Return the schema object named inside a PostgREST message, if any.""" | |
| match = _QUOTED_OBJECT.search(message or "") | |
| return match.group(1) if match else None | |
| def _object_label(raw: Optional[str]) -> Optional[str]: | |
| """Strip the ``public.`` schema prefix for a friendlier message.""" | |
| if not raw: | |
| return None | |
| return raw.split(".", 1)[1] if raw.startswith("public.") else raw | |
| def describe(exc: Any) -> Tuple[int, str]: | |
| """Map a PostgREST ``APIError`` onto an HTTP status and a readable detail. | |
| Kept as a pure function so it can be unit-tested without spinning up an app. | |
| """ | |
| code = getattr(exc, "code", None) | |
| message = getattr(exc, "message", None) or str(exc) | |
| obj = _object_label(_quoted_object(message)) | |
| # A missing table/column and an RLS refusal mean the *deployment* is behind | |
| # the code, which is exactly the kind of thing an operator must see in the | |
| # logs. The other codes are usually caller mistakes and stay at DEBUG. | |
| if code in (MISSING_TABLE, MISSING_COLUMN): | |
| logger.error( | |
| "数据库结构落后于代码 (code=%s, object=%s): %s", | |
| code, | |
| obj or "<unknown>", | |
| message, | |
| ) | |
| elif code == RLS_DENIED: | |
| logger.error( | |
| "数据库拒绝写入,可能缺少 RLS 策略 (code=%s, object=%s): %s", | |
| code, | |
| obj or "<unknown>", | |
| message, | |
| ) | |
| else: | |
| logger.debug("PostgREST 错误已映射 (code=%s, object=%s)", code, obj) | |
| if code == MISSING_TABLE: | |
| detail = f"数据库缺少数据表 {obj},服务端结构落后于代码。" if obj else ( | |
| "数据库缺少数据表,服务端结构落后于代码。" | |
| ) | |
| return 500, f"{detail}请执行 {MIGRATION_SCRIPT} 后重试。" | |
| if code == MISSING_COLUMN: | |
| detail = f"数据表字段 {obj} 不存在,服务端结构落后于代码。" if obj else ( | |
| "数据表字段不存在,服务端结构落后于代码。" | |
| ) | |
| return 500, f"{detail}请执行 {MIGRATION_SCRIPT} 后重试。" | |
| if code == NO_ROWS: | |
| return 404, "资源不存在" | |
| if code == INVALID_CAST: | |
| # Overwhelmingly a non-UUID user id reaching a ``uuid`` column: the | |
| # identifier simply cannot match any row, so "not found" is accurate. | |
| return 404, "资源不存在:标识符格式不合法" | |
| if code == RLS_DENIED: | |
| # Row Level Security refused the write. The backend uses the anon key, | |
| # so a table that Supabase created with RLS on and no policy answers | |
| # 42501 for every write -- a provisioning gap, not a bad request. | |
| detail = f"数据库拒绝写入数据表 {obj}(RLS 无策略)。" if obj else ( | |
| "数据库拒绝写入(RLS 无策略)。" | |
| ) | |
| return 500, f"{detail}请执行 {RLS_SCRIPT} 后重试。" | |
| return 500, f"数据库查询失败({code or 'unknown'}):{message}" | |
| def is_unique_violation(exc: Any) -> bool: | |
| """True when *exc* is a PostgREST ``23505`` (duplicate key).""" | |
| return getattr(exc, "code", None) == UNIQUE_VIOLATION | |
| def is_foreign_key_violation(exc: Any) -> bool: | |
| """True when *exc* is a PostgREST ``23503`` (foreign key refuses the row). | |
| Handlers that write to a table whose foreign key still targets a retired | |
| table use this to degrade to a local-only answer instead of a bare 500. | |
| """ | |
| return getattr(exc, "code", None) == FOREIGN_KEY | |
| def register_postgrest_error_handler(app: FastAPI) -> None: | |
| """Attach the translation handler to ``app`` (no-op without postgrest).""" | |
| if APIError is None: # pragma: no cover | |
| logger.warning("postgrest 不可用,未注册数据库错误转换处理器") | |
| return | |
| async def _handler(request: Any, exc: Exception) -> JSONResponse: | |
| status_code, detail = describe(exc) | |
| logger.warning( | |
| "数据库错误已转换为 HTTP %s (path=%s, code=%s): %s", | |
| status_code, | |
| getattr(request, "url", {}), | |
| getattr(exc, "code", None), | |
| detail, | |
| ) | |
| return JSONResponse(status_code=status_code, content={"detail": detail}) | |
| app.add_exception_handler(APIError, _handler) | |
| logger.debug("已注册 PostgREST 错误转换处理器") | |
| def as_dict(exc: Any) -> Dict[str, Any]: | |
| """Expose the raw PostgREST envelope for logging/debugging.""" | |
| return { | |
| "code": getattr(exc, "code", None), | |
| "message": getattr(exc, "message", None), | |
| "hint": getattr(exc, "hint", None), | |
| "details": getattr(exc, "details", None), | |
| } | |
| def http_error_from(exc: Exception, fallback_status: int = 500) -> HTTPException: | |
| """Build an ``HTTPException`` that preserves *why* a query failed. | |
| Router handlers used to end every database call with:: | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| which flattened *every* failure into a 500 whose ``detail`` was a Python | |
| dict repr -- so "the deployed database is missing a table" and "the code is | |
| broken" looked identical to whoever was reading the logs. Funnelling those | |
| clauses through here keeps the status mapping in one place and lets | |
| ``PGRST205`` say which migration to run. | |
| """ | |
| if APIError is not None and isinstance(exc, APIError): | |
| status_code, detail = describe(exc) | |
| return HTTPException(status_code=status_code, detail=detail) | |
| if isinstance(exc, HTTPException): | |
| return exc | |
| return HTTPException(status_code=fallback_status, detail=str(exc)) | |