Spaces:
Sleeping
Sleeping
| """ | |
| Federation Node — Cloudflare D1 Client | |
| ====================================== | |
| Contract: C-FED-NODE-001 v0.1.1 (Phase 2 Vault) | |
| Raw HTTPS wrapper for executing SQLite queries against Cloudflare D1. | |
| """ | |
| import os | |
| import httpx | |
| from typing import Any, Optional | |
| ACCOUNT_ID = os.getenv("CLOUDFLARE_ACCOUNT_ID") | |
| DATABASE_ID = os.getenv("CLOUDFLARE_D1_DATABASE_ID") | |
| API_TOKEN = os.getenv("CLOUDFLARE_D1_API_TOKEN") | |
| async def execute_sql(sql: str, params: Optional[list[Any]] = None) -> list[dict]: | |
| """Execute a single SQL query against the D1 Vault.""" | |
| if not (ACCOUNT_ID and DATABASE_ID and API_TOKEN): | |
| print("⚠️ D1 Credentials missing. SQL execution skipped.") | |
| return [] | |
| url = f"https://api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/d1/database/{DATABASE_ID}/query" | |
| headers = { | |
| "Authorization": f"Bearer {API_TOKEN}", | |
| "Content-Type": "application/json" | |
| } | |
| payload = {"sql": sql} | |
| if params: | |
| payload["params"] = params | |
| async with httpx.AsyncClient(timeout=10.0) as client: | |
| try: | |
| r = await client.post(url, headers=headers, json=payload) | |
| r.raise_for_status() | |
| data = r.json() | |
| if not data.get("success"): | |
| print(f"🔴 D1 Query Error: {data.get('errors')}") | |
| return [] | |
| return data["result"][0].get("results", []) | |
| except Exception as e: | |
| print(f"🔴 D1 Connection Error: {e}") | |
| return [] | |