关于 drizzle-migrations
面向使用 Drizzle ORM 和 SQLite 的开发者,涵盖架构变更、迁移、查询模式与配置。
主要功能
- 01SQLite 架构定义
- 02生成并应用迁移
- 03Drizzle 查询模式与关系
- 04配置和架构指导
适用场景
- 01添加表或列
- 02生成并应用迁移
- 03定义关系并编写查询
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ curiositech/ some_claude_skills --skill drizzle-migrations安装后在 Claude Code 中输入/drizzle-migrations确认已加载。
附带文件.claude-plugin/plugin.json
详细介绍
Drizzle ORM 迁移
此技能可帮助你使用 Drizzle ORM 和 SQLite 管理数据库架构变更。
适用场景
✅ 适用于以下场景:
- 添加新表或修改现有列
- 生成并运行数据库迁移
- Drizzle 专属的查询模式和关系
- 使用 Drizzle 的 SQLite 架构最佳实践
- 设置 Drizzle 配置
❌ 不适用于以下场景:
- Supabase/PostgreSQL → 使用
supabase-admin技能 - 不使用 Drizzle 的原始 SQL → 使用标准 SQL 资源
- Prisma ORM → 语法和模式不同
- 通用数据库设计理论 → 使用数据库架构资源
项目设置
配置:drizzle.config.ts
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
schema: './src/db/schema.ts',
out: './drizzle',
dialect: 'sqlite',
dbCredentials: {
url: './data/app.db',
},
});
命令:
npm run db:generate # Generate migration files
npm run db:push # Push schema directly (dev only)
npm run db:studio # Open Drizzle Studio GUI
架构定义
位置:src/db/schema.ts
表定义
import { sqliteTable, text, integer, real, blob } from 'drizzle-orm/sqlite-core';
import { relations } from 'drizzle-orm';
// Basic table
export const users = sqliteTable('users', {
id: text('id').primaryKey(),
email: text('email').notNull().unique(),
username: text('username').notNull(),
passwordHash: text('password_hash'),
createdAt: text('created_at').notNull().default(sql`CURRENT_TIMESTAMP`),
updatedAt: text('updated_at'),
});
// Table with foreign key
export const checkIns = sqliteTable('check_ins', {
id: text('id').primaryKey(),
userId: text('user_id').notNull().references(() => users.id, {
onDelete: 'cascade',
}),
mood: integer('mood').notNull(),
cravingLevel: integer('craving_level').notNull(),
sleepHours: real('sleep_hours'),
notes: text('notes'),
createdAt: text('created_at').notNull().default(sql`CURRENT_TIMESTAMP`),
});
// Table with composite index
export const auditLog = sqliteTable('audit_log', {
id: text('id').primaryKey(),
userId: text('user_id').notNull(),
action: text('action').notNull(),
targetType: text('target_type'),
targetId: text('target_id'),
details: text('details'), // JSON string
createdAt: text('created_at').notNull().default(sql`CURRENT_TIMESTAMP`),
}, (table) => ({
userActionIdx: index('idx_audit_user_action').on(table.userId, table.action),
createdAtIdx: index('idx_audit_created').on(table.createdAt),
}));
关系
export const usersRelations = relations(users, ({ many }) => ({
checkIns: many(checkIns),
sessions: many(sessions),
journalEntries: many(journalEntries),
}));
export const checkInsRelations = relations(checkIns, ({ one }) => ({
user: one(users, {
fields: [checkIns.userId],
references: [users.id],
}),
}));
列类型
Drizzle 中的 SQLite 类型
import {
sqliteTable,
text, // TEXT - strings, JSON, dates
integer, // INTEGER - numbers, booleans (0/1)
real, // REAL - floating point
blob, // BLOB - binary data
} from 'drizzle-orm/sqlite-core';
const examples = sqliteTable('examples', {
// Strings
name: text('name').notNull(),
description: text('description'),
// Numbers
count: integer('count').notNull().default(0),
rating: real('rating'),
// Booleans (stored as 0/1)
isActive: integer('is_active', { mode: 'boolean' }).default(true),
// Dates (stored as ISO strings)
createdAt: text('created_at').notNull().default(sql`CURRENT_TIMESTAMP`),
expiresAt: text('expires_at'),
// JSON (stored as TEXT)
metadata: text('metadata', { mode: 'json' }),
// Enums (stored as TEXT)
status: text('status', { enum: ['pending', 'active', 'archived'] }),
});
迁移策略
策略 1:Push(仅用于开发)
npm run db:push
- 直接应用架构变更
- 适用于快速开发
- 绝不可在生产环境中使用
策略 2:生成并迁移(生产环境)
# 1. Generate migration file
npm run db:generate
# 2. Review generated SQL in /drizzle folder
# 3. Apply migration (in code or manually)
在代码中应用迁移
import { drizzle } from 'drizzle-orm/better-sqlite3';
import { migrate } from 'drizzle-orm/better-sqlite3/migrator';
import Database from 'better-sqlite3';
const sqlite = new Database('./data/app.db');
const db = drizzle(sqlite);
// Run migrations
migrate(db, { migrationsFolder: './drizzle' });
常见架构变更
添加新表
// 1. Add to schema.ts
export const newFeature = sqliteTable('new_feature', {
id: text('id').primaryKey(),
userId: text('user_id').notNull().references(() => users.id),
name: text('name').notNull(),
createdAt: text('created_at').notNull().default(sql`CURRENT_TIMESTAMP`),
});
// 2. Add relations
export const newFeatureRelations = relations(newFeature, ({ one }) => ({
user: one(users, {
fields: [newFeature.userId],
references: [users.id],
}),
}));
// 3. Generate migration
// npm run db:generate
添加列
// In schema.ts, add the new column
export const users = sqliteTable('users', {
// existing columns...
newColumn: text('new_column'), // Add this
});
// Generate migration
// npm run db:generate
添加索引
export const messages = sqliteTable('messages', {
id: text('id').primaryKey(),
conversationId: text('conversation_id').notNull(),
createdAt: text('created_at').notNull(),
}, (table) => ({
// Add index
convCreatedIdx: index('idx_messages_conv_created')
.on(table.conversationId, table.createdAt),
}));
重命名(需要手动编写 SQL)
较旧版本的 SQLite 不支持直接重命名列。对于复杂变更:
-- drizzle/XXXX_rename_column.sql
-- Manual migration for column rename
-- 1. Create new table with desired schema
CREATE TABLE users_new (
id TEXT PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
display_name TEXT NOT NULL, -- renamed from username
created_at TEXT NOT NULL
);
-- 2. Copy data
INSERT INTO users_new SELECT id, email, username, created_at FROM users;
-- 3. Drop old table
DROP TABLE users;
-- 4. Rename new table
ALTER TABLE users_new RENAME TO users;
查询模式
基本查询
import { db } from '@/db';
import { eq, and, or, desc, asc, like, gte, lte } from 'drizzle-orm';
import { users, checkIns } from '@/db/schema';
// Select all
const allUsers = await db.select().from(users);
// Select with conditions
const activeUsers = await db
.select()
.from(users)
.where(eq(users.isActive, true));
// Select specific columns
const userEmails = await db
.select({ id: users.id, email: users.email })
.from(users);
// Complex where clause
const results = await db
.select()
.from(checkIns)
.where(
and(
eq(checkIns.userId, userId),
gte(checkIns.createdAt, startDate),
lte(checkIns.createdAt, endDate)
)
)
.orderBy(desc(checkIns.createdAt))
.limit(30);
插入
// Single insert
const [newUser] = await db
.insert(users)
.values({
id: generateId(),
email: '[email protected]',
username: 'newuser',
})
.returning();
// Bulk insert
await db.insert(checkIns).values([
{ id: '1', userId, mood: 7, cravingLevel: 2 },
{ id: '2', userId, mood: 8, cravingLevel: 1 },
]);
// Upsert (insert or update)
await db
.insert(users)
.values({ id: 'user-1', email: '[email protected]' })
.onConflictDoUpdate({
target: users.id,
set: { email: '[email protected]' },
});
更新
await db
.update(users)
.set({ username: 'newname', updatedAt: new Date().toISOString() })
.where(eq(users.id, userId));
删除
// Always use WHERE clause!
await db
.delete(checkIns)
.where(eq(checkIns.id, checkInId));
// Delete with multiple conditions
await db
.delete(sessions)
.where(
and(
eq(sessions.userId, userId),
lte(sessions.expiresAt, new Date().toISOString())
)
);
联接
const userWithCheckIns = await db
.select({
user: users,
checkIn: checkIns,
})
.from(users)
.leftJoin(checkIns, eq(users.id, checkIns.userId))
.where(eq(users.id, userId));
聚合
import { count, avg, sum, max, min } from 'drizzle-orm';
const stats = await db
.select({
totalCheckIns: count(),
avgMood: avg(checkIns.mood),
maxStreak: max(checkIns.streak),
})
.from(checkIns)
.where(eq(checkIns.userId, userId));
最佳实践
- 相关变更始终使用事务
await db.transaction(async (tx) => {
await tx.insert(users).values(userData);
await tx.insert(profiles).values(profileData);
});
- DELETE/UPDATE 始终包含 WHERE
- 为频繁查询的列创建索引
- 在 SQLite 中以 ISO 字符串存储日期
- 使用
returning()获取插入或更新的行 - 生成迁移,不要推送到生产环境
参考资料
评论
支持 Markdown