[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AJXN3AEVT39KYYJTHS3HZ6":3,"skill-same:01M7AJXN3AEVT39KYYJTHS3HZ6":60},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":24,"commitSha":25,"skillDirectory":5,"forksCount":26,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":29,"install":30,"resources":43},"01M7AJXN3AEVT39KYYJTHS3HZ6","cloudflare-d1",null,"Complete knowledge domain for Cloudflare D1 - serverless SQLite database on Cloudflare's edge network.\n\nUse when: creating D1 databases, writing SQL migrations, configuring D1 bindings, querying D1 from Workers,\nhandling SQLite data, building relational data models, or encountering \"D1_ERROR\", \"statement too long\",\n\"too many requests queued\", migration failures, or query performance issues.\n\nKeywords: d1, d1 database, cloudflare d1, wrangler d1, d1 migrations, d1 bindings, sqlite workers,\nserverless database, edge database, d1 queries, sql cloudflare, prepared statements, batch queries,\nd1 api, wrangler migrations, D1_ERROR, D1_EXEC_ERROR, statement too long, database bindings,\nsqlite cloudflare, sql workers api, d1 indexes, query optimization, d1 schema","davidanthonyn\u002Fagent-skills","davidanthonyn","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F55152980?v=4","01M7AJ4MY8S5C2RJCGX6626J0G","01M7AJ4MZB7EC7CAP27ANCSE7N",1,"MIT","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fcloudflare-d1\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: cloudflare-d1\ndescription: |\n  Complete knowledge domain for Cloudflare D1 - serverless SQLite database on Cloudflare's edge network.\n\n  Use when: creating D1 databases, writing SQL migrations, configuring D1 bindings, querying D1 from Workers,\n  handling SQLite data, building relational data models, or encountering \"D1_ERROR\", \"statement too long\",\n  \"too many requests queued\", migration failures, or query performance issues.\n\n  Keywords: d1, d1 database, cloudflare d1, wrangler d1, d1 migrations, d1 bindings, sqlite workers,\n  serverless database, edge database, d1 queries, sql cloudflare, prepared statements, batch queries,\n  d1 api, wrangler migrations, D1_ERROR, D1_EXEC_ERROR, statement too long, database bindings,\n  sqlite cloudflare, sql workers api, d1 indexes, query optimization, d1 schema\nlicense: MIT\n---\n\n# Cloudflare D1 Database\n\n**Status**: Production Ready ✅\n**Last Updated**: 2025-10-21\n**Dependencies**: cloudflare-worker-base (for Worker setup)\n**Latest Versions**: wrangler@4.43.0, @cloudflare\u002Fworkers-types@4.20251014.0\n\n---\n\n## Quick Start (5 Minutes)\n\n### 1. Create D1 Database\n\n```bash\n# Create a new D1 database\nnpx wrangler d1 create my-database\n\n# Output includes database_id - save this!\n# ✅ Successfully created DB 'my-database'\n#\n# [[d1_databases]]\n# binding = \"DB\"\n# database_name = \"my-database\"\n# database_id = \"\u003CUUID>\"\n```\n\n### 2. Configure Bindings\n\nAdd to your `wrangler.jsonc`:\n\n```jsonc\n{\n  \"name\": \"my-worker\",\n  \"main\": \"src\u002Findex.ts\",\n  \"compatibility_date\": \"2025-10-11\",\n  \"d1_databases\": [\n    {\n      \"binding\": \"DB\",                    \u002F\u002F Available as env.DB in your Worker\n      \"database_name\": \"my-database\",      \u002F\u002F Name from wrangler d1 create\n      \"database_id\": \"\u003CUUID>\",             \u002F\u002F ID from wrangler d1 create\n      \"preview_database_id\": \"local-db\"    \u002F\u002F For local development\n    }\n  ]\n}\n```\n\n**CRITICAL:**\n- `binding` is how you access the database in code (`env.DB`)\n- `database_id` is the production database UUID\n- `preview_database_id` is for local dev (can be any string)\n- **Never commit real `database_id` values to public repos** - use environment variables or secrets\n\n### 3. Create Your First Migration\n\n```bash\n# Create migration file\nnpx wrangler d1 migrations create my-database create_users_table\n\n# This creates: migrations\u002F0001_create_users_table.sql\n```\n\nEdit the migration file:\n\n```sql\n-- migrations\u002F0001_create_users_table.sql\nDROP TABLE IF EXISTS users;\nCREATE TABLE IF NOT EXISTS users (\n  user_id INTEGER PRIMARY KEY AUTOINCREMENT,\n  email TEXT NOT NULL UNIQUE,\n  username TEXT NOT NULL,\n  created_at INTEGER NOT NULL,\n  updated_at INTEGER\n);\n\n-- Create index for common queries\nCREATE INDEX IF NOT EXISTS idx_users_email ON users(email);\n\n-- Optimize database\nPRAGMA optimize;\n```\n\n### 4. Apply Migration\n\n```bash\n# Apply locally first (for testing)\nnpx wrangler d1 migrations apply my-database --local\n\n# Apply to production when ready\nnpx wrangler d1 migrations apply my-database --remote\n```\n\n### 5. Query from Your Worker\n\n```typescript\n\u002F\u002F src\u002Findex.ts\nimport { Hono } from 'hono';\n\ntype Bindings = {\n  DB: D1Database;\n};\n\nconst app = new Hono\u003C{ Bindings: Bindings }>();\n\napp.get('\u002Fapi\u002Fusers\u002F:email', async (c) => {\n  const email = c.req.param('email');\n\n  try {\n    \u002F\u002F ALWAYS use prepared statements with bind()\n    const result = await c.env.DB.prepare(\n      'SELECT * FROM users WHERE email = ?'\n    )\n    .bind(email)\n    .first();\n\n    if (!result) {\n      return c.json({ error: 'User not found' }, 404);\n    }\n\n    return c.json(result);\n  } catch (error: any) {\n    console.error('D1 Error:', error.message);\n    return c.json({ error: 'Database error' }, 500);\n  }\n});\n\nexport default app;\n```\n\n---\n\n## D1 Migrations System\n\n### Migration Workflow\n\n```bash\n# 1. Create migration\nnpx wrangler d1 migrations create \u003CDATABASE_NAME> \u003CMIGRATION_NAME>\n\n# 2. List unapplied migrations\nnpx wrangler d1 migrations list \u003CDATABASE_NAME> --local\nnpx wrangler d1 migrations list \u003CDATABASE_NAME> --remote\n\n# 3. Apply migrations\nnpx wrangler d1 migrations apply \u003CDATABASE_NAME> --local   # Test locally\nnpx wrangler d1 migrations apply \u003CDATABASE_NAME> --remote  # Deploy to production\n```\n\n### Migration File Naming\n\nMigrations are automatically versioned:\n\n```\nmigrations\u002F\n├── 0000_initial_schema.sql\n├── 0001_add_users_table.sql\n├── 0002_add_posts_table.sql\n└── 0003_add_indexes.sql\n```\n\n**Rules:**\n- Files are executed in sequential order\n- Each migration runs once (tracked in `d1_migrations` table)\n- Failed migrations roll back (transactional)\n- Can't modify or delete applied migrations\n\n### Custom Migration Configuration\n\n```jsonc\n{\n  \"d1_databases\": [\n    {\n      \"binding\": \"DB\",\n      \"database_name\": \"my-database\",\n      \"database_id\": \"\u003CUUID>\",\n      \"migrations_dir\": \"db\u002Fmigrations\",        \u002F\u002F Custom directory (default: migrations\u002F)\n      \"migrations_table\": \"schema_migrations\"   \u002F\u002F Custom tracking table (default: d1_migrations)\n    }\n  ]\n}\n```\n\n### Migration Best Practices\n\n#### ✅ Always Do:\n\n```sql\n-- Use IF NOT EXISTS to make migrations idempotent\nCREATE TABLE IF NOT EXISTS users (...);\nCREATE INDEX IF NOT EXISTS idx_users_email ON users(email);\n\n-- Run PRAGMA optimize after schema changes\nPRAGMA optimize;\n\n-- Use transactions for data migrations\nBEGIN TRANSACTION;\nUPDATE users SET updated_at = unixepoch() WHERE updated_at IS NULL;\nCOMMIT;\n```\n\n#### ❌ Never Do:\n\n```sql\n-- DON'T include BEGIN TRANSACTION at start (D1 handles this)\nBEGIN TRANSACTION;  -- ❌ Remove this\n\n-- DON'T use MySQL\u002FPostgreSQL syntax\nALTER TABLE users MODIFY COLUMN email VARCHAR(255);  -- ❌ Not SQLite\n\n-- DON'T create tables without IF NOT EXISTS\nCREATE TABLE users (...);  -- ❌ Fails if table exists\n```\n\n### Handling Foreign Keys in Migrations\n\n```sql\n-- Temporarily disable foreign key checks during schema changes\nPRAGMA defer_foreign_keys = true;\n\n-- Make schema changes that would violate foreign keys\nALTER TABLE posts DROP COLUMN author_id;\nALTER TABLE posts ADD COLUMN user_id INTEGER REFERENCES users(user_id);\n\n-- Foreign keys re-enabled automatically at end of migration\n```\n\n---\n\n## D1 Workers API\n\n### Type Definitions\n\n```typescript\n\u002F\u002F Add to env.d.ts or worker-configuration.d.ts\ninterface Env {\n  DB: D1Database;\n  \u002F\u002F ... other bindings\n}\n\n\u002F\u002F For Hono\ntype Bindings = {\n  DB: D1Database;\n};\n\nconst app = new Hono\u003C{ Bindings: Bindings }>();\n```\n\n### prepare() - Prepared Statements (PRIMARY METHOD)\n\n**Always use prepared statements for queries with user input.**\n\n```typescript\n\u002F\u002F Basic prepared statement\nconst stmt = env.DB.prepare('SELECT * FROM users WHERE user_id = ?');\nconst bound = stmt.bind(userId);\nconst result = await bound.first();\n\n\u002F\u002F Chained (most common pattern)\nconst user = await env.DB.prepare('SELECT * FROM users WHERE email = ?')\n  .bind(email)\n  .first();\n```\n\n**Why use prepare():**\n- ✅ Prevents SQL injection\n- ✅ Can be reused with different parameters\n- ✅ Better performance (query plan caching)\n- ✅ Type-safe with TypeScript\n\n### Query Result Methods\n\n#### .all() - Get All Rows\n\n```typescript\nconst { results, meta } = await env.DB.prepare(\n  'SELECT * FROM users WHERE created_at > ?'\n)\n.bind(timestamp)\n.all();\n\nconsole.log(results);  \u002F\u002F Array of rows\nconsole.log(meta);     \u002F\u002F { duration, rows_read, rows_written }\n```\n\n#### .first() - Get First Row\n\n```typescript\n\u002F\u002F Returns first row or null\nconst user = await env.DB.prepare('SELECT * FROM users WHERE email = ?')\n  .bind('user@example.com')\n  .first();\n\nif (!user) {\n  return c.json({ error: 'Not found' }, 404);\n}\n```\n\n#### .first(column) - Get Single Column Value\n\n```typescript\n\u002F\u002F Returns the value of a specific column from first row\nconst count = await env.DB.prepare('SELECT COUNT(*) as total FROM users')\n  .first('total');\n\nconsole.log(count);  \u002F\u002F 42 (just the number, not an object)\n```\n\n#### .run() - Execute Without Results\n\n```typescript\n\u002F\u002F For INSERT, UPDATE, DELETE\nconst { success, meta } = await env.DB.prepare(\n  'INSERT INTO users (email, username, created_at) VALUES (?, ?, ?)'\n)\n.bind(email, username, Date.now())\n.run();\n\nconsole.log(meta);  \u002F\u002F { duration, rows_read, rows_written, last_row_id }\n```\n\n### batch() - Execute Multiple Queries\n\n**CRITICAL FOR PERFORMANCE**: Use batch() to reduce latency.\n\n```typescript\n\u002F\u002F Prepare multiple statements\nconst stmt1 = env.DB.prepare('SELECT * FROM users WHERE user_id = ?').bind(1);\nconst stmt2 = env.DB.prepare('SELECT * FROM users WHERE user_id = ?').bind(2);\nconst stmt3 = env.DB.prepare('SELECT * FROM posts WHERE user_id = ?').bind(1);\n\n\u002F\u002F Execute all in one round trip\nconst results = await env.DB.batch([stmt1, stmt2, stmt3]);\n\nconsole.log(results[0].results);  \u002F\u002F Users query 1\nconsole.log(results[1].results);  \u002F\u002F Users query 2\nconsole.log(results[2].results);  \u002F\u002F Posts query\n```\n\n**Batch Behavior:**\n- Executes sequentially (in order)\n- Each statement commits individually (auto-commit mode)\n- If one fails, remaining statements don't execute\n- Much faster than individual queries (single network round trip)\n\n**Batch Use Cases:**\n```typescript\n\u002F\u002F ✅ Insert multiple rows efficiently\nconst inserts = users.map(user =>\n  env.DB.prepare('INSERT INTO users (email, username) VALUES (?, ?)')\n    .bind(user.email, user.username)\n);\nawait env.DB.batch(inserts);\n\n\u002F\u002F ✅ Fetch related data in parallel\nconst [user, posts, comments] = await env.DB.batch([\n  env.DB.prepare('SELECT * FROM users WHERE user_id = ?').bind(userId),\n  env.DB.prepare('SELECT * FROM posts WHERE user_id = ?').bind(userId),\n  env.DB.prepare('SELECT * FROM comments WHERE user_id = ?').bind(userId)\n]);\n```\n\n### exec() - Execute Raw SQL (AVOID IN PRODUCTION)\n\n```typescript\n\u002F\u002F Only for migrations, maintenance, and one-off tasks\nconst result = await env.DB.exec(`\n  SELECT * FROM users;\n  SELECT * FROM posts;\n`);\n\nconsole.log(result);  \u002F\u002F { count: 2, duration: 5 }\n```\n\n**NEVER use exec() for:**\n- ❌ Queries with user input (SQL injection risk)\n- ❌ Production queries (poor performance)\n- ❌ Queries that need results (exec doesn't return data)\n\n**ONLY use exec() for:**\n- ✅ Running migration SQL files locally\n- ✅ One-off maintenance tasks\n- ✅ Database initialization scripts\n\n---\n\n## Query Patterns\n\n### Basic CRUD Operations\n\n#### Create (INSERT)\n\n```typescript\n\u002F\u002F Single insert\nconst { meta } = await env.DB.prepare(\n  'INSERT INTO users (email, username, created_at) VALUES (?, ?, ?)'\n)\n.bind(email, username, Date.now())\n.run();\n\nconst newUserId = meta.last_row_id;\n\n\u002F\u002F Bulk insert with batch()\nconst users = [\n  { email: 'user1@example.com', username: 'user1' },\n  { email: 'user2@example.com', username: 'user2' }\n];\n\nconst inserts = users.map(u =>\n  env.DB.prepare('INSERT INTO users (email, username, created_at) VALUES (?, ?, ?)')\n    .bind(u.email, u.username, Date.now())\n);\n\nawait env.DB.batch(inserts);\n```\n\n#### Read (SELECT)\n\n```typescript\n\u002F\u002F Single row\nconst user = await env.DB.prepare('SELECT * FROM users WHERE user_id = ?')\n  .bind(userId)\n  .first();\n\n\u002F\u002F Multiple rows\nconst { results } = await env.DB.prepare(\n  'SELECT * FROM users WHERE created_at > ? ORDER BY created_at DESC LIMIT ?'\n)\n.bind(timestamp, 10)\n.all();\n\n\u002F\u002F Count\nconst count = await env.DB.prepare('SELECT COUNT(*) as total FROM users')\n  .first('total');\n\n\u002F\u002F Exists check\nconst exists = await env.DB.prepare('SELECT 1 FROM users WHERE email = ? LIMIT 1')\n  .bind(email)\n  .first();\n\nif (exists) {\n  \u002F\u002F Email already registered\n}\n```\n\n#### Update (UPDATE)\n\n```typescript\nconst { meta } = await env.DB.prepare(\n  'UPDATE users SET username = ?, updated_at = ? WHERE user_id = ?'\n)\n.bind(newUsername, Date.now(), userId)\n.run();\n\nconst rowsAffected = meta.rows_written;\n\nif (rowsAffected === 0) {\n  \u002F\u002F User not found\n}\n```\n\n#### Delete (DELETE)\n\n```typescript\nconst { meta } = await env.DB.prepare('DELETE FROM users WHERE user_id = ?')\n  .bind(userId)\n  .run();\n\nconst rowsDeleted = meta.rows_written;\n```\n\n### Advanced Queries\n\n#### Pagination\n\n```typescript\napp.get('\u002Fapi\u002Fusers', async (c) => {\n  const page = parseInt(c.req.query('page') || '1');\n  const limit = parseInt(c.req.query('limit') || '20');\n  const offset = (page - 1) * limit;\n\n  const [countResult, usersResult] = await c.env.DB.batch([\n    c.env.DB.prepare('SELECT COUNT(*) as total FROM users'),\n    c.env.DB.prepare('SELECT * FROM users ORDER BY created_at DESC LIMIT ? OFFSET ?')\n      .bind(limit, offset)\n  ]);\n\n  const total = countResult.results[0].total as number;\n  const users = usersResult.results;\n\n  return c.json({\n    users,\n    pagination: {\n      page,\n      limit,\n      total,\n      pages: Math.ceil(total \u002F limit)\n    }\n  });\n});\n```\n\n#### Joins\n\n```typescript\nconst { results } = await env.DB.prepare(`\n  SELECT\n    posts.*,\n    users.username as author_name,\n    users.email as author_email\n  FROM posts\n  INNER JOIN users ON posts.user_id = users.user_id\n  WHERE posts.published = ?\n  ORDER BY posts.created_at DESC\n  LIMIT ?\n`)\n.bind(1, 10)\n.all();\n```\n\n#### Transactions (Batch Pattern)\n\nD1 doesn't support multi-statement transactions, but batch() provides sequential execution:\n\n```typescript\n\u002F\u002F Transfer credits between users (pseudo-transaction)\nawait env.DB.batch([\n  env.DB.prepare('UPDATE users SET credits = credits - ? WHERE user_id = ?')\n    .bind(amount, fromUserId),\n  env.DB.prepare('UPDATE users SET credits = credits + ? WHERE user_id = ?')\n    .bind(amount, toUserId),\n  env.DB.prepare('INSERT INTO transactions (from_user, to_user, amount) VALUES (?, ?, ?)')\n    .bind(fromUserId, toUserId, amount)\n]);\n```\n\n**Note**: If any statement fails, the batch stops. This provides some transaction-like behavior.\n\n---\n\n## Error Handling\n\n### Error Types\n\n```typescript\ntry {\n  const result = await env.DB.prepare('SELECT * FROM users WHERE user_id = ?')\n    .bind(userId)\n    .first();\n} catch (error: any) {\n  \u002F\u002F D1 errors have a message property\n  const errorMessage = error.message;\n\n  if (errorMessage.includes('D1_ERROR')) {\n    \u002F\u002F D1-specific error\n  } else if (errorMessage.includes('D1_EXEC_ERROR')) {\n    \u002F\u002F SQL syntax error\n  } else if (errorMessage.includes('D1_TYPE_ERROR')) {\n    \u002F\u002F Type mismatch (e.g., undefined instead of null)\n  } else if (errorMessage.includes('D1_COLUMN_NOTFOUND')) {\n    \u002F\u002F Column doesn't exist\n  }\n\n  console.error('Database error:', errorMessage);\n  return c.json({ error: 'Database operation failed' }, 500);\n}\n```\n\n### Common Errors and Fixes\n\n#### \"Statement too long\"\n\n```typescript\n\u002F\u002F ❌ DON'T: Single massive INSERT\nawait env.DB.exec(`\n  INSERT INTO users (email) VALUES\n    ('user1@example.com'),\n    ('user2@example.com'),\n    ... \u002F\u002F 1000 more rows\n`);\n\n\u002F\u002F ✅ DO: Break into batches\nconst batchSize = 100;\nfor (let i = 0; i \u003C users.length; i += batchSize) {\n  const batch = users.slice(i, i + batchSize);\n  const inserts = batch.map(u =>\n    env.DB.prepare('INSERT INTO users (email) VALUES (?)').bind(u.email)\n  );\n  await env.DB.batch(inserts);\n}\n```\n\n#### \"Too many requests queued\"\n\n```typescript\n\u002F\u002F ❌ DON'T: Fire off many individual queries\nfor (const user of users) {\n  await env.DB.prepare('INSERT INTO users (email) VALUES (?)').bind(user.email).run();\n}\n\n\u002F\u002F ✅ DO: Use batch()\nconst inserts = users.map(u =>\n  env.DB.prepare('INSERT INTO users (email) VALUES (?)').bind(u.email)\n);\nawait env.DB.batch(inserts);\n```\n\n#### \"D1_TYPE_ERROR\" (undefined vs null)\n\n```typescript\n\u002F\u002F ❌ DON'T: Use undefined\nawait env.DB.prepare('INSERT INTO users (email, bio) VALUES (?, ?)')\n  .bind(email, undefined);  \u002F\u002F ❌ D1 doesn't support undefined\n\n\u002F\u002F ✅ DO: Use null for optional values\nawait env.DB.prepare('INSERT INTO users (email, bio) VALUES (?, ?)')\n  .bind(email, bio || null);\n```\n\n### Retry Logic\n\n```typescript\nasync function queryWithRetry\u003CT>(\n  queryFn: () => Promise\u003CT>,\n  maxRetries = 3\n): Promise\u003CT> {\n  for (let attempt = 0; attempt \u003C maxRetries; attempt++) {\n    try {\n      return await queryFn();\n    } catch (error: any) {\n      const message = error.message;\n\n      \u002F\u002F Retry on transient errors\n      const isRetryable =\n        message.includes('Network connection lost') ||\n        message.includes('storage caused object to be reset') ||\n        message.includes('reset because its code was updated');\n\n      if (!isRetryable || attempt === maxRetries - 1) {\n        throw error;\n      }\n\n      \u002F\u002F Exponential backoff\n      const delay = Math.min(1000 * Math.pow(2, attempt), 5000);\n      await new Promise(resolve => setTimeout(resolve, delay));\n    }\n  }\n\n  throw new Error('Retry logic failed');\n}\n\n\u002F\u002F Usage\nconst user = await queryWithRetry(() =>\n  env.DB.prepare('SELECT * FROM users WHERE user_id = ?')\n    .bind(userId)\n    .first()\n);\n```\n\n---\n\n## Performance Optimization\n\n### Indexes\n\nIndexes dramatically improve query performance for filtered columns.\n\n#### When to Create Indexes\n\n```typescript\n\u002F\u002F ✅ Index columns used in WHERE clauses\nCREATE INDEX idx_users_email ON users(email);\n\n\u002F\u002F ✅ Index foreign keys\nCREATE INDEX idx_posts_user_id ON posts(user_id);\n\n\u002F\u002F ✅ Index columns used for sorting\nCREATE INDEX idx_posts_created_at ON posts(created_at DESC);\n\n\u002F\u002F ✅ Multi-column indexes for complex queries\nCREATE INDEX idx_posts_user_published ON posts(user_id, published);\n```\n\n#### Test Index Usage\n\n```sql\n-- Check if index is being used\nEXPLAIN QUERY PLAN SELECT * FROM users WHERE email = 'user@example.com';\n\n-- Should see: SEARCH users USING INDEX idx_users_email\n```\n\n#### Partial Indexes\n\n```sql\n-- Index only non-deleted records\nCREATE INDEX idx_users_active ON users(email) WHERE deleted = 0;\n\n-- Index only published posts\nCREATE INDEX idx_posts_published ON posts(created_at DESC) WHERE published = 1;\n```\n\n### PRAGMA optimize\n\nRun after creating indexes or making schema changes:\n\n```sql\n-- In your migration file\nCREATE INDEX idx_users_email ON users(email);\nPRAGMA optimize;\n```\n\nOr from Worker:\n\n```typescript\nawait env.DB.exec('PRAGMA optimize');\n```\n\n### Query Optimization Tips\n\n```typescript\n\u002F\u002F ✅ Use specific columns instead of SELECT *\nconst users = await env.DB.prepare(\n  'SELECT user_id, email, username FROM users'\n).all();\n\n\u002F\u002F ✅ Use LIMIT to prevent scanning entire table\nconst latest = await env.DB.prepare(\n  'SELECT * FROM posts ORDER BY created_at DESC LIMIT 10'\n).all();\n\n\u002F\u002F ✅ Use indexes for WHERE conditions\n\u002F\u002F Create index first: CREATE INDEX idx_users_email ON users(email)\nconst user = await env.DB.prepare('SELECT * FROM users WHERE email = ?')\n  .bind(email)\n  .first();\n\n\u002F\u002F ❌ Avoid functions in WHERE (can't use indexes)\n\u002F\u002F Bad: WHERE LOWER(email) = 'user@example.com'\n\u002F\u002F Good: WHERE email = 'user@example.com' (store email lowercase)\n```\n\n---\n\n## Local Development\n\n### Local vs Remote Databases\n\n```bash\n# Create local database (automatic on first --local command)\nnpx wrangler d1 migrations apply my-database --local\n\n# Query local database\nnpx wrangler d1 execute my-database --local --command \"SELECT * FROM users\"\n\n# Query remote database\nnpx wrangler d1 execute my-database --remote --command \"SELECT * FROM users\"\n```\n\n### Local Database Location\n\nLocal D1 databases are stored in:\n```\n.wrangler\u002Fstate\u002Fv3\u002Fd1\u002Fminiflare-D1DatabaseObject\u002F\u003Cdatabase_id>.sqlite\n```\n\n### Seeding Local Database\n\n```bash\n# Create seed file\ncat > seed.sql \u003C\u003C 'EOF'\nINSERT INTO users (email, username, created_at) VALUES\n  ('alice@example.com', 'alice', 1698000000),\n  ('bob@example.com', 'bob', 1698000060);\nEOF\n\n# Apply seed\nnpx wrangler d1 execute my-database --local --file=seed.sql\n```\n\n---\n\n## Drizzle ORM (Optional)\n\nWhile D1 works great with raw SQL, some developers prefer ORMs. Drizzle ORM supports D1:\n\n```bash\nnpm install drizzle-orm\nnpm install -D drizzle-kit\n```\n\n**Note**: Drizzle adds complexity and another layer to learn. For most D1 use cases, **raw SQL with wrangler is simpler and more direct**. Only consider Drizzle if you:\n- Prefer TypeScript schema definitions over SQL\n- Want auto-complete for queries\n- Are building a very large application with complex schemas\n\n**Official Drizzle D1 docs**: https:\u002F\u002Form.drizzle.team\u002Fdocs\u002Fget-started-sqlite#cloudflare-d1\n\n---\n\n## Best Practices Summary\n\n### ✅ Always Do:\n\n1. **Use prepared statements** with `.bind()` for user input\n2. **Use `.batch()`** for multiple queries (reduces latency)\n3. **Create indexes** on frequently queried columns\n4. **Run `PRAGMA optimize`** after schema changes\n5. **Use `IF NOT EXISTS`** in migrations for idempotency\n6. **Test migrations locally** before applying to production\n7. **Handle errors gracefully** with try\u002Fcatch\n8. **Use `null`** instead of `undefined` for optional values\n9. **Validate input** before binding to queries\n10. **Check `meta.rows_written`** after UPDATE\u002FDELETE\n\n### ❌ Never Do:\n\n1. **Never use `.exec()`** with user input (SQL injection risk)\n2. **Never hardcode `database_id`** in public repos\n3. **Never use `undefined`** in bind parameters (causes D1_TYPE_ERROR)\n4. **Never fire individual queries in loops** (use batch instead)\n5. **Never forget `LIMIT`** on potentially large result sets\n6. **Never use `SELECT *`** in production (specify columns)\n7. **Never include `BEGIN TRANSACTION`** in migration files\n8. **Never modify applied migrations** (create new ones)\n9. **Never skip error handling** on database operations\n10. **Never assume queries succeed** (always check results)\n\n---\n\n## Known Issues Prevented\n\n| Issue | Description | How to Avoid |\n|-------|-------------|--------------|\n| **Statement too long** | Large INSERT statements exceed D1 limits | Break into batches of 100-250 rows |\n| **Transaction conflicts** | `BEGIN TRANSACTION` in migration files | Remove BEGIN\u002FCOMMIT (D1 handles this) |\n| **Foreign key violations** | Schema changes break foreign key constraints | Use `PRAGMA defer_foreign_keys = true` |\n| **Rate limiting \u002F queue overload** | Too many individual queries | Use `batch()` instead of loops |\n| **Memory limit exceeded** | Query loads too much data into memory | Add LIMIT, paginate results, shard queries |\n| **Type mismatch errors** | Using `undefined` instead of `null` | Always use `null` for optional values |\n\n---\n\n## Wrangler Commands Reference\n\n```bash\n# Database management\nwrangler d1 create \u003CDATABASE_NAME>\nwrangler d1 list\nwrangler d1 delete \u003CDATABASE_NAME>\nwrangler d1 info \u003CDATABASE_NAME>\n\n# Migrations\nwrangler d1 migrations create \u003CDATABASE_NAME> \u003CMIGRATION_NAME>\nwrangler d1 migrations list \u003CDATABASE_NAME> --local|--remote\nwrangler d1 migrations apply \u003CDATABASE_NAME> --local|--remote\n\n# Execute queries\nwrangler d1 execute \u003CDATABASE_NAME> --local|--remote --command \"SELECT * FROM users\"\nwrangler d1 execute \u003CDATABASE_NAME> --local|--remote --file=.\u002Fquery.sql\n\n# Time Travel (view historical data)\nwrangler d1 time-travel info \u003CDATABASE_NAME> --timestamp \"2025-10-20\"\nwrangler d1 time-travel restore \u003CDATABASE_NAME> --timestamp \"2025-10-20\"\n```\n\n---\n\n## Official Documentation\n\n- **D1 Overview**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fd1\u002F\n- **Get Started**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fd1\u002Fget-started\u002F\n- **Migrations**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fd1\u002Freference\u002Fmigrations\u002F\n- **Workers API**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fd1\u002Fworker-api\u002F\n- **Best Practices**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fd1\u002Fbest-practices\u002F\n- **Wrangler Commands**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fworkers\u002Fwrangler\u002Fcommands\u002F#d1\n\n---\n\n**Ready to build with D1!** 🚀\n","# Cloudflare D1 Database\n\n**Status**: Production Ready ✅\n**Last Updated**: 2025-10-21\n**Dependencies**: cloudflare-worker-base (for Worker setup)\n**Latest Versions**: wrangler@4.43.0, @cloudflare\u002Fworkers-types@4.20251014.0\n\n---\n\n## Quick Start (5 Minutes)\n\n### 1. Create D1 Database\n\n```bash\n# Create a new D1 database\nnpx wrangler d1 create my-database\n\n# Output includes database_id - save this!\n# ✅ Successfully created DB 'my-database'\n#\n# [[d1_databases]]\n# binding = \"DB\"\n# database_name = \"my-database\"\n# database_id = \"\u003CUUID>\"\n```\n\n### 2. Configure Bindings\n\nAdd to your `wrangler.jsonc`:\n\n```jsonc\n{\n  \"name\": \"my-worker\",\n  \"main\": \"src\u002Findex.ts\",\n  \"compatibility_date\": \"2025-10-11\",\n  \"d1_databases\": [\n    {\n      \"binding\": \"DB\",                    \u002F\u002F Available as env.DB in your Worker\n      \"database_name\": \"my-database\",      \u002F\u002F Name from wrangler d1 create\n      \"database_id\": \"\u003CUUID>\",             \u002F\u002F ID from wrangler d1 create\n      \"preview_database_id\": \"local-db\"    \u002F\u002F For local development\n    }\n  ]\n}\n```\n\n**CRITICAL:**\n- `binding` is how you access the database in code (`env.DB`)\n- `database_id` is the production database UUID\n- `preview_database_id` is for local dev (can be any string)\n- **Never commit real `database_id` values to public repos** - use environment variables or secrets\n\n### 3. Create Your First Migration\n\n```bash\n# Create migration file\nnpx wrangler d1 migrations create my-database create_users_table\n\n# This creates: migrations\u002F0001_create_users_table.sql\n```\n\nEdit the migration file:\n\n```sql\n-- migrations\u002F0001_create_users_table.sql\nDROP TABLE IF EXISTS users;\nCREATE TABLE IF NOT EXISTS users (\n  user_id INTEGER PRIMARY KEY AUTOINCREMENT,\n  email TEXT NOT NULL UNIQUE,\n  username TEXT NOT NULL,\n  created_at INTEGER NOT NULL,\n  updated_at INTEGER\n);\n\n-- Create index for common queries\nCREATE INDEX IF NOT EXISTS idx_users_email ON users(email);\n\n-- Optimize database\nPRAGMA optimize;\n```\n\n### 4. Apply Migration\n\n```bash\n# Apply locally first (for testing)\nnpx wrangler d1 migrations apply my-database --local\n\n# Apply to production when ready\nnpx wrangler d1 migrations apply my-database --remote\n```\n\n### 5. Query from Your Worker\n\n```typescript\n\u002F\u002F src\u002Findex.ts\nimport { Hono } from 'hono';\n\ntype Bindings = {\n  DB: D1Database;\n};\n\nconst app = new Hono\u003C{ Bindings: Bindings }>();\n\napp.get('\u002Fapi\u002Fusers\u002F:email', async (c) => {\n  const email = c.req.param('email');\n\n  try {\n    \u002F\u002F ALWAYS use prepared statements with bind()\n    const result = await c.env.DB.prepare(\n      'SELECT * FROM users WHERE email = ?'\n    )\n    .bind(email)\n    .first();\n\n    if (!result) {\n      return c.json({ error: 'User not found' }, 404);\n    }\n\n    return c.json(result);\n  } catch (error: any) {\n    console.error('D1 Error:', error.message);\n    return c.json({ error: 'Database error' }, 500);\n  }\n});\n\nexport default app;\n```\n\n---\n\n## D1 Migrations System\n\n### Migration Workflow\n\n```bash\n# 1. Create migration\nnpx wrangler d1 migrations create \u003CDATABASE_NAME> \u003CMIGRATION_NAME>\n\n# 2. List unapplied migrations\nnpx wrangler d1 migrations list \u003CDATABASE_NAME> --local\nnpx wrangler d1 migrations list \u003CDATABASE_NAME> --remote\n\n# 3. Apply migrations\nnpx wrangler d1 migrations apply \u003CDATABASE_NAME> --local   # Test locally\nnpx wrangler d1 migrations apply \u003CDATABASE_NAME> --remote  # Deploy to production\n```\n\n### Migration File Naming\n\nMigrations are automatically versioned:\n\n```\nmigrations\u002F\n├── 0000_initial_schema.sql\n├── 0001_add_users_table.sql\n├── 0002_add_posts_table.sql\n└── 0003_add_indexes.sql\n```\n\n**Rules:**\n- Files are executed in sequential order\n- Each migration runs once (tracked in `d1_migrations` table)\n- Failed migrations roll back (transactional)\n- Can't modify or delete applied migrations\n\n### Custom Migration Configuration\n\n```jsonc\n{\n  \"d1_databases\": [\n    {\n      \"binding\": \"DB\",\n      \"database_name\": \"my-database\",\n      \"database_id\": \"\u003CUUID>\",\n      \"migrations_dir\": \"db\u002Fmigrations\",        \u002F\u002F Custom directory (default: migrations\u002F)\n      \"migrations_table\": \"schema_migrations\"   \u002F\u002F Custom tracking table (default: d1_migrations)\n    }\n  ]\n}\n```\n\n### Migration Best Practices\n\n#### ✅ Always Do:\n\n```sql\n-- Use IF NOT EXISTS to make migrations idempotent\nCREATE TABLE IF NOT EXISTS users (...);\nCREATE INDEX IF NOT EXISTS idx_users_email ON users(email);\n\n-- Run PRAGMA optimize after schema changes\nPRAGMA optimize;\n\n-- Use transactions for data migrations\nBEGIN TRANSACTION;\nUPDATE users SET updated_at = unixepoch() WHERE updated_at IS NULL;\nCOMMIT;\n```\n\n#### ❌ Never Do:\n\n```sql\n-- DON'T include BEGIN TRANSACTION at start (D1 handles this)\nBEGIN TRANSACTION;  -- ❌ Remove this\n\n-- DON'T use MySQL\u002FPostgreSQL syntax\nALTER TABLE users MODIFY COLUMN email VARCHAR(255);  -- ❌ Not SQLite\n\n-- DON'T create tables without IF NOT EXISTS\nCREATE TABLE users (...);  -- ❌ Fails if table exists\n```\n\n### Handling Foreign Keys in Migrations\n\n```sql\n-- Temporarily disable foreign key checks during schema changes\nPRAGMA defer_foreign_keys = true;\n\n-- Make schema changes that would violate foreign keys\nALTER TABLE posts DROP COLUMN author_id;\nALTER TABLE posts ADD COLUMN user_id INTEGER REFERENCES users(user_id);\n\n-- Foreign keys re-enabled automatically at end of migration\n```\n\n---\n\n## D1 Workers API\n\n### Type Definitions\n\n```typescript\n\u002F\u002F Add to env.d.ts or worker-configuration.d.ts\ninterface Env {\n  DB: D1Database;\n  \u002F\u002F ... other bindings\n}\n\n\u002F\u002F For Hono\ntype Bindings = {\n  DB: D1Database;\n};\n\nconst app = new Hono\u003C{ Bindings: Bindings }>();\n```\n\n### prepare() - Prepared Statements (PRIMARY METHOD)\n\n**Always use prepared statements for queries with user input.**\n\n```typescript\n\u002F\u002F Basic prepared statement\nconst stmt = env.DB.prepare('SELECT * FROM users WHERE user_id = ?');\nconst bound = stmt.bind(userId);\nconst result = await bound.first();\n\n\u002F\u002F Chained (most common pattern)\nconst user = await env.DB.prepare('SELECT * FROM users WHERE email = ?')\n  .bind(email)\n  .first();\n```\n\n**Why use prepare():**\n- ✅ Prevents SQL injection\n- ✅ Can be reused with different parameters\n- ✅ Better performance (query plan caching)\n- ✅ Type-safe with TypeScript\n\n### Query Result Methods\n\n#### .all() - Get All Rows\n\n```typescript\nconst { results, meta } = await env.DB.prepare(\n  'SELECT * FROM users WHERE created_at > ?'\n)\n.bind(timestamp)\n.all();\n\nconsole.log(results);  \u002F\u002F Array of rows\nconsole.log(meta);     \u002F\u002F { duration, rows_read, rows_written }\n```\n\n#### .first() - Get First Row\n\n```typescript\n\u002F\u002F Returns first row or null\nconst user = await env.DB.prepare('SELECT * FROM users WHERE email = ?')\n  .bind('user@example.com')\n  .first();\n\nif (!user) {\n  return c.json({ error: 'Not found' }, 404);\n}\n```\n\n#### .first(column) - Get Single Column Value\n\n```typescript\n\u002F\u002F Returns the value of a specific column from first row\nconst count = await env.DB.prepare('SELECT COUNT(*) as total FROM users')\n  .first('total');\n\nconsole.log(count);  \u002F\u002F 42 (just the number, not an object)\n```\n\n#### .run() - Execute Without Results\n\n```typescript\n\u002F\u002F For INSERT, UPDATE, DELETE\nconst { success, meta } = await env.DB.prepare(\n  'INSERT INTO users (email, username, created_at) VALUES (?, ?, ?)'\n)\n.bind(email, username, Date.now())\n.run();\n\nconsole.log(meta);  \u002F\u002F { duration, rows_read, rows_written, last_row_id }\n```\n\n### batch() - Execute Multiple Queries\n\n**CRITICAL FOR PERFORMANCE**: Use batch() to reduce latency.\n\n```typescript\n\u002F\u002F Prepare multiple statements\nconst stmt1 = env.DB.prepare('SELECT * FROM users WHERE user_id = ?').bind(1);\nconst stmt2 = env.DB.prepare('SELECT * FROM users WHERE user_id = ?').bind(2);\nconst stmt3 = env.DB.prepare('SELECT * FROM posts WHERE user_id = ?').bind(1);\n\n\u002F\u002F Execute all in one round trip\nconst results = await env.DB.batch([stmt1, stmt2, stmt3]);\n\nconsole.log(results[0].results);  \u002F\u002F Users query 1\nconsole.log(results[1].results);  \u002F\u002F Users query 2\nconsole.log(results[2].results);  \u002F\u002F Posts query\n```\n\n**Batch Behavior:**\n- Executes sequentially (in order)\n- Each statement commits individually (auto-commit mode)\n- If one fails, remaining statements don't execute\n- Much faster than individual queries (single network round trip)\n\n**Batch Use Cases:**\n```typescript\n\u002F\u002F ✅ Insert multiple rows efficiently\nconst inserts = users.map(user =>\n  env.DB.prepare('INSERT INTO users (email, username) VALUES (?, ?)')\n    .bind(user.email, user.username)\n);\nawait env.DB.batch(inserts);\n\n\u002F\u002F ✅ Fetch related data in parallel\nconst [user, posts, comments] = await env.DB.batch([\n  env.DB.prepare('SELECT * FROM users WHERE user_id = ?').bind(userId),\n  env.DB.prepare('SELECT * FROM posts WHERE user_id = ?').bind(userId),\n  env.DB.prepare('SELECT * FROM comments WHERE user_id = ?').bind(userId)\n]);\n```\n\n### exec() - Execute Raw SQL (AVOID IN PRODUCTION)\n\n```typescript\n\u002F\u002F Only for migrations, maintenance, and one-off tasks\nconst result = await env.DB.exec(`\n  SELECT * FROM users;\n  SELECT * FROM posts;\n`);\n\nconsole.log(result);  \u002F\u002F { count: 2, duration: 5 }\n```\n\n**NEVER use exec() for:**\n- ❌ Queries with user input (SQL injection risk)\n- ❌ Production queries (poor performance)\n- ❌ Queries that need results (exec doesn't return data)\n\n**ONLY use exec() for:**\n- ✅ Running migration SQL files locally\n- ✅ One-off maintenance tasks\n- ✅ Database initialization scripts\n\n---\n\n## Query Patterns\n\n### Basic CRUD Operations\n\n#### Create (INSERT)\n\n```typescript\n\u002F\u002F Single insert\nconst { meta } = await env.DB.prepare(\n  'INSERT INTO users (email, username, created_at) VALUES (?, ?, ?)'\n)\n.bind(email, username, Date.now())\n.run();\n\nconst newUserId = meta.last_row_id;\n\n\u002F\u002F Bulk insert with batch()\nconst users = [\n  { email: 'user1@example.com', username: 'user1' },\n  { email: 'user2@example.com', username: 'user2' }\n];\n\nconst inserts = users.map(u =>\n  env.DB.prepare('INSERT INTO users (email, username, created_at) VALUES (?, ?, ?)')\n    .bind(u.email, u.username, Date.now())\n);\n\nawait env.DB.batch(inserts);\n```\n\n#### Read (SELECT)\n\n```typescript\n\u002F\u002F Single row\nconst user = await env.DB.prepare('SELECT * FROM users WHERE user_id = ?')\n  .bind(userId)\n  .first();\n\n\u002F\u002F Multiple rows\nconst { results } = await env.DB.prepare(\n  'SELECT * FROM users WHERE created_at > ? ORDER BY created_at DESC LIMIT ?'\n)\n.bind(timestamp, 10)\n.all();\n\n\u002F\u002F Count\nconst count = await env.DB.prepare('SELECT COUNT(*) as total FROM users')\n  .first('total');\n\n\u002F\u002F Exists check\nconst exists = await env.DB.prepare('SELECT 1 FROM users WHERE email = ? LIMIT 1')\n  .bind(email)\n  .first();\n\nif (exists) {\n  \u002F\u002F Email already registered\n}\n```\n\n#### Update (UPDATE)\n\n```typescript\nconst { meta } = await env.DB.prepare(\n  'UPDATE users SET username = ?, updated_at = ? WHERE user_id = ?'\n)\n.bind(newUsername, Date.now(), userId)\n.run();\n\nconst rowsAffected = meta.rows_written;\n\nif (rowsAffected === 0) {\n  \u002F\u002F User not found\n}\n```\n\n#### Delete (DELETE)\n\n```typescript\nconst { meta } = await env.DB.prepare('DELETE FROM users WHERE user_id = ?')\n  .bind(userId)\n  .run();\n\nconst rowsDeleted = meta.rows_written;\n```\n\n### Advanced Queries\n\n#### Pagination\n\n```typescript\napp.get('\u002Fapi\u002Fusers', async (c) => {\n  const page = parseInt(c.req.query('page') || '1');\n  const limit = parseInt(c.req.query('limit') || '20');\n  const offset = (page - 1) * limit;\n\n  const [countResult, usersResult] = await c.env.DB.batch([\n    c.env.DB.prepare('SELECT COUNT(*) as total FROM users'),\n    c.env.DB.prepare('SELECT * FROM users ORDER BY created_at DESC LIMIT ? OFFSET ?')\n      .bind(limit, offset)\n  ]);\n\n  const total = countResult.results[0].total as number;\n  const users = usersResult.results;\n\n  return c.json({\n    users,\n    pagination: {\n      page,\n      limit,\n      total,\n      pages: Math.ceil(total \u002F limit)\n    }\n  });\n});\n```\n\n#### Joins\n\n```typescript\nconst { results } = await env.DB.prepare(`\n  SELECT\n    posts.*,\n    users.username as author_name,\n    users.email as author_email\n  FROM posts\n  INNER JOIN users ON posts.user_id = users.user_id\n  WHERE posts.published = ?\n  ORDER BY posts.created_at DESC\n  LIMIT ?\n`)\n.bind(1, 10)\n.all();\n```\n\n#### Transactions (Batch Pattern)\n\nD1 doesn't support multi-statement transactions, but batch() provides sequential execution:\n\n```typescript\n\u002F\u002F Transfer credits between users (pseudo-transaction)\nawait env.DB.batch([\n  env.DB.prepare('UPDATE users SET credits = credits - ? WHERE user_id = ?')\n    .bind(amount, fromUserId),\n  env.DB.prepare('UPDATE users SET credits = credits + ? WHERE user_id = ?')\n    .bind(amount, toUserId),\n  env.DB.prepare('INSERT INTO transactions (from_user, to_user, amount) VALUES (?, ?, ?)')\n    .bind(fromUserId, toUserId, amount)\n]);\n```\n\n**Note**: If any statement fails, the batch stops. This provides some transaction-like behavior.\n\n---\n\n## Error Handling\n\n### Error Types\n\n```typescript\ntry {\n  const result = await env.DB.prepare('SELECT * FROM users WHERE user_id = ?')\n    .bind(userId)\n    .first();\n} catch (error: any) {\n  \u002F\u002F D1 errors have a message property\n  const errorMessage = error.message;\n\n  if (errorMessage.includes('D1_ERROR')) {\n    \u002F\u002F D1-specific error\n  } else if (errorMessage.includes('D1_EXEC_ERROR')) {\n    \u002F\u002F SQL syntax error\n  } else if (errorMessage.includes('D1_TYPE_ERROR')) {\n    \u002F\u002F Type mismatch (e.g., undefined instead of null)\n  } else if (errorMessage.includes('D1_COLUMN_NOTFOUND')) {\n    \u002F\u002F Column doesn't exist\n  }\n\n  console.error('Database error:', errorMessage);\n  return c.json({ error: 'Database operation failed' }, 500);\n}\n```\n\n### Common Errors and Fixes\n\n#### \"Statement too long\"\n\n```typescript\n\u002F\u002F ❌ DON'T: Single massive INSERT\nawait env.DB.exec(`\n  INSERT INTO users (email) VALUES\n    ('user1@example.com'),\n    ('user2@example.com'),\n    ... \u002F\u002F 1000 more rows\n`);\n\n\u002F\u002F ✅ DO: Break into batches\nconst batchSize = 100;\nfor (let i = 0; i \u003C users.length; i += batchSize) {\n  const batch = users.slice(i, i + batchSize);\n  const inserts = batch.map(u =>\n    env.DB.prepare('INSERT INTO users (email) VALUES (?)').bind(u.email)\n  );\n  await env.DB.batch(inserts);\n}\n```\n\n#### \"Too many requests queued\"\n\n```typescript\n\u002F\u002F ❌ DON'T: Fire off many individual queries\nfor (const user of users) {\n  await env.DB.prepare('INSERT INTO users (email) VALUES (?)').bind(user.email).run();\n}\n\n\u002F\u002F ✅ DO: Use batch()\nconst inserts = users.map(u =>\n  env.DB.prepare('INSERT INTO users (email) VALUES (?)').bind(u.email)\n);\nawait env.DB.batch(inserts);\n```\n\n#### \"D1_TYPE_ERROR\" (undefined vs null)\n\n```typescript\n\u002F\u002F ❌ DON'T: Use undefined\nawait env.DB.prepare('INSERT INTO users (email, bio) VALUES (?, ?)')\n  .bind(email, undefined);  \u002F\u002F ❌ D1 doesn't support undefined\n\n\u002F\u002F ✅ DO: Use null for optional values\nawait env.DB.prepare('INSERT INTO users (email, bio) VALUES (?, ?)')\n  .bind(email, bio || null);\n```\n\n### Retry Logic\n\n```typescript\nasync function queryWithRetry\u003CT>(\n  queryFn: () => Promise\u003CT>,\n  maxRetries = 3\n): Promise\u003CT> {\n  for (let attempt = 0; attempt \u003C maxRetries; attempt++) {\n    try {\n      return await queryFn();\n    } catch (error: any) {\n      const message = error.message;\n\n      \u002F\u002F Retry on transient errors\n      const isRetryable =\n        message.includes('Network connection lost') ||\n        message.includes('storage caused object to be reset') ||\n        message.includes('reset because its code was updated');\n\n      if (!isRetryable || attempt === maxRetries - 1) {\n        throw error;\n      }\n\n      \u002F\u002F Exponential backoff\n      const delay = Math.min(1000 * Math.pow(2, attempt), 5000);\n      await new Promise(resolve => setTimeout(resolve, delay));\n    }\n  }\n\n  throw new Error('Retry logic failed');\n}\n\n\u002F\u002F Usage\nconst user = await queryWithRetry(() =>\n  env.DB.prepare('SELECT * FROM users WHERE user_id = ?')\n    .bind(userId)\n    .first()\n);\n```\n\n---\n\n## Performance Optimization\n\n### Indexes\n\nIndexes dramatically improve query performance for filtered columns.\n\n#### When to Create Indexes\n\n```typescript\n\u002F\u002F ✅ Index columns used in WHERE clauses\nCREATE INDEX idx_users_email ON users(email);\n\n\u002F\u002F ✅ Index foreign keys\nCREATE INDEX idx_posts_user_id ON posts(user_id);\n\n\u002F\u002F ✅ Index columns used for sorting\nCREATE INDEX idx_posts_created_at ON posts(created_at DESC);\n\n\u002F\u002F ✅ Multi-column indexes for complex queries\nCREATE INDEX idx_posts_user_published ON posts(user_id, published);\n```\n\n#### Test Index Usage\n\n```sql\n-- Check if index is being used\nEXPLAIN QUERY PLAN SELECT * FROM users WHERE email = 'user@example.com';\n\n-- Should see: SEARCH users USING INDEX idx_users_email\n```\n\n#### Partial Indexes\n\n```sql\n-- Index only non-deleted records\nCREATE INDEX idx_users_active ON users(email) WHERE deleted = 0;\n\n-- Index only published posts\nCREATE INDEX idx_posts_published ON posts(created_at DESC) WHERE published = 1;\n```\n\n### PRAGMA optimize\n\nRun after creating indexes or making schema changes:\n\n```sql\n-- In your migration file\nCREATE INDEX idx_users_email ON users(email);\nPRAGMA optimize;\n```\n\nOr from Worker:\n\n```typescript\nawait env.DB.exec('PRAGMA optimize');\n```\n\n### Query Optimization Tips\n\n```typescript\n\u002F\u002F ✅ Use specific columns instead of SELECT *\nconst users = await env.DB.prepare(\n  'SELECT user_id, email, username FROM users'\n).all();\n\n\u002F\u002F ✅ Use LIMIT to prevent scanning entire table\nconst latest = await env.DB.prepare(\n  'SELECT * FROM posts ORDER BY created_at DESC LIMIT 10'\n).all();\n\n\u002F\u002F ✅ Use indexes for WHERE conditions\n\u002F\u002F Create index first: CREATE INDEX idx_users_email ON users(email)\nconst user = await env.DB.prepare('SELECT * FROM users WHERE email = ?')\n  .bind(email)\n  .first();\n\n\u002F\u002F ❌ Avoid functions in WHERE (can't use indexes)\n\u002F\u002F Bad: WHERE LOWER(email) = 'user@example.com'\n\u002F\u002F Good: WHERE email = 'user@example.com' (store email lowercase)\n```\n\n---\n\n## Local Development\n\n### Local vs Remote Databases\n\n```bash\n# Create local database (automatic on first --local command)\nnpx wrangler d1 migrations apply my-database --local\n\n# Query local database\nnpx wrangler d1 execute my-database --local --command \"SELECT * FROM users\"\n\n# Query remote database\nnpx wrangler d1 execute my-database --remote --command \"SELECT * FROM users\"\n```\n\n### Local Database Location\n\nLocal D1 databases are stored in:\n```\n.wrangler\u002Fstate\u002Fv3\u002Fd1\u002Fminiflare-D1DatabaseObject\u002F\u003Cdatabase_id>.sqlite\n```\n\n### Seeding Local Database\n\n```bash\n# Create seed file\ncat > seed.sql \u003C\u003C 'EOF'\nINSERT INTO users (email, username, created_at) VALUES\n  ('alice@example.com', 'alice', 1698000000),\n  ('bob@example.com', 'bob', 1698000060);\nEOF\n\n# Apply seed\nnpx wrangler d1 execute my-database --local --file=seed.sql\n```\n\n---\n\n## Drizzle ORM (Optional)\n\nWhile D1 works great with raw SQL, some developers prefer ORMs. Drizzle ORM supports D1:\n\n```bash\nnpm install drizzle-orm\nnpm install -D drizzle-kit\n```\n\n**Note**: Drizzle adds complexity and another layer to learn. For most D1 use cases, **raw SQL with wrangler is simpler and more direct**. Only consider Drizzle if you:\n- Prefer TypeScript schema definitions over SQL\n- Want auto-complete for queries\n- Are building a very large application with complex schemas\n\n**Official Drizzle D1 docs**: https:\u002F\u002Form.drizzle.team\u002Fdocs\u002Fget-started-sqlite#cloudflare-d1\n\n---\n\n## Best Practices Summary\n\n### ✅ Always Do:\n\n1. **Use prepared statements** with `.bind()` for user input\n2. **Use `.batch()`** for multiple queries (reduces latency)\n3. **Create indexes** on frequently queried columns\n4. **Run `PRAGMA optimize`** after schema changes\n5. **Use `IF NOT EXISTS`** in migrations for idempotency\n6. **Test migrations locally** before applying to production\n7. **Handle errors gracefully** with try\u002Fcatch\n8. **Use `null`** instead of `undefined` for optional values\n9. **Validate input** before binding to queries\n10. **Check `meta.rows_written`** after UPDATE\u002FDELETE\n\n### ❌ Never Do:\n\n1. **Never use `.exec()`** with user input (SQL injection risk)\n2. **Never hardcode `database_id`** in public repos\n3. **Never use `undefined`** in bind parameters (causes D1_TYPE_ERROR)\n4. **Never fire individual queries in loops** (use batch instead)\n5. **Never forget `LIMIT`** on potentially large result sets\n6. **Never use `SELECT *`** in production (specify columns)\n7. **Never include `BEGIN TRANSACTION`** in migration files\n8. **Never modify applied migrations** (create new ones)\n9. **Never skip error handling** on database operations\n10. **Never assume queries succeed** (always check results)\n\n---\n\n## Known Issues Prevented\n\n| Issue | Description | How to Avoid |\n|-------|-------------|--------------|\n| **Statement too long** | Large INSERT statements exceed D1 limits | Break into batches of 100-250 rows |\n| **Transaction conflicts** | `BEGIN TRANSACTION` in migration files | Remove BEGIN\u002FCOMMIT (D1 handles this) |\n| **Foreign key violations** | Schema changes break foreign key constraints | Use `PRAGMA defer_foreign_keys = true` |\n| **Rate limiting \u002F queue overload** | Too many individual queries | Use `batch()` instead of loops |\n| **Memory limit exceeded** | Query loads too much data into memory | Add LIMIT, paginate results, shard queries |\n| **Type mismatch errors** | Using `undefined` instead of `null` | Always use `null` for optional values |\n\n---\n\n## Wrangler Commands Reference\n\n```bash\n# Database management\nwrangler d1 create \u003CDATABASE_NAME>\nwrangler d1 list\nwrangler d1 delete \u003CDATABASE_NAME>\nwrangler d1 info \u003CDATABASE_NAME>\n\n# Migrations\nwrangler d1 migrations create \u003CDATABASE_NAME> \u003CMIGRATION_NAME>\nwrangler d1 migrations list \u003CDATABASE_NAME> --local|--remote\nwrangler d1 migrations apply \u003CDATABASE_NAME> --local|--remote\n\n# Execute queries\nwrangler d1 execute \u003CDATABASE_NAME> --local|--remote --command \"SELECT * FROM users\"\nwrangler d1 execute \u003CDATABASE_NAME> --local|--remote --file=.\u002Fquery.sql\n\n# Time Travel (view historical data)\nwrangler d1 time-travel info \u003CDATABASE_NAME> --timestamp \"2025-10-20\"\nwrangler d1 time-travel restore \u003CDATABASE_NAME> --timestamp \"2025-10-20\"\n```\n\n---\n\n## Official Documentation\n\n- **D1 Overview**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fd1\u002F\n- **Get Started**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fd1\u002Fget-started\u002F\n- **Migrations**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fd1\u002Freference\u002Fmigrations\u002F\n- **Workers API**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fd1\u002Fworker-api\u002F\n- **Best Practices**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fd1\u002Fbest-practices\u002F\n- **Wrangler Commands**: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fworkers\u002Fwrangler\u002Fcommands\u002F#d1\n\n---\n\n**Ready to build with D1!** 🚀\n",{"name":5,"license":14,"description":23},"Complete knowledge domain for Cloudflare D1 - serverless SQLite database on Cloudflare's edge network.\n\nUse when: creating D1 databases, writing SQL migrations, configuring D1 bindings, querying D1 from Workers,\nhandling SQLite data, building relational data models, or encountering \"D1_ERROR\", \"statement too long\",\n\"too many requests queued\", migration failures, or query performance issues.\n\nKeywords: d1, d1 database, cloudflare d1, wrangler d1, d1 migrations, d1 bindings, sqlite workers,\nserverless database, edge database, d1 queries, sql cloudflare, prepared statements, batch queries,\nd1 api, wrangler migrations, D1_ERROR, D1_EXEC_ERROR, statement too long, database bindings,\nsqlite cloudflare, sql workers api, d1 indexes, query optimization, d1 schema\n","main","6b73b29e4866f997b1eb47fe8d9631396265fc24",0,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn","2026-09-09 16:06:07",{"source":8,"skillName":5,"commands":31,"prompt":41,"zipAvailable":42},[32,35,38],{"tool":33,"command":34},"npx","npx skills add davidanthonyn\u002Fagent-skills --skill cloudflare-d1",{"tool":36,"command":37},"bunx","bunx skills add davidanthonyn\u002Fagent-skills --skill cloudflare-d1",{"tool":39,"command":40},"pnpm","pnpm dlx skills add davidanthonyn\u002Fagent-skills --skill cloudflare-d1","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fcloudflare-d1\u002FSKILL.md",true,[44,50,54],{"path":45,"resourceType":46,"resourceTypeDesc":47,"sizeBytes":48,"sourceHtmlUrl":49},"README.md","REFERENCE","参考文档",5344,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fcloudflare-d1\u002FREADME.md",{"path":51,"resourceType":46,"resourceTypeDesc":47,"sizeBytes":52,"sourceHtmlUrl":53},"SKILL.json",24574,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fcloudflare-d1\u002FSKILL.json",{"path":55,"resourceType":56,"resourceTypeDesc":57,"sizeBytes":58,"sourceHtmlUrl":59},"SKILL.md.backup","OTHER","其他",23269,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fcloudflare-d1\u002FSKILL.md.backup",[61,68,76,83,90,99],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M7AQNJDXVNVMN08N5BHBGZBF","zustand-state-management","Production-tested setup for Zustand state management in React applications with TypeScript.\nThis skill provides comprehensive patterns for building scalable, type-safe global state.\n\nUse when: setting up global state in React, migrating from Redux or Context API, implementing\nstate persistence with localStorage, configuring TypeScript with Zustand, using slices pattern\nfor modular stores, adding devtools middleware for debugging, handling Next.js SSR hydration,\nor encountering hydration errors, TypeScript inference issues, or persist middleware problems.\n\nPrevents 5 documented issues: Next.js hydration mismatches, TypeScript double parentheses\nsyntax errors, persist middleware export errors, infinite render loops, and slices pattern\ntype inference failures.\n\nKeywords: zustand, state management, React state, TypeScript state, persist middleware,\ndevtools, slices pattern, global state, React hooks, create store, useBoundStore,\nStateCreator, hydration error, text content mismatch, infinite render, localStorage,\nsessionStorage, immer middleware, shallow equality, selector pattern, zustand v5","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fzustand-state-management\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":72,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":18},"01M7AQN2DW9DTPM8BYNZSHQANC","zetic-mlange","Help users integrate the ZETIC Melange (MLange) on-device AI SDK into Android (Kotlin\u002FJava) and iOS (Swift) mobile apps. Use this skill whenever the user mentions Zetic, MLange, Melange, ZeticMLangeModel, ZeticMLangeLLMModel, ZeticMLangeHFModel, on-device NPU inference for mobile, or deploying ML models to Android\u002FiOS with NPU acceleration. Also trigger when users ask about running LLMs on-device with GGUF quantization, mobile NPU model deployment, or converting PyTorch\u002FONNX models for mobile inference. Covers general model inference, LLM inference (streaming token generation), and HuggingFace model loading.","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fzetic-mlange\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fzetic-mlange\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":18},"01M7AQMEK370FBPC75N2W8WA4W","youtube-downloader","Download videos, audio, playlists, and channels from YouTube and 1000+ websites using yt-dlp. Supports quality selection, format conversion, subtitle download, playlist filtering, metadata extraction, thumbnail download, and batch operations. Use when downloading YouTube videos in any quality (4K, 8K, HDR), extracting audio as MP3\u002FM4A\u002FFLAC, downloading entire playlists\u002Fchannels, getting subtitles in multiple languages, converting to specific formats, downloading live streams, archiving content, or batch processing multiple URLs. Optimized for reliability with automatic retries, rate limiting, and error handling.","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fyoutube-downloader\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":18},"01M7AQHKQ4VQB04NH6BG4SV9Q7","wordpress-plugin-core","This skill provides comprehensive knowledge for WordPress plugin development, covering core patterns, security best practices, database interactions, hooks\u002Ffilters, Settings API, custom post types, REST API, and AJAX. This skill should be used when creating WordPress plugins, troubleshooting security issues, implementing custom post types\u002Ftaxonomies, building admin interfaces, or working with the WordPress database.\n\nUse when: Creating new WordPress plugins, implementing nonces\u002Fsanitization\u002Fescaping, working with $wpdb and prepared statements, building Settings API pages, registering custom post types or taxonomies, implementing REST API endpoints, handling AJAX requests, debugging plugin activation\u002Fdeactivation issues, preventing SQL injection\u002FXSS\u002FCSRF vulnerabilities.\n\nKeywords: wordpress plugin development, wordpress security, wordpress hooks, wordpress filters, wordpress database, wpdb prepare, sanitize_text_field, esc_html, wp_nonce, custom post type, register_post_type, settings api, rest api, admin-ajax, wordpress sql injection, wordpress xss, wordpress csrf, plugin header, activation hook, deactivation hook, wordpress coding standards, wordpress plugin architecture","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fwordpress-plugin-core\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":94,"licenseFileUrl":95,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":18},"01M7AQH4JW8F2MJFS1C43TZ2TY","webapp-testing","Test local web applications with Playwright. Use when asked to verify frontend functionality, debug UI behavior, capture browser screenshots, or inspect browser logs.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fwebapp-testing\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":18},"01M7AQH0PWD6Z1NN66V15DT25M","web-performance-audit","Audit web performance using Chrome DevTools MCP. Use when asked to audit, profile, debug, or optimize page load performance, Lighthouse scores, or site speed.","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fweb-performance-audit\u002FSKILL.md",[],[]]