fcakyon/claude-codex-settings / plugins/cloudflare-skills/skills/basin
basin
VerifiedBuild and troubleshoot Cloudflare Basin analytics workflows with Basin Pipelines, Basin Catalog, and Basin SQL. Use for streaming data into R2 Iceberg tables, managing catalogs, or querying those tables; also use for requests using the former Data Platform, Pipelines, R2 Data Catalog, or R2 SQL names.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 2.9 KB |
| references/catalog/README.md | markdown | 1.2 KB |
| references/catalog/api.md | markdown | 3.3 KB |
| references/catalog/configuration.md | markdown | 2.1 KB |
| references/catalog/gotchas.md | markdown | 2.2 KB |
| references/catalog/patterns.md | markdown | 1.7 KB |
| references/pipelines/README.md | markdown | 4.5 KB |
| references/pipelines/api.md | markdown | 5.0 KB |
| references/pipelines/configuration.md | markdown | 6.1 KB |
| references/pipelines/gotchas.md | markdown | 3.0 KB |
| references/pipelines/patterns.md | markdown | 4.6 KB |
| references/skill-feedback.md | markdown | 2.7 KB |
| references/sql/README.md | markdown | 3.4 KB |
| references/sql/api.md | markdown | 4.8 KB |
| references/sql/configuration.md | markdown | 1.7 KB |
| references/sql/gotchas.md | markdown | 2.0 KB |
| references/sql/patterns.md | markdown | 4.3 KB |
references/sql/patterns.md
View on GitHub# Basin SQL Patterns
Code templates for CLI, REST, and Worker access. For performance/partitioning best practices, pull `https://developers.cloudflare.com/basin-sql/reference/limitations-best-practices/index.md`.
## Wrangler CLI
```bash
export WRANGLER_BASIN_SQL_AUTH_TOKEN=$API_TOKEN
npx wrangler basin sql query "${ACCOUNT_ID}_my-bucket" "
SELECT category, COUNT(*) AS cnt, round(AVG(amount), 2) AS avg_amount
FROM analytics.events
WHERE __ingest_ts >= '2026-01-01T00:00:00Z'
GROUP BY category ORDER BY cnt DESC LIMIT 100"
```
## REST API (Python)
```python
import requests
API = f"https://api.sql.cloudflarestorage.com/api/v1/accounts/{ACCOUNT_ID}/basin-sql/query/{BUCKET}"
HEADERS = {"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"}
def r2sql(query):
body = requests.post(API, headers=HEADERS, json={"query": query}, timeout=180).json()
if body["success"]:
return body["result"]["rows"], body["result"]["metrics"]
raise RuntimeError(body["errors"])
rows, metrics = r2sql("SELECT category, COUNT(*) AS cnt FROM analytics.events GROUP BY category LIMIT 10")
```
## REST API (curl)
```bash
curl -X POST \
"https://api.sql.cloudflarestorage.com/api/v1/accounts/$ACCOUNT_ID/basin-sql/query/$BUCKET" \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d '{"query": "SELECT COUNT(*) AS total FROM analytics.events"}'
```
## Dashboard Worker
No Basin SQL binding exists — query the REST endpoint via `fetch()`.
```typescript
interface Env { ACCOUNT_ID: string; BUCKET: string; R2_SQL_TOKEN: string; }
async function queryR2SQL(env: Env, query: string) {
const url = `https://api.sql.cloudflarestorage.com/api/v1/accounts/${env.ACCOUNT_ID}/basin-sql/query/${env.BUCKET}`;
const resp = await fetch(url, {
method: "POST",
headers: { Authorization: `Bearer ${env.R2_SQL_TOKEN}`, "Content-Type": "application/json" },
body: JSON.stringify({ query }),
});
if (!resp.ok) throw new Error(`Basin SQL ${resp.status}: ${await resp.text()}`);
return (await resp.json() as any).result;
}
export default {
async fetch(req: Request, env: Env): Promise<Response> {
if (new URL(req.url).pathname === "/api/analytics") {
const result = await queryR2SQL(env, `
SELECT category, COUNT(*) AS cnt FROM analytics.events
GROUP BY category ORDER BY cnt DESC LIMIT 10`);
return Response.json(result.rows);
}
return new Response("Not found", { status: 404 });
},
};
```
```bash
npx wrangler secret put R2_SQL_TOKEN
```
## Example Queries
```sql
-- Error rate by endpoint
SELECT path, COUNT(*) AS total, SUM(CASE WHEN status >= 400 THEN 1 ELSE 0 END) AS errors
FROM logs.http_requests WHERE __ingest_ts >= '2026-01-01T00:00:00Z'
GROUP BY path ORDER BY errors DESC LIMIT 20;
-- Top-3 slowest requests per method (window + QUALIFY)
SELECT method, path, response_time_ms FROM logs.http_requests
QUALIFY ROW_NUMBER() OVER (PARTITION BY method ORDER BY response_time_ms DESC) <= 3;
-- Cross-table analytics with approx distinct
SELECT z.domain, COUNT(*) AS requests, approx_distinct(h.client_ip) AS uniques
FROM ns.zones z INNER JOIN ns.http_requests h ON z.zone_id = h.zone_id
WHERE h.__ingest_ts >= '2026-06-01T00:00:00Z'
GROUP BY z.domain ORDER BY requests DESC LIMIT 25;
```
## Cursor-Based Pagination
Paginate on a sortable (ideally partition) column rather than `OFFSET`:
```sql
SELECT * FROM logs.requests ORDER BY __ingest_ts DESC LIMIT 500; -- page 1
SELECT * FROM logs.requests WHERE __ingest_ts < '<last_ts>' ORDER BY __ingest_ts DESC LIMIT 500; -- page 2
```
## Performance (essentials)
- **Always `LIMIT`** (early termination); **filter on partition keys first** (`__ingest_ts` range), then add predicates.
- **Narrow time ranges**; **compact tables** (file count dominates latency — enable automatic compaction in [Basin Catalog](../catalog/configuration.md)).
- Read response `metrics` (`files_scanned`, `bytes_scanned`) to tune. Full guidance: limitations-best-practices doc.
## Basin Pipelines → Basin SQL
After `npx wrangler basin pipelines setup` (Basin Catalog destination), wait for first flush (3–7 min), then query the table. See [pipelines/patterns.md](../pipelines/patterns.md).
## See Also
- [api.md](api.md) · [gotchas.md](gotchas.md) · [catalog/patterns.md](../catalog/patterns.md)
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deployment | Stars: 319k | Updated | Claude CodeCodex | Verified | Install |
| xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved. | Stars: 197k | Updated | Claude CodeCodex | Verified | Install |
| shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy. | Stars: 118k | Updated | Claude CodeCodex | Verified | Install |
| childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release. | Stars: 118k | Updated | Claude CodeCodex | Verified | Install |