@drizzle-adapter/core

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

A TypeScript-first Object-Oriented adapter layer for Drizzle ORM that provides a unified interface across different database drivers.

原始使用文档
文档目录11 节
  1. Overview
  2. Key Features
  3. Installation
  4. Usage
  5. DrizzleAdapterSingleton
  6. Methods
  7. Usage Example
  8. Use Cases
  9. Supported Drivers
  10. Contributing
  11. Related Packages

@drizzle-adapter/core

A TypeScript-first Object-Oriented adapter layer for Drizzle ORM that provides a unified interface across different database drivers.

Overview

The @drizzle-adapter/core package serves as an abstraction layer over Drizzle ORM, providing a unified interface that works consistently across different database drivers. This abstraction allows you to write database-agnostic code that can work with any supported database system without modification.

The key concept is that while different database drivers in Drizzle ORM may offer varying features and slightly different APIs, this adapter layer normalizes these differences, ensuring your code remains portable across different database systems.

Key Features

  • Unified Interface: Write your database code once and switch between different databases without changing your application code
  • Type Safety: Full TypeScript support with strict typing
  • Dependency Injection Ready: Clean architecture with interfaces suitable for dependency injection
  • Driver Agnostic: Support for multiple database drivers including MySQL, PostgreSQL, SQLite, and more
  • Consistent API: Normalized interface across different database systems
  • Automatic Driver Loading: Factory pattern that automatically loads and configures the appropriate driver

Installation

pnpm install @drizzle-adapter/core

Plus the driver-specific package you want to use:

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.

Usage

  1. Configure your database connection:
import { TypeDrizzleDatabaseConfig } from '@drizzle-adapter/core';

const config: TypeDrizzleDatabaseConfig = {
  DATABASE_DRIVER: 'mysql2', // or 'node-postgres', 'libsql', etc.
  DATABASE_URL: process.env.DATABASE_URL
};
  1. Create an adapter instance using the core factory:
import { DrizzleAdapterFactory } from '@drizzle-adapter/core';

// The factory automatically loads the appropriate driver
const factory = new DrizzleAdapterFactory();
const adapter = factory.create(config);
  1. Define your schema:
// 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()
});
  1. Use the adapter for database operations:
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();
}
  1. Example Repository Pattern (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

The DrizzleAdapterSingleton class implements the Singleton design pattern, ensuring that only one instance of DrizzleAdapterInterface can exist. This is useful for managing a single adapter instance throughout your application.

Methods

  • setInstance(instance: DrizzleAdapterInterface | undefined): Sets the singleton instance of the adapter.
  • getInstance(): Returns the singleton instance of the adapter. Throws an error if the instance has not been set.

Usage Example

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

Use Cases

  • Global Access: Use DrizzleAdapterSingleton when you need a globally accessible adapter instance throughout your application.
  • Configuration Management: Set the adapter instance once during application initialization and access it from anywhere in your codebase without passing it around.

Supported Drivers

The Drizzle Adapter ecosystem includes adapters for:

  • MySQL (@drizzle-adapter/mysql2)
  • PostgreSQL (@drizzle-adapter/node-postgres, @drizzle-adapter/postgres-js)
  • SQLite (@drizzle-adapter/libsql)
  • Cloudflare D1 (@drizzle-adapter/d1)
  • Neon (@drizzle-adapter/neon-http)
  • TiDB (@drizzle-adapter/tidb-serverless)
  • PGLite (@drizzle-adapter/pglite)

Contributing

Contributions are welcome! Here's how you can help:

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

版本与发布记录

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

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

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

@drizzle-adapter/core 是什么?

A TypeScript-first Object-Oriented adapter layer for Drizzle ORM that provides a unified interface across different database drivers.

如何安装 @drizzle-adapter/core?

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

@drizzle-adapter/core 支持 TypeScript 吗?

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

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

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

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

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

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

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

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

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