Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Cloudflare platform skill covering Workers, D1, R2, KV, AI, Durable Objects, and security.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/d1/README.md
1# Cloudflare D1 Database23Expert guidance for Cloudflare D1, a serverless SQLite database designed for horizontal scale-out across multiple databases.45## Overview67D1 is Cloudflare's managed, serverless database with:8- SQLite SQL semantics and compatibility9- Built-in disaster recovery via Time Travel (30-day point-in-time recovery)10- Horizontal scale-out architecture (10 GB per database)11- Worker and HTTP API access12- Pricing based on query and storage costs only1314**Architecture Philosophy**: D1 is optimized for per-user, per-tenant, or per-entity database patterns rather than single large databases.1516## Quick Start1718```bash19# Create database20wrangler d1 create <database-name>2122# Execute migration23wrangler d1 migrations apply <db-name> --remote2425# Local development26wrangler dev27```2829## Core Query Methods3031```typescript32// .all() - Returns all rows; .first() - First row or null; .first(col) - Single column value33// .run() - INSERT/UPDATE/DELETE; .raw() - Array of arrays (efficient)34const { results, success, meta } = await env.DB.prepare('SELECT * FROM users WHERE active = ?').bind(true).all();35const user = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(userId).first();36```3738## Batch Operations3940```typescript41// Multiple queries in single round trip (atomic transaction)42const results = await env.DB.batch([43env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(1),44env.DB.prepare('SELECT * FROM posts WHERE author_id = ?').bind(1),45env.DB.prepare('UPDATE users SET last_access = ? WHERE id = ?').bind(Date.now(), 1)46]);47```4849## Sessions API (Paid Plans)5051```typescript52// Create long-running session for analytics/migrations (up to 15 minutes)53const session = env.DB.withSession();54try {55await session.prepare('CREATE INDEX idx_heavy ON large_table(column)').run();56await session.prepare('ANALYZE').run();57} finally {58session.close(); // Always close to release resources59}60```6162## Read Replication (Paid Plans)6364```typescript65// Read from nearest replica for lower latency (automatic failover)66const user = await env.DB_REPLICA.prepare('SELECT * FROM users WHERE id = ?').bind(userId).first();6768// Writes always go to primary69await env.DB.prepare('UPDATE users SET last_login = ? WHERE id = ?').bind(Date.now(), userId).run();70```7172## Platform Limits7374| Limit | Free Tier | Paid Plans |75|-------|-----------|------------|76| Database size | 500 MB | 10 GB per database |77| Row size | 1 MB max | 1 MB max |78| Query timeout | 30 seconds | 30 seconds |79| Batch size | 1,000 statements | 10,000 statements |80| Time Travel retention | 7 days | 30 days |81| Read replicas | Not available | Yes (paid add-on) |8283**Pricing**: $0.001 per million rows read + $1.00 per million rows written + $0.75/GB storage/month (includes free monthly allowance; no per-database fee)8485## CLI Commands8687```bash88# Database management89wrangler d1 create <db-name>90wrangler d1 list91wrangler d1 delete <db-name>9293# Migrations94wrangler d1 migrations create <db-name> <migration-name> # Create new migration file95wrangler d1 migrations apply <db-name> --remote # Apply pending migrations96wrangler d1 migrations apply <db-name> --local # Apply locally97wrangler d1 migrations list <db-name> --remote # Show applied migrations9899# Direct SQL execution100wrangler d1 execute <db-name> --remote --command="SELECT * FROM users"101wrangler d1 execute <db-name> --local --file=./schema.sql102103# Backups & Import/Export104wrangler d1 export <db-name> --remote --output=./backup.sql # Full export with schema105wrangler d1 export <db-name> --remote --no-schema --output=./data.sql # Data only106wrangler d1 time-travel restore <db-name> --timestamp="2024-01-15T14:30:00Z" # Point-in-time recovery107108# Development109wrangler dev --persist-to=./.wrangler/state110```111112## Reading Order113114**Start here**: Quick Start above → configuration.md (setup) → api.md (queries)115116**Common tasks**:117- First time setup: configuration.md → Run migrations118- Adding queries: api.md → Prepared statements119- Pagination/caching: patterns.md120- Production optimization: Read Replication + Sessions API (this file)121- Debugging: gotchas.md122123## In This Reference124125- [configuration.md](./configuration.md) - wrangler.jsonc setup, migrations, TypeScript types, ORMs, local dev126- [api.md](./api.md) - Query methods (.all/.first/.run/.raw), batch, sessions, read replicas, error handling127- [patterns.md](./patterns.md) - Pagination, bulk operations, caching, multi-tenant, sessions, analytics128- [gotchas.md](./gotchas.md) - SQL injection, limits by plan tier, performance, common errors129130## See Also131132- [workers](../workers/) - Worker runtime and fetch handler patterns133- [hyperdrive](../hyperdrive/) - Connection pooling for external databases134