d1-database

Build serverless applications with Cloudflare D1 — SQLite running at the edge. Appropriate for questions about “serverless databases,” “Cloudflare D1,” “SQLite on edge nodes,” “Workers databases,” “edge databases,” or “serverless SQL.” Covers schema setup, queries, migrations, Workers integration, and using the Drizzle ORM.

Last repository push
GitHub Stars
219
Forks
38
Issues / PRs
1

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "d1-database" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-098e1e5cb65724f4775e9e5dd62ab9f8939f604130e3cf3713afec94fa674bc7. Verify the upstream source and version against https://github.com/TerminalSkills/skills before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

github.com

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

Build serverless applications with Cloudflare D1 — SQLite running at the edge. Appropriate for questions about “serverless databases,” “Cloudflare D1,” “SQLite on edge nodes,” “Workers databases,” “edge databases,” or “serverless SQL.” Covers schema setup, queries, migrations, Workers integration, and using the Drizzle ORM.

0 Downloads

Introduction source: third_party · TerminalSkills · 1.0.0 Reference

SkillPi interpretation

Audience
Building on Cloudflare Workers and need a database Read-heavy applications (blogs, content sites, APIs) Want SQLite simplicity with global distribution Serverless applications with no connection pooling headaches Edge-first applications where database latency matters
Software, accounts and paid services
```bash
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: d1-database
description: >-
  Build serverless applications with Cloudflare D1 — SQLite at the edge. Use
  when someone asks to "serverless database", "Cloudflare D1", "SQLite at the
  edge", "database for Workers", "edge database", or "serverless SQL". Covers
  schema setup, queries, migrations, Workers integration, and Drizzle ORM.
license: Apache-2.0
compatibility: "Cloudflare Workers. Wrangler CLI. SQLite-compatible."
metadata:
  author: terminal-skills
  version: "1.0.0"
  category: data-ai
  tags: ["database", "cloudflare", "d1", "sqlite", "edge"]

Cloudflare D1

Overview

D1 is Cloudflare's serverless SQLite database — runs at the edge alongside Workers. Zero connection overhead (it's in the same data center as your Worker), SQLite query syntax, automatic replication, and pay-per-query pricing. Perfect for read-heavy workloads, content sites, and applications where latency matters.

When to Use

  • Building on Cloudflare Workers and need a database
  • Read-heavy applications (blogs, content sites, APIs)
  • Want SQLite simplicity with global distribution
  • Serverless applications with no connection pooling headaches
  • Edge-first applications where database latency matters

Instructions

Setup

# Create a D1 database
npx wrangler d1 create my-database

# Add to wrangler.toml
# wrangler.toml
[[d1_databases]]
binding = "DB"
database_name = "my-database"
database_id = "xxxx-xxxx-xxxx"

Schema and Migrations

# Create migration
npx wrangler d1 migrations create my-database init
-- migrations/0001_init.sql
CREATE TABLE users (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  email TEXT NOT NULL UNIQUE,
  name TEXT NOT NULL,
  created_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE posts (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  title TEXT NOT NULL,
  content TEXT NOT NULL,
  author_id INTEGER NOT NULL REFERENCES users(id),
  published BOOLEAN DEFAULT FALSE,
  created_at TEXT DEFAULT (datetime('now'))
);

CREATE INDEX idx_posts_author ON posts(author_id);
CREATE INDEX idx_posts_published ON posts(published);
# Apply migrations
npx wrangler d1 migrations apply my-database

Queries in Workers

// src/index.ts — Cloudflare Worker with D1
export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);

    if (url.pathname === "/api/posts" && request.method === "GET") {
      const { results } = await env.DB.prepare(
        `SELECT posts.*, users.name as author_name
         FROM posts
         JOIN users ON posts.author_id = users.id
         WHERE posts.published = TRUE
         ORDER BY posts.created_at DESC
         LIMIT ?`
      ).bind(20).all();

      return Response.json({ posts: results });
    }

    if (url.pathname === "/api/posts" && request.method === "POST") {
      const body = await request.json();
      const result = await env.DB.prepare(
        "INSERT INTO posts (title, content, author_id) VALUES (?, ?, ?) RETURNING *"
      ).bind(body.title, body.content, body.authorId).first();

      return Response.json({ post: result }, { status: 201 });
    }

    return new Response("Not found", { status: 404 });
  },
};

With Drizzle ORM

// src/db/schema.ts — Drizzle schema for D1
import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";

export const users = sqliteTable("users", {
  id: integer("id").primaryKey({ autoIncrement: true }),
  email: text("email").notNull().unique(),
  name: text("name").notNull(),
});

export const posts = sqliteTable("posts", {
  id: integer("id").primaryKey({ autoIncrement: true }),
  title: text("title").notNull(),
  content: text("content").notNull(),
  authorId: integer("author_id").notNull().references(() => users.id),
  published: integer("published", { mode: "boolean" }).default(false),
});
// src/index.ts — Using Drizzle with D1
import { drizzle } from "drizzle-orm/d1";
import { eq } from "drizzle-orm";
import * as schema from "./db/schema";

export default {
  async fetch(request: Request, env: Env) {
    const db = drizzle(env.DB, { schema });

    const publishedPosts = await db.query.posts.findMany({
      where: eq(schema.posts.published, true),
      with: { author: true },
      orderBy: (posts, { desc }) => [desc(posts.id)],
      limit: 20,
    });

    return Response.json({ posts: publishedPosts });
  },
};

Examples

Example 1: Build a blog API on the edge

User prompt: "Create a blog API with Cloudflare Workers and D1 for posts and comments."

The agent will create D1 schema, migrations, CRUD endpoints in a Worker, and Drizzle ORM integration.

Example 2: User authentication with D1

User prompt: "Store user accounts in D1 with email/password auth."

The agent will create users table, password hashing with Web Crypto API, session management, and auth middleware.

Guidelines

  • SQLite syntax — D1 is SQLite under the hood
  • Prepared statements with .bind() — prevent SQL injection
  • .first() for single row, .all() for multiple — query methods
  • Migrations via Wrangler — version-controlled schema changes
  • Read replicas are automatic — D1 replicates globally
  • Write latency is higher — writes go to primary; reads are fast everywhere
  • 5MB row limit — not for large blobs
  • Free tier: 5M reads, 100K writes/day — generous for small apps
  • Drizzle ORM recommended — type-safe queries with D1 adapter
  • Local development — wrangler dev uses local SQLite

Current listing version

1.0.0

Verify the source revision ↗

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value85/100

Highlights

  • 提供 Cloudflare D1 的完整使用指南,涵盖数据库创建、迁移、查询、ORM 集成等核心功能
  • 面向边缘计算和无服务器架构开发者,具有明确实用价值和广泛适用场景
Trigger Precision95/100

Highlights

  • 触发词覆盖完整且精准,包含 "serverless database"、"Cloudflare D1"、"SQLite at the edge" 等多种变体
  • 边界清晰,专门针对 D1 使用场景,不易与其他 Skill 重叠
Structure and Standards85/100

Areas to improve

  • 缺少明确的出口条件说明 Reported severity: Minor

    文档中未明确说明何时应停止使用该 Skill 或转向其他解决方案

    Recommendation: 在 Guidelines 或新增章节中补充出口条件,如数据量超过限制、需要复杂事务等场景

  • When to Use 章节说明不够详细 Reported severity: Minor

    When to Use 部分列出了适用场景,但缺乏对不适用场景的明确说明

    Recommendation: 补充不适用场景说明,帮助用户更准确判断是否使用该 Skill

Highlights

  • Phase/步骤清晰完整,从 Setup 到 Examples 形成完整闭环
  • frontmatter 完整规范,包含必要的元数据信息
  • 提供端到端示例,增强实用性和可操作性
Execution Reliability90/100

Highlights

  • 工具来源明确(Wrangler CLI, Drizzle ORM),参数正确,代码示例完整可执行
  • 覆盖主要异常场景和最佳实践,包含安全建议(SQL injection 防护)和限制说明
  • 提供本地开发方案和免费 tier 信息,增强实用性
Evidence Verifiability (mean of the first four)89/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

  • Install or fetch external dependencies

    Use official sources and pin versions. Check install scripts in an isolated environment. This document check does not cover code downloaded later.

    Mentioned in main document · lines 37, 54, 81

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

```bash

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.