Loading...
Loading...
Compare original and translation side by side
| Source | Location pattern |
|---|---|
| Drizzle schema | |
| D1 migrations | |
| Raw SQL | |
| Prisma | |
| 来源 | 位置模式 |
|---|---|
| Drizzle schema | |
| D1迁移文件 | |
| 原生SQL | |
| Prisma | |
| Parameter | Options | Default |
|---|---|---|
| Purpose | dev, demo, testing | dev |
| Volume | small (5-10 rows/table), medium (20-50), large (100+) | small |
| Domain context | "e-commerce store", "SaaS app", "blog", etc. | Infer from schema |
| Output format | TypeScript (Drizzle), raw SQL, or both | Match project's ORM |
| 参数 | 选项 | 默认值 |
|---|---|---|
| 用途 | dev(开发)、demo(演示)、testing(测试) | dev |
| 数据量 | small(每张表5-10行)、medium(20-50行)、large(100+行) | small |
| 业务场景 | "电商平台"、"SaaS应用"、"博客"等 | 从schema推断 |
| 输出格式 | TypeScript(Drizzle)、原生SQL或两者兼具 | 匹配项目使用的ORM |
1. users (no dependencies)
2. categories (no dependencies)
3. posts (depends on users, categories)
4. comments (depends on users, posts)
5. tags (no dependencies)
6. post_tags (depends on posts, tags)1. users (无依赖)
2. categories (无依赖)
3. posts (依赖users、categories)
4. comments (依赖users、posts)
5. tags (无依赖)
6. post_tags (依赖posts、tags)const firstNames = ['Sarah', 'James', 'Priya', 'Mohammed', 'Emma', 'Wei', 'Carlos', 'Aisha'];
const lastNames = ['Chen', 'Smith', 'Patel', 'Garcia', 'Kim', 'O\'Brien', 'Nguyen', 'Wilson'];sarah.chen@example.comexample.comconst randomDate = (daysBack: number) => {
const d = new Date();
d.setDate(d.getDate() - Math.floor(Math.random() * daysBack));
return d.toISOString();
};crypto.randomUUID()function seededRandom(seed: number) {
return () => {
seed = (seed * 16807) % 2147483647;
return (seed - 1) / 2147483646;
};
}
const rand = seededRandom(42); // Same seed = same data every time(rand() * 900 + 100).toFixed(2)const firstNames = ['Sarah', 'James', 'Priya', 'Mohammed', 'Emma', 'Wei', 'Carlos', 'Aisha'];
const lastNames = ['Chen', 'Smith', 'Patel', 'Garcia', 'Kim', 'O\'Brien', 'Nguyen', 'Wilson'];sarah.chen@example.comexample.comconst randomDate = (daysBack: number) => {
const d = new Date();
d.setDate(d.getDate() - Math.floor(Math.random() * daysBack));
return d.toISOString();
};crypto.randomUUID()function seededRandom(seed: number) {
return () => {
seed = (seed * 16807) % 2147483647;
return (seed - 1) / 2147483646;
};
}
const rand = seededRandom(42); // 相同种子=每次生成相同数据(rand() * 900 + 100).toFixed(2)// scripts/seed.ts
import { drizzle } from 'drizzle-orm/d1';
import * as schema from '../src/db/schema';
export async function seed(db: ReturnType<typeof drizzle>) {
console.log('Seeding database...');
// Clear existing data (reverse dependency order)
await db.delete(schema.comments);
await db.delete(schema.posts);
await db.delete(schema.users);
// Insert users
const users = [
{ id: crypto.randomUUID(), name: 'Sarah Chen', email: 'sarah@example.com', ... },
// ...
];
// D1 batch limit: 10 rows per INSERT
for (let i = 0; i < users.length; i += 10) {
await db.insert(schema.users).values(users.slice(i, i + 10));
}
// Insert posts (references users)
const posts = [
{ id: crypto.randomUUID(), userId: users[0].id, title: '...', ... },
// ...
];
for (let i = 0; i < posts.length; i += 10) {
await db.insert(schema.posts).values(posts.slice(i, i + 10));
}
console.log(`Seeded: ${users.length} users, ${posts.length} posts`);
}npx tsx scripts/seed.tsapp.post('/api/seed', async (c) => {
const db = drizzle(c.env.DB);
await seed(db);
return c.json({ ok: true });
});// scripts/seed.ts
import { drizzle } from 'drizzle-orm/d1';
import * as schema from '../src/db/schema';
export async function seed(db: ReturnType<typeof drizzle>) {
console.log('Seeding database...');
// 清除现有数据(反向依赖顺序)
await db.delete(schema.comments);
await db.delete(schema.posts);
await db.delete(schema.users);
// 插入用户
const users = [
{ id: crypto.randomUUID(), name: 'Sarah Chen', email: 'sarah@example.com', ... },
// ...
];
// D1批量限制:每次INSERT最多10行
for (let i = 0; i < users.length; i += 10) {
await db.insert(schema.users).values(users.slice(i, i + 10));
}
// 插入文章(关联用户)
const posts = [
{ id: crypto.randomUUID(), userId: users[0].id, title: '...', ... },
// ...
];
for (let i = 0; i < posts.length; i += 10) {
await db.insert(schema.posts).values(posts.slice(i, i + 10));
}
console.log(`Seeded: ${users.length} users, ${posts.length} posts`);
}npx tsx scripts/seed.tsapp.post('/api/seed', async (c) => {
const db = drizzle(c.env.DB);
await seed(db);
return c.json({ ok: true });
});-- seed.sql
-- Run: npx wrangler d1 execute DB_NAME --local --file=./scripts/seed.sql
-- Clear existing (reverse order)
DELETE FROM comments;
DELETE FROM posts;
DELETE FROM users;
-- Users
INSERT INTO users (id, name, email, created_at) VALUES
('uuid-1', 'Sarah Chen', 'sarah@example.com', '2025-01-15T10:30:00Z'),
('uuid-2', 'James Wilson', 'james@example.com', '2025-02-01T14:22:00Z');
-- Posts (max 10 rows per INSERT for D1)
INSERT INTO posts (id, user_id, title, body, created_at) VALUES
('post-1', 'uuid-1', 'Getting Started', 'Welcome to...', '2025-03-01T09:00:00Z');-- seed.sql
-- 运行命令: npx wrangler d1 execute DB_NAME --local --file=./scripts/seed.sql
-- 清除现有数据(反向顺序)
DELETE FROM comments;
DELETE FROM posts;
DELETE FROM users;
-- 用户数据
INSERT INTO users (id, name, email, created_at) VALUES
('uuid-1', 'Sarah Chen', 'sarah@example.com', '2025-01-15T10:30:00Z'),
('uuid-2', 'James Wilson', 'james@example.com', '2025-02-01T14:22:00Z');
-- 文章数据(D1每次INSERT最多10行)
INSERT INTO posts (id, user_id, title, body, created_at) VALUES
('post-1', 'uuid-1', 'Getting Started', 'Welcome to...', '2025-03-01T09:00:00Z');// Option A: Delete-then-insert (simple, loses data)
await db.delete(schema.users);
await db.insert(schema.users).values(seedUsers);
// Option B: Upsert (preserves non-seed data)
for (const user of seedUsers) {
await db.insert(schema.users)
.values(user)
.onConflictDoUpdate({ target: schema.users.id, set: user });
}// 选项A:先删除再插入(简单,但会丢失现有数据)
await db.delete(schema.users);
await db.insert(schema.users).values(seedUsers);
// 选项B:Upsert(保留非种子数据)
for (const user of seedUsers) {
await db.insert(schema.users)
.values(user)
.onConflictDoUpdate({ target: schema.users.id, set: user });
}| Gotcha | Solution |
|---|---|
| Max ~10 rows per INSERT | Batch inserts in chunks of 10 |
| No native BOOLEAN | Use INTEGER (0/1) |
| No native DATETIME | Use TEXT with ISO 8601 strings |
| JSON stored as TEXT | |
| Foreign keys always enforced | Insert parent tables first |
| 100 bound parameter limit | Keep batch size × columns < 100 |
| 注意事项 | 解决方案 |
|---|---|
| 每次INSERT最多约10行 | 将插入操作按10行一批分批执行 |
| 无原生BOOLEAN类型 | 使用INTEGER(0/1)代替 |
| 无原生DATETIME类型 | 使用TEXT类型存储ISO 8601格式字符串 |
| JSON以TEXT格式存储 | 插入前执行 |
| 外键始终强制生效 | 先插入父表 |
| 绑定参数上限为100 | 确保批量大小 × 列数 < 100 |