File size: 1,494 Bytes
8511813
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
"""
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 []