@ 细雨适应器/ 核心
用于 Drizzle ORM 的 TypeScript- First Object 定向适配器层,提供跨越不同数据库驱动器的统一接口.
概览
这个 @drizzle-adapter/core 软件包充当了Drizzle ORM之上的抽象层,提供了一个统一接口,在不同的数据库驱动器之间一致工作。 这个抽象值允许您写出数据库不可知代码,可以不作修改地与任何支持的数据库系统工作.
关键的概念是,虽然Drizzle ORM中不同的数据库驱动程序可能提供不同的特性和稍有不同的API,但这个适配器层使这些差异正常化,确保您的代码在不同的数据库系统之间保持可移植性.
关键特性
- 统一接口: 一次写出您的数据库代码并在不同的数据库之间切换,而不更改您的应用程序代码
- 类型安全: 完整类型脚本支持并严格打字
- 依赖性注射准备: 具有适合依赖性注射的接口的清洁建筑
- 驱动数据: 支持多个数据库驱动程序,包括 MySQL, PostgreSQL, SQLite等
- 一致 API: 不同数据库系统的接口标准化
- 自动加载驱动程序: 自动加载和配置相应驱动程序的工厂模式
安装
pnpm install @drizzle-adapter/core
加您要使用的驱动程序专用软件包 :
pnpm install @drizzle-adapter/mysql2 # for MySQL
# or
pnpm install @drizzle-adapter/node-postgres # for PostgreSQL
# or
pnpm install @drizzle-adapter/libsql # for SQLite
# etc.
使用量
- 配置您的数据库连接 :
import { TypeDrizzleDatabaseConfig } from '@drizzle-adapter/core';
const config: TypeDrizzleDatabaseConfig = {
DATABASE_DRIVER: 'mysql2', // or 'node-postgres', 'libsql', etc.
DATABASE_URL: process.env.DATABASE_URL
};
- 使用核心工厂创建适配器实例 :
import { DrizzleAdapterFactory } from '@drizzle-adapter/core';
// The factory automatically loads the appropriate driver
const factory = new DrizzleAdapterFactory();
const adapter = factory.create(config);
- 定义您的方案 :
// The data types are abstracted, so this works with any database
const dataTypes = adapter.getDataTypes();
const users = dataTypes.dbTable('users', {
id: dataTypes.dbSerial('id').primaryKey(),
name: dataTypes.dbText('name').notNull(),
email: dataTypes.dbText('email').notNull(),
createdAt: dataTypes.dbTimestamp('created_at').defaultNow()
});
- 数据库操作使用适配器 :
import { eq } from 'drizzle-orm';
// Connect to the database (works the same for any driver)
const connection = await adapter.getConnection();
// Get the database client
const client = connection.getClient();
try {
// All these operations work consistently across different databases
// Insert
await client.insert(users).values({
name: 'John Doe',
email: '[email protected]'
});
// Query
const user = await client
.select()
.from(users)
.where(eq(users.email, '[email protected]'))
.limit(1);
// Update
await client
.update(users)
.set({ name: 'John Smith' })
.where(eq(users.email, '[email protected]'));
// Delete
await client
.delete(users)
.where(eq(users.email, '[email protected]'));
} finally {
// Always disconnect
await connection.disconnect();
}
- 示例存储模式( Database Agnostic) :
import { DrizzleAdapterInterface, DrizzleClientInterface } from '@drizzle-adapter/core';
import { eq } from 'drizzle-orm';
interface User {
id: number;
name: string;
email: string;
}
class UserRepository {
private client: DrizzleClientInterface;
private users: any; // Your users table schema
constructor(private adapter: DrizzleAdapterInterface) {
// Schema definition works the same regardless of the database
const dataTypes = adapter.getDataTypes();
this.users = dataTypes.dbTable('users', {
id: dataTypes.dbSerial('id').primaryKey(),
name: dataTypes.dbText('name').notNull(),
email: dataTypes.dbText('email').notNull()
});
}
async connect(): Promise<void> {
const connection = await this.adapter.getConnection();
this.client = connection.getClient();
}
async disconnect(): Promise<void> {
await this.adapter.getConnection().disconnect();
}
async findById(id: number): Promise<User | null> {
const result = await this.client
.select()
.from(this.users)
.where(eq(this.users.id, id))
.limit(1);
return result[0] || null;
}
async create(user: Omit<User, 'id'>): Promise<User> {
const result = await this.client
.insert(this.users)
.values(user)
.returning();
return result[0];
}
async update(id: number, data: Partial<Omit<User, 'id'>>): Promise<User | null> {
const result = await this.client
.update(this.users)
.set(data)
.where(eq(this.users.id, id))
.returning();
return result[0] || null;
}
async delete(id: number): Promise<void> {
await this.client
.delete(this.users)
.where(eq(this.users.id, id));
}
}
// Usage example (works with any database):
async function main() {
const factory = new DrizzleAdapterFactory();
// MySQL configuration
const mysqlAdapter = factory.create({
DATABASE_DRIVER: 'mysql2',
DATABASE_URL: process.env.MYSQL_URL
});
// PostgreSQL configuration
const pgAdapter = factory.create({
DATABASE_DRIVER: 'node-postgres',
DATABASE_URL: process.env.POSTGRES_URL
});
// The same repository works with any adapter
const mysqlRepo = new UserRepository(mysqlAdapter);
const pgRepo = new UserRepository(pgAdapter);
// Use either repository - the code is exactly the same
await mysqlRepo.connect();
try {
const user = await mysqlRepo.create({
name: 'John Doe',
email: '[email protected]'
});
} finally {
await mysqlRepo.disconnect();
}
}
滴答音响
这个 DrizzleAdapterSingleton class 执行 Singleton 设计模式,确保只使用一个实例 DrizzleAdapterInterface 可以存在。 这对管理整个应用程序的单个适配器实例很有用 .
方法
- 静态( 静态 : DrizzleAdapter Interface QQ 未定义):设置适配器的单通实例.
- 获取Instance (): 返回适配器的单通实例。 如果实例未设定, 则丢出错误 .
用法示例
import { DrizzleAdapterSingleton } from '@drizzle-adapter/core';
import type { DrizzleAdapterInterface } from '@drizzle-adapter/core';
// Setting the instance
DrizzleAdapterSingleton.setInstance(myAdapter);
// Getting the instance
const adapter = DrizzleAdapterSingleton.getInstance();
使用大小写
- 全球接入: 使用
DrizzleAdapterSingleton当您需要整个应用程序中全球可访问的适配器实例时. - 配置管理: 应用程序初始化期间设置适配器实例一次, 从代码库的任意位置访问, 而不绕过它 .
支持的驱动程序
Drizzle适应器生态系统包括下列适应器:
- MySQL (英语:
@drizzle-adapter/mysql2(中文(简体) ) - PostgreSQL (英语:
@drizzle-adapter/node-postgres, (中文(简体) ),@drizzle-adapter/postgres-js(中文(简体) ) - SQLite (% 1 ) (
@drizzle-adapter/libsql(中文(简体) ) - 云花板 D1 (英语)
@drizzle-adapter/d1(中文(简体) ) - 神经元( Neon)
@drizzle-adapter/neon-http(中文(简体) ) - TiDB (
@drizzle-adapter/tidb-serverless(中文(简体) ) - PGLite (英语:
@drizzle-adapter/pglite(中文(简体) )
捐款
欢迎捐款! 这就是你能帮助:
- 叉子存储器
- 创建您的特性分支( E)
git checkout -b feature/amazing-feature(中文(简体) ) - 提交更改( E)
git commit -m 'Add some amazing feature'(中文(简体) ) - 推向分行(
git push origin feature/amazing-feature(中文(简体) ) - 打开拉请求