@ 细雨适应器/ pglite
PgLite适配器用于Drizzle适配器生态系统,提供一种轻量级的PostgreSQL兼容数据库,适合开发和测试.
概览
这个 @drizzle-adapter/pglite 软件包为 Drizzle 适应器接口提供 PgLite 执行。 虽然你不直接与此软件包互动( 您使用 @drizzle-adapter/core 相反,它可以在Drizzle适应器生态系统中建立一个轻量级的PostgreSQL兼容数据库.
为什么是PgLite?
PgLite为开发和测试提供了独特的优势:
- 嵌入式邮递SQL: 完全不安装的 PostgreSQL 兼容性
- 0 配置: 在没有设置的盒子内工作
- 内存或文件存储: 选择内存或持久存储
- 适合测试: 用于每次测试的快速、孤立的数据库实例
- 发展友好组织: 快速启动, 没有外部依赖
- 邮递SQL 兼容: 使用没有 PostgreSQL 服务器的 PostgreSQL 特性
- 轻巧:足迹小,适合CI/CD环境
- 快速执行: 原地执行,以改善业绩
完美为:
- 单位测试: 每个测试中孤立的数据库实例
- 集成测试: 用于测试的全部 PostgreSQL 兼容性
- 地方发展: 不需要安装 PostgreSQL
- CI/CD 管道: 用于自动化测试的快速、轻量级数据库
- 原型制作: 新项目快速设置
安装
# Install both the core package and the PgLite adapter
pnpm install @drizzle-adapter/core @drizzle-adapter/pglite
重要:适配器注册
适配器要正确使用 DrizzleAdapterFactory 操作,必须导入它进行自我注册的副作用:
// Import for side effects - adapter will self-register
import '@drizzle-adapter/pglite';
// Now you can use the factory
import { DrizzleAdapterFactory } from '@drizzle-adapter/core';
使用量
配置
import { DrizzleAdapterFactory, TypeDrizzleDatabaseConfig } from '@drizzle-adapter/core';
// In-memory database (perfect for testing)
const config: TypeDrizzleDatabaseConfig = {
DATABASE_DRIVER: 'pglite'
};
const factory = new DrizzleAdapterFactory();
const adapter = factory.create(config);
Schema 定义
const dataTypes = adapter.getDataTypes();
const users = dataTypes.dbTable('users', {
id: dataTypes.dbSerial('id').primaryKey(),
name: dataTypes.dbText('name').notNull(),
email: dataTypes.dbText('email').notNull().unique(),
profile: dataTypes.dbJsonb('profile'),
createdAt: dataTypes.dbTimestamp('created_at').defaultNow()
});
const posts = dataTypes.dbTable('posts', {
id: dataTypes.dbSerial('id').primaryKey(),
userId: dataTypes.dbInteger('user_id')
.references(() => users.id),
title: dataTypes.dbText('title').notNull(),
content: dataTypes.dbText('content').notNull(),
tags: dataTypes.dbArray('tags', { type: 'text' }),
metadata: dataTypes.dbJsonb('metadata'),
published: dataTypes.dbBoolean('published').default(false),
createdAt: dataTypes.dbTimestamp('created_at').defaultNow()
});
基本 CRUD 操作
import { eq, and, or, desc, sql } from 'drizzle-orm';
const client = await adapter.getConnection().getClient();
// INSERT
// Single insert with returning
const [newUser] = await client
.insert(users)
.values({
name: 'John Doe',
email: '[email protected]',
profile: { bio: 'Hello!' }
})
.returning();
// Bulk insert
await client
.insert(posts)
.values([
{
userId: newUser.id,
title: 'First Post',
content: 'Hello, world!',
tags: ['hello', 'first']
},
{
userId: newUser.id,
title: 'Second Post',
content: 'Another post',
tags: ['second']
}
]);
// 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 and array operations
const postsWithTags = await client
.select({
userName: users.name,
postTitle: posts.title,
tags: posts.tags
})
.from(posts)
.leftJoin(users, eq(posts.userId, users.id))
.where(sql`${posts.tags} && ARRAY['hello']::text[]`)
.orderBy(desc(posts.createdAt));
// UPDATE
await client
.update(users)
.set({
name: 'John Smith',
profile: { bio: 'Updated bio' }
})
.where(eq(users.id, newUser.id));
// DELETE
await client
.delete(posts)
.where(
and(
eq(posts.userId, newUser.id),
eq(posts.published, false)
)
);
测试示例
import { DrizzleAdapterFactory } from '@drizzle-adapter/core';
describe('User Repository Tests', () => {
let adapter: DrizzleAdapterInterface;
let repository: UserRepository;
beforeEach(async () => {
// New in-memory database for each test
const factory = new DrizzleAdapterFactory();
adapter = factory.create({
DATABASE_DRIVER: 'pglite'
});
repository = new UserRepository(adapter);
await repository.connect();
// Create tables
const client = await adapter.getConnection().getClient();
await client.execute(sql`
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE
)
`);
});
afterEach(async () => {
await repository.disconnect();
});
it('should create a new user', async () => {
const user = await repository.create({
name: 'Test User',
email: '[email protected]'
});
expect(user.name).toBe('Test User');
expect(user.email).toBe('[email protected]');
});
it('should find user by email', async () => {
await repository.create({
name: 'Test User',
email: '[email protected]'
});
const user = await repository.findByEmail('[email protected]');
expect(user).not.toBeNull();
expect(user?.name).toBe('Test User');
});
});
最佳做法
- 测试: 使用内存数据库进行测试
- 隔离: 为每个测试创建新实例
- 发展: 不使用 PostgreSQL 用于本地开发
- 排雷中心/发改委: 适用于自动化测试管道的完美
- Schema 验证: 测试没有完整服务器的 PostgreSQL 计划
捐款
我们欢迎捐款! 请随意提交拉力请求 对于重大变动,请先开出一个问题来讨论你想要改变什么.
相关软件包
- @ 细雨适应器/ 核心 - 核心接口和类型
- @ 细雨适应器/ pg- core - 共享 PostgreSQL 功能