Interactive wizard to set up Cloudflare D1 database with database creation, Worker binding configuration, schema generation, and first migration. Use when user wants to create first D1 database or add D1 to existing Worker.
Sets up Cloudflare D1 database with interactive configuration, schema generation, and migration execution.
/plugin marketplace add secondsky/claude-skills/plugin install cloudflare-d1@claude-skillsInteractive wizard for complete D1 setup: create database, configure bindings, generate schema, and run first migration.
Check before starting:
wrangler whoami)Use AskUserQuestion to collect setup preferences.
Question 1: Database Name
databaseNameQuestion 2: Binding Name
bindingNameQuestion 3: Schema Source
hasSchema, schemaPath or tableNamesQuestion 4: Read Replication
enableReplicationQuestion 5: Data Jurisdiction (if user is on paid plan)
jurisdictionBuild and execute wrangler command based on user inputs:
# Base command
wrangler d1 create <databaseName>
# Add jurisdiction if specified and not GLOBAL
if [jurisdiction != "GLOBAL"]:
wrangler d1 create <databaseName> --jurisdiction <jurisdiction>
Execute:
# Example
wrangler d1 create my-app-db --jurisdiction EU
Capture Output:
Extract database_id from output (36-character UUID)
✅ Successfully created DB 'my-app-db' (abc123-def456-ghi789-...)
Store database_id for next steps.
Error Handling:
wrangler login firstCheck if wrangler.jsonc or wrangler.toml exists:
if [ -f "wrangler.jsonc" ]; then
CONFIG_FILE="wrangler.jsonc"
elif [ -f "wrangler.toml" ]; then
CONFIG_FILE="wrangler.toml"
else
# Ask user which format to create
CONFIG_FILE="wrangler.jsonc" # Default to JSON
fi
Add D1 Configuration:
If wrangler.jsonc:
Use Edit tool to add to d1_databases array (or create array if doesn't exist):
{
"d1_databases": [
{
"binding": "<bindingName>",
"database_name": "<databaseName>",
"database_id": "<databaseId>",
"preview_database_id": "local"
// Conditional fields:
// "replicate": { "enabled": true }, // if enableReplication
// "jurisdiction": "EU" // if jurisdiction != "GLOBAL"
}
]
}
If wrangler.toml:
[[d1_databases]]
binding = "<bindingName>"
database_name = "<databaseName>"
database_id = "<databaseId>"
Verify:
# Show configuration to user
cat wrangler.jsonc | grep -A 10 "d1_databases"
Error Handling:
Create migrations directory structure:
mkdir -p migrations
Confirm directory created:
ls -la migrations
If user has existing schema (hasSchema == true):
cp <schemaPath> migrations/0001_initial_schema.sql
If generating schema (hasSchema == false):
Ask for table details using AskUserQuestion:
tableNames (array)Generate basic schema for each table:
-- migrations/0001_initial_schema.sql
-- Example for "users" table
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
created_at INTEGER DEFAULT (unixepoch()),
updated_at INTEGER DEFAULT (unixepoch())
);
CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
-- Example for "posts" table
CREATE TABLE IF NOT EXISTS posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
title TEXT NOT NULL,
content TEXT,
created_at INTEGER DEFAULT (unixepoch()),
FOREIGN KEY (user_id) REFERENCES users(id)
);
CREATE INDEX IF NOT EXISTS idx_posts_user_id ON posts(user_id);
-- Optimize query planner
PRAGMA optimize;
Best Practices Applied:
IF NOT EXISTSWrite Schema File:
# Use Write tool to create migrations/0001_initial_schema.sql
Test Locally First (recommended):
wrangler d1 migrations apply <databaseName> --local
Check for errors. If successful, proceed to remote.
Apply to Remote:
wrangler d1 migrations apply <databaseName> --remote
Verify:
# List applied migrations
wrangler d1 migrations list <databaseName>
# Show schema
wrangler d1 execute <databaseName> --command ".schema"
Error Handling:
Ask User:
If yes:
# Install d1-orm (if not present)
bun add -d drizzle-orm drizzle-kit
# Note: Type generation varies by tooling
# Provide manual type example for now
Create basic TypeScript interface:
// src/types/db.ts
export interface User {
id: number;
email: string;
name: string;
created_at: number;
updated_at: number;
}
export interface Post {
id: number;
user_id: number;
title: string;
content: string | null;
created_at: number;
}
Success Message:
✅ D1 Database Setup Complete!
Database Configuration:
- Name: <databaseName> (<databaseId>)
- Binding: env.<bindingName>
- Replication: <Enabled/Disabled>
- Jurisdiction: <jurisdiction>
- Migrations Applied: 1
Next Steps:
1. Start querying your database:
```typescript
import { Hono } from 'hono';
type Bindings = {
<bindingName>: D1Database;
};
const app = new Hono<{ Bindings: Bindings }>();
app.get('/users', async (c) => {
const { results } = await c.env.<bindingName>.prepare(
'SELECT * FROM users LIMIT 10'
).all();
return c.json(results);
});
export default app;
Create additional migrations:
wrangler d1 migrations create <databaseName> add_posts_table
View database info:
wrangler d1 info <databaseName>
Monitor performance:
wrangler d1 insights <databaseName>
📚 Helpful Resources:
references/query-patterns.mdreferences/best-practices.mdreferences/limits.mdreferences/metrics-analytics.md💡 Tips:
---
## Error Handling
### Wrangler Not Authenticated
❌ Error: Not authenticated
Solution:
### Database Limit Reached
❌ Error: Account database limit reached (10 databases on free plan)
Solutions:
Check current databases: wrangler d1 list
### Migration Failed
❌ Error: Migration failed with SQL syntax error
Solution:
### Invalid Configuration
❌ Error: Invalid wrangler.jsonc syntax
Solution:
---
## Example Full Workflow
**User Input**:
- Database name: "my-app-db"
- Binding: "DB"
- Schema: Generate basic (tables: users, posts)
- Replication: Yes
- Jurisdiction: EU
**Executed Commands**:
```bash
# 1. Create database
wrangler d1 create my-app-db --jurisdiction EU
# Output: database_id = abc123-def456-...
# 2. Configure wrangler.jsonc (Edit tool)
# Added d1_databases configuration
# 3. Create migrations directory
mkdir -p migrations
# 4. Generate schema (Write tool)
# Created migrations/0001_initial_schema.sql with users and posts tables
# 5. Apply migration
wrangler d1 migrations apply my-app-db --local # Test first
wrangler d1 migrations apply my-app-db --remote # Then production
# 6. Verify
wrangler d1 migrations list my-app-db
wrangler d1 execute my-app-db --command ".schema"
Result:
✅ Setup complete!
- Database: my-app-db (EU jurisdiction)
- Binding: env.DB
- Tables: users (5 columns), posts (5 columns)
- Indexes: 2 created
- Replication: Enabled
This command provides interactive D1 setup through 8 guided steps:
Output: Fully configured D1 database ready for queries, with helpful next steps and code examples.
When to Use: First-time D1 setup or adding D1 to existing Worker project.