@drizzle-adapter/pglite

中文文档
1.1.1发布于 2026/03/26MITTypeScriptES Module近 30 天下载 1.8万

PgLite adapter implementation for the Drizzle Adapter ecosystem, providing a lightweight PostgreSQL-compatible database perfect for development and testing.

原始使用文档
文档目录13 节
  1. Overview
  2. Why PgLite?
  3. Perfect For:
  4. Installation
  5. Important: Adapter Registration
  6. Usage
  7. Configuration
  8. Schema Definition
  9. Basic CRUD Operations
  10. Testing Example
  11. Best Practices
  12. Contributing
  13. Related Packages

@drizzle-adapter/pglite

PgLite adapter implementation for the Drizzle Adapter ecosystem, providing a lightweight PostgreSQL-compatible database perfect for development and testing.

Overview

The @drizzle-adapter/pglite package provides the PgLite implementation for the Drizzle Adapter interface. While you don't interact with this package directly (you use @drizzle-adapter/core instead), it enables a lightweight PostgreSQL-compatible database in the Drizzle Adapter ecosystem.

Why PgLite?

PgLite offers unique advantages for development and testing:

  • Embedded PostgreSQL: Full PostgreSQL compatibility without installation
  • Zero Configuration: Works out of the box with no setup
  • Memory or File Storage: Choose between in-memory or persistent storage
  • Perfect for Testing: Fast, isolated database instances for each test
  • Development Friendly: Quick startup, no external dependencies
  • PostgreSQL Compatible: Use PostgreSQL features without PostgreSQL server
  • Lightweight: Small footprint, perfect for CI/CD environments
  • Fast Execution: Native implementation for better performance

Perfect For:

  1. Unit Testing: Isolated database instances per test
  2. Integration Testing: Full PostgreSQL compatibility for tests
  3. Local Development: No need for PostgreSQL installation
  4. CI/CD Pipelines: Fast, lightweight database for automated testing
  5. Prototyping: Quick setup for new projects

Installation

# Install both the core package and the PgLite adapter
pnpm install @drizzle-adapter/core @drizzle-adapter/pglite

Important: Adapter Registration

For the adapter to work correctly with the DrizzleAdapterFactory, you must import it for its self-registration side effects:

// Import for side effects - adapter will self-register
import '@drizzle-adapter/pglite';

// Now you can use the factory
import { DrizzleAdapterFactory } from '@drizzle-adapter/core';

Usage

Configuration

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 Definition

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()
});

Basic CRUD Operations

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)
    )
  );

Testing Example

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');
  });
});

Best Practices

  1. Testing: Use in-memory database for tests
  2. Isolation: Create new instance for each test
  3. Development: Use for local development without PostgreSQL
  4. CI/CD: Perfect for automated testing pipelines
  5. Schema Validation: Test PostgreSQL schemas without full server

Contributing

We welcome contributions! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

版本与发布记录

@drizzle-adapter/pglite 共发布 12 个版本,首次发布于 2024/12/03;过去 12 个月发布了 1 个版本。

版本发布日期距今
1.1.1latest2026/03/267 个月前
1.0.122025/07/171.3 年前
1.0.112025/07/121.3 年前
1.0.102025/07/121.3 年前
1.0.92025/04/201.6 年前
1.0.82025/03/101.7 年前

关于 @drizzle-adapter/pglite 的常见问题

@drizzle-adapter/pglite 是什么?

PgLite adapter implementation for the Drizzle Adapter ecosystem, providing a lightweight PostgreSQL-compatible database perfect for development and testing.

如何安装 @drizzle-adapter/pglite?

在项目目录运行 npm install @drizzle-adapter/pglite,或使用 pnpm add / yarn add / bun add。

@drizzle-adapter/pglite 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@drizzle-adapter/pglite 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@drizzle-adapter/pglite 可以商用吗?

@drizzle-adapter/pglite 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@drizzle-adapter/pglite 的下载量有多少?

根据 npm 官方下载统计,@drizzle-adapter/pglite 在 2026/10/13 – 2026/11/11 这 30 天内被下载 18,049 次,日均约 602 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@drizzle-adapter/pglite 还在维护吗?

最新版本 1.1.1 发布于 2026/03/26(7 个月前);至今共发布 12 个版本,其中过去 12 个月发布了 1 个;首次发布于 2024/12/03。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。