Spaces:
Sleeping
Sleeping
| from fastapi import APIRouter | |
| import os | |
| import json | |
| from datetime import datetime | |
| from supabase import create_client, Client | |
| router = APIRouter() | |
| async def test_supabase(): | |
| """ | |
| Debug endpoint to test Supabase connection and insertion. | |
| WARNING: Public endpoint for debugging only. Remove after use. | |
| """ | |
| results = { | |
| "timestamp": datetime.now().isoformat(), | |
| "env_vars": {}, | |
| "connection": "pending", | |
| "insert": "pending", | |
| "error": None | |
| } | |
| # 1. Check Env Vars | |
| url = os.getenv("SUPABASE_URL") | |
| key = os.getenv("SUPABASE_ANON_KEY") or os.getenv("SUPABASE_SERVICE_ROLE_KEY") | |
| enable_metrics = os.getenv("ENABLE_METRICS_LOGGING", "false").lower() == "true" | |
| results["env_vars"] = { | |
| "SUPABASE_URL_SET": bool(url), | |
| "SUPABASE_KEY_SET": bool(key), | |
| "ENABLE_METRICS_LOGGING": enable_metrics, | |
| "ENABLE_METRICS_LOGGING_RAW": os.getenv("ENABLE_METRICS_LOGGING") | |
| } | |
| if not url or not key: | |
| results["connection"] = "failed" | |
| results["error"] = "Missing SUPABASE_URL or SUPABASE_KEY env vars" | |
| return results | |
| # 2. Connect | |
| try: | |
| supabase: Client = create_client(url, key) | |
| results["connection"] = "success" | |
| except Exception as e: | |
| results["connection"] = "failed" | |
| results["error"] = f"Client init failed: {str(e)}" | |
| return results | |
| # 3. Test Insert | |
| payload = { | |
| "question": "DEBUG_ENDPOINT_PROBE", | |
| "answer": "This is a test row from /api/test-supabase", | |
| "provenance": "debug_endpoint", | |
| "user_id": "debug_user" | |
| } | |
| try: | |
| response = supabase.table("metrics_chat_answers").insert(payload).execute() | |
| results["insert"] = "success" | |
| results["data"] = response.data | |
| except Exception as e: | |
| results["insert"] = "failed" | |
| results["error"] = f"Insert failed: {str(e)}" | |
| # Add hint about RLS | |
| if "policy" in str(e).lower() or "permission" in str(e).lower(): | |
| results["hint"] = "Check Row Level Security (RLS) policies for 'metrics_chat_answers' table." | |
| return results | |