@ 细雨适应器/ mysql2
MySQL 适配器用于 Drizzle适配器生态系统 使用 Mysql2 驱动程序.
概览
这个 @drizzle-adapter/mysql2 软件包利用高性能为 Drizzle 适应器接口提供 MySQL 执行 mysql2 驾驶员。 虽然你不直接与此软件包互动( 您使用 @drizzle-adapter/core 相反,它使得MySQL能够在Drizzle适应器生态系统中提供支持.
为什么是Misql2?
Mysql2驱动程序具有显著优势:
- 高性能:优化速度和效率
- 发言稿: 编写说明的当地支持
- 连接集合: 内置连接池管理
- 二进制协议: 高效二进制协议支持
- 保证API: 基于承诺的现代接口
- 压缩: 网络压缩支持
- SSL/TLS 系统: 安全连接支持
- 字符集/组合: 完整的字符集和整理支持
安装
# Install both the core package and the MySQL adapter
pnpm install @drizzle-adapter/core @drizzle-adapter/mysql2
重要:适配器注册
适配器要正确使用 DrizzleAdapterFactory 操作,必须导入它进行自我注册的副作用:
// Import for side effects - adapter will self-register
import '@drizzle-adapter/mysql2';
// Now you can use the factory
import { DrizzleAdapterFactory } from '@drizzle-adapter/core';
使用量
配置
import { DrizzleAdapterFactory, TypeDrizzleDatabaseConfig } from '@drizzle-adapter/core';
const config: TypeDrizzleDatabaseConfig = {
DATABASE_DRIVER: 'mysql2',
DATABASE_HOST: 'localhost',
DATABASE_PORT: 3306,
DATABASE_USER: 'user',
DATABASE_PASSWORD: 'password',
DATABASE_NAME: 'database'
};
const factory = new DrizzleAdapterFactory();
const adapter = factory.create(config);
Schema 定义
const dataTypes = adapter.getDataTypes();
const users = dataTypes.dbTable('users', {
id: dataTypes.dbBigInt('id', { mode: 'number' }).primaryKey().autoincrement(),
name: dataTypes.dbVarChar('name', { length: 255 }).notNull(),
email: dataTypes.dbVarChar('email', { length: 255 }).notNull().unique(),
status: dataTypes.dbEnum('status', ['active', 'inactive']).default('active'),
metadata: dataTypes.dbJson('metadata'),
createdAt: dataTypes.dbTimestamp('created_at').defaultNow()
});
const posts = dataTypes.dbTable('posts', {
id: dataTypes.dbBigInt('id', { mode: 'number' }).primaryKey().autoincrement(),
userId: dataTypes.dbBigInt('user_id', { mode: 'number' })
.references(() => users.id),
title: dataTypes.dbVarChar('title', { length: 255 }).notNull(),
content: dataTypes.dbText('content').notNull(),
published: dataTypes.dbBoolean('published').default(false),
createdAt: dataTypes.dbTimestamp('created_at').defaultNow(),
updatedAt: dataTypes.dbTimestamp('updated_at').onUpdateNow()
});
基本 CRUD 操作
import { eq, and, or, desc, sql } from 'drizzle-orm';
const connection = await adapter.getConnection();
const client = connection.getClient();
try {
// INSERT
// Single insert with returning
const [newUser] = await client
.insert(users)
.values({
name: 'John Doe',
email: '[email protected]',
metadata: { role: 'user' }
})
.returning();
// Bulk insert
await client
.insert(posts)
.values([
{
userId: newUser.id,
title: 'First Post',
content: 'Hello, world!'
},
{
userId: newUser.id,
title: 'Second Post',
content: 'Another post'
}
]);
// SELECT
// Select all
const allUsers = await client
.select()
.from(users);
// Select with conditions
const user = await client
.select()
.from(users)
.where(eq(users.email, '[email protected]'));
// Select with join
const userPosts = await client
.select({
userName: users.name,
postTitle: posts.title,
content: posts.content,
metadata: users.metadata
})
.from(posts)
.leftJoin(users, eq(posts.userId, users.id))
.where(eq(posts.published, true))
.orderBy(desc(posts.createdAt));
// UPDATE
// Update with JSON operations
await client
.update(users)
.set({
name: 'John Smith',
metadata: sql`JSON_SET(${users.metadata}, '$.role', 'admin')`
})
.where(eq(users.id, newUser.id));
// DELETE
await client
.delete(posts)
.where(
and(
eq(posts.userId, newUser.id),
eq(posts.published, false)
)
);
} finally {
await connection.disconnect();
}
高级特性
交易支持
const connection = await adapter.getConnection();
const client = connection.getClient();
try {
await client.transaction(async (tx) => {
const [user] = await tx
.insert(users)
.values({
name: 'John Doe',
email: '[email protected]'
})
.returning();
await tx
.insert(posts)
.values({
userId: user.id,
title: 'My First Post',
content: 'Hello, world!'
});
});
} finally {
await connection.disconnect();
}
JSON业务
// Query with JSON conditions
const premiumUsers = await client
.select()
.from(users)
.where(sql`JSON_EXTRACT(${users.metadata}, '$.subscription') = 'premium'`);
// Update nested JSON
await client
.update(users)
.set({
metadata: sql`JSON_SET(
${users.metadata},
'$.subscription', 'premium',
'$.validUntil', CURRENT_TIMESTAMP
)`
})
.where(eq(users.id, userId));
全文搜索
// Create FULLTEXT index
await client.execute(sql`
ALTER TABLE ${posts}
ADD FULLTEXT INDEX posts_fulltext (title, content)
`);
// Search posts
const searchResults = await client
.select()
.from(posts)
.where(sql`MATCH(title, content) AGAINST(${searchTerm} IN BOOLEAN MODE)`)
.orderBy(desc(posts.createdAt));
最佳做法
- 连接管理: 总是尝试/最后使用以确保连接被关闭
- 交易: 相关业务使用交易
- 发言稿: 自动准备发言
- 处理错误: 执行适当的错误处理和重试
- 查询优化: 使用适当的索引和查询规划
捐款
我们欢迎捐款! 请随意提交拉力请求 对于重大变动,请先开出一个问题来讨论你想要改变什么.
相关软件包
- @ 细雨适应器/ 核心 - 核心接口和类型
- @ 细雨适应器/ mysql- core - 共享 MySQL 功能