d1-database
Serverless SQLite database for structured data at the edge. Load when building relational schemas, running SQL queries, managing migrations, performing CRUD operations, using JOINs/aggregations, handling JSON columns, or enforcing foreign keys with D1.
What this skill does
# D1 Database
D1 is Cloudflare's native serverless SQL database built on SQLite. Run queries at the edge with automatic replication and low latency.
## FIRST: Create Database
```bash
# Create D1 database
wrangler d1 create my-database
# Output includes database_id - add to wrangler.jsonc
```
Add binding to `wrangler.jsonc`:
```jsonc
{
"d1_databases": [
{
"binding": "DB",
"database_name": "my-database",
"database_id": "<DATABASE_ID>",
"migrations_dir": "./migrations"
}
]
}
```
Generate TypeScript types:
```bash
wrangler types
```
## When to Use
| Use Case | Why D1 |
|----------|--------|
| Relational data | Structured tables with relationships |
| Complex queries | JOINs, aggregations, full SQL support |
| User data | Accounts, profiles, settings |
| Content management | Posts, comments, metadata |
| E-commerce | Products, orders, inventory |
| Analytics | Event tracking with SQL queries |
**When NOT to use D1:**
- Simple key-value data → Use Workers KV
- Large files/objects → Use R2
- Real-time coordination → Use Durable Objects
- High-frequency writes → Use Queues + D1
## Quick Reference
| Operation | Method | Returns |
|-----------|--------|---------|
| Execute query | `db.prepare(sql).bind(...).run()` | `{ success: boolean, meta: {...} }` |
| Get all rows | `db.prepare(sql).bind(...).all()` | `{ results: T[], success: boolean }` |
| Get first row | `db.prepare(sql).bind(...).first()` | `T \| null` |
| Get single value | `db.prepare(sql).bind(...).first('column')` | `any \| null` |
| Batch queries | `db.batch([stmt1, stmt2, ...])` | `Array<D1Result>` |
| Raw query | `db.prepare(sql).bind(...).raw()` | `Array<Array<any>>` |
## Minimal Example
```typescript
// src/index.ts
interface Env {
DB: D1Database;
}
export default {
async fetch(request: Request, env: Env) {
// Get all users
const { results } = await env.DB
.prepare("SELECT * FROM users WHERE active = ?")
.bind(true)
.all<{ id: number; name: string; email: string }>();
return Response.json(results);
}
} satisfies ExportedHandler<Env>;
```
## CRUD Operations
```typescript
interface Env {
DB: D1Database;
}
type User = {
id: number;
name: string;
email: string;
created_at: string;
};
type NewUser = Omit<User, "id" | "created_at">;
export default {
async fetch(request: Request, env: Env) {
const url = new URL(request.url);
const { pathname } = url;
// CREATE - Insert new user
if (pathname === "/users" && request.method === "POST") {
const user: NewUser = await request.json();
const result = await env.DB
.prepare("INSERT INTO users (name, email) VALUES (?, ?)")
.bind(user.name, user.email)
.run();
if (!result.success) {
return Response.json({ error: "Failed to create user" }, { status: 500 });
}
return Response.json({
id: result.meta.last_row_id,
message: "User created"
}, { status: 201 });
}
// READ - Get user by ID
if (pathname.startsWith("/users/") && request.method === "GET") {
const id = pathname.split("/")[2];
const user = await env.DB
.prepare("SELECT * FROM users WHERE id = ?")
.bind(id)
.first<User>();
if (!user) {
return Response.json({ error: "User not found" }, { status: 404 });
}
return Response.json(user);
}
// READ - Get all users (with pagination)
if (pathname === "/users" && request.method === "GET") {
const page = parseInt(url.searchParams.get("page") || "1");
const limit = parseInt(url.searchParams.get("limit") || "10");
const offset = (page - 1) * limit;
const { results } = await env.DB
.prepare("SELECT * FROM users ORDER BY created_at DESC LIMIT ? OFFSET ?")
.bind(limit, offset)
.all<User>();
return Response.json({
users: results,
page,
limit
});
}
// UPDATE - Update user
if (pathname.startsWith("/users/") && request.method === "PUT") {
const id = pathname.split("/")[2];
const updates: Partial<NewUser> = await request.json();
const result = await env.DB
.prepare("UPDATE users SET name = ?, email = ? WHERE id = ?")
.bind(updates.name, updates.email, id)
.run();
if (result.meta.changes === 0) {
return Response.json({ error: "User not found" }, { status: 404 });
}
return Response.json({ message: "User updated" });
}
// DELETE - Delete user
if (pathname.startsWith("/users/") && request.method === "DELETE") {
const id = pathname.split("/")[2];
const result = await env.DB
.prepare("DELETE FROM users WHERE id = ?")
.bind(id)
.run();
if (result.meta.changes === 0) {
return Response.json({ error: "User not found" }, { status: 404 });
}
return Response.json({ message: "User deleted" });
}
return Response.json({ error: "Not found" }, { status: 404 });
}
} satisfies ExportedHandler<Env>;
```
## Migrations Workflow
D1 uses SQL migration files to manage schema changes over time.
### Create Migration
```bash
# Create new migration file
wrangler d1 migrations create my-database create_users_table
# Creates: migrations/0001_create_users_table.sql
```
Edit the generated migration file:
```sql
-- migrations/0001_create_users_table.sql
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_users_email ON users(email);
```
### Apply Migrations
```bash
# Apply locally for testing
wrangler d1 migrations apply my-database --local
# Apply to remote database
wrangler d1 migrations apply my-database --remote
# List pending migrations
wrangler d1 migrations list my-database --local
```
### Migration Best Practices
1. **One migration per change**: Create separate migrations for each schema change
2. **Test locally first**: Always run `--local` before `--remote`
3. **Never edit applied migrations**: Create new migrations to fix issues
4. **Use transactions**: Migrations run in transactions by default
5. **Add indexes**: Include indexes in migrations for query performance
Example migration with multiple tables:
```sql
-- migrations/0002_add_posts.sql
CREATE TABLE posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
title TEXT NOT NULL,
content TEXT NOT NULL,
published BOOLEAN DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE INDEX idx_posts_user_id ON posts(user_id);
CREATE INDEX idx_posts_published ON posts(published);
```
## Batch Operations
Execute multiple statements in a single transaction for better performance and atomicity.
```typescript
interface Env {
DB: D1Database;
}
type Post = {
title: string;
content: string;
userId: number;
};
export default {
async fetch(request: Request, env: Env) {
const posts: Post[] = await request.json();
// Prepare all statements
const statements = posts.map(post =>
env.DB
.prepare("INSERT INTO posts (title, content, user_id) VALUES (?, ?, ?)")
.bind(post.title, post.content, post.userId)
);
// Execute as a batch (all or nothing)
try {
const results = await env.DB.batch(statements);
const insertedIds = results.map(r => r.meta.last_row_id);
return Response.json({
message: "Posts created",
ids: insertedIds,
count: results.length
});
} catch (error) {
return Response.json(
{ error: "Batch insert failed", details: error.message },
{ status: 500 }
);
}
}
} satisfies ExportedHandler<Env>;
```
**Batch benefits:**
- All statements succeed or all fail (atomic)
- Single round-trip to database
- Better pRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.