@duckdbfan/drizzle-duckdb

中文文档
2.5.0发布于 2026/11/10Apache-2.0TypeScriptES Module构建来源已验证近 30 天下载 2.4万

A drizzle ORM client for use with DuckDB. Based on drizzle's Postgres client.

原始使用文档
文档目录16 节
  1. DuckDB dialect for Drizzle ORM
  2. Installation
  3. Quick Start
  4. Connecting
  5. Connection Pooling
  6. Configuration
  7. DuckDB Types
  8. Arrays
  9. Transactions
  10. Migrations
  11. Schema Introspection
  12. Analytics and MotherDuck Helpers
  13. Known Limitations
  14. Examples
  15. Contributing
  16. License

Drizzle DuckDB

DuckDB dialect for Drizzle ORM

npm version License

Documentation • LLM Context • Examples • Contributing


Drizzle DuckDB brings Drizzle ORM to DuckDB, the in-process analytical database. You get Drizzle's type-safe query builder, migrations and TypeScript inference on top of DuckDB. It works with in-memory databases, local files, MotherDuck and Postgres servers running pg_duckdb.

Status: Experimental. Query building, migrations and type inference are stable. Some DuckDB-specific types and edge cases are still being refined.

Every docs page has a Markdown (raw) button with LLM-friendly source.

Installation

bun add @duckdbfan/drizzle-duckdb drizzle-orm @duckdb/node-api
# or: npm install / pnpm add with the same packages
RequirementSupported versions
drizzle-orm0.40.1 or newer, below 0.46.0
@duckdb/node-api1.4.4 or newer, below 1.6.0, including -r.N builds such as 1.5.6-r.1
RuntimeNode.js 18.17 or newer (22 or 24 recommended), or Bun

Quick Start

import { drizzle } from '@duckdbfan/drizzle-duckdb';
import { sql } from 'drizzle-orm';
import { integer, pgTable, text } from 'drizzle-orm/pg-core';

const users = pgTable('users', {
  id: integer('id').primaryKey(),
  name: text('name').notNull(),
  email: text('email').notNull(),
});

const db = await drizzle(':memory:');

await db.execute(sql`
  CREATE TABLE users (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT NOT NULL
  )
`);

await db.insert(users).values([
  { id: 1, name: 'Alice', email: '[email protected]' },
  { id: 2, name: 'Bob', email: '[email protected]' },
]);

const allUsers = await db.select().from(users);
//    ^? { id: number; name: string; email: string }[]

await db.close();

Schemas use the regular drizzle-orm/pg-core builders (pgTable, pgSchema and so on), and all standard Drizzle query methods work. DuckDB SQL is largely Postgres-compatible, and the dialect adapts queries where it is not.

Connecting

Pass a path and the driver creates a connection pool for you. await db.close() closes it.

import { drizzle } from '@duckdbfan/drizzle-duckdb';

// In-memory
const db = await drizzle(':memory:');

// Local file (created if missing)
const db = await drizzle('./my-database.duckdb');

// MotherDuck
const db = await drizzle({
  connection: {
    path: 'md:my_database',
    options: { motherduck_token: process.env.MOTHERDUCK_TOKEN },
  },
});

// DuckLake catalog
const db = await drizzle(':memory:', {
  ducklake: {
    catalog: './ducklake.duckdb',
    attachOptions: { dataPath: './ducklake-data' },
  },
});

Calls with the same file path share one DuckDB instance in a process, so they see each other's writes. :memory: is never shared.

You can also pass your own connection, pool or pg_duckdb client. These calls are synchronous:

import { DuckDBInstance } from '@duckdb/node-api';
import pg from 'pg';

// Existing DuckDB connection
const instance = await DuckDBInstance.create(':memory:');
const db = drizzle(await instance.connect());

// Postgres server with pg_duckdb. A pg.Client works too.
const db = drizzle(new pg.Pool({ connectionString: process.env.DATABASE_URL }));

A pg.Pool is wrapped with createPgDuckConnectionPool(), so each transaction runs on one pooled client and await db.close() ends the pool.

See Database Connection for singleton and serverless patterns.

Connection Pooling

DuckDB runs one query per connection, so the path forms above create a pool (default size 4).

  • Set the size or a MotherDuck preset: pool: { size: 8 }, pool: 'jumbo' or pool: 'giga'.
  • Tune recycling: pool: { size: 8, idleTimeoutMs: 60_000, maxLifetimeMs: 10 * 60_000 }.
  • Disable pooling: pool: false.
  • Transactions pin one pooled connection for their whole lifetime.
  • pool is ignored when you pass a connection or pool instance.

Create the pool yourself when you need the setup hook or want to share it between drizzle() instances:

import { DuckDBInstance } from '@duckdb/node-api';
import { createDuckDBConnectionPool, drizzle } from '@duckdbfan/drizzle-duckdb';

const instance = await DuckDBInstance.create('md:', {
  motherduck_token: process.env.MOTHERDUCK_TOKEN,
});
const pool = createDuckDBConnectionPool(instance, {
  size: 8,
  acquireTimeout: 20_000,
  maxWaitingRequests: 200,
  maxLifetimeMs: 10 * 60_000,
  idleTimeoutMs: 60_000,
});
const db = drizzle(pool);
console.log(pool.stats()); // Leases, queue depth, waits, recycling and timeouts

acquireTimeout limits time in the pool queue. Connection creation and setup run after that wait and have no deadline from this option. Check pool.stats() before increasing pool size, since more connections can compete with DuckDB's own query threads.

Configuration

import { DefaultLogger } from 'drizzle-orm';

const db = await drizzle(':memory:', {
  // Log every query
  logger: new DefaultLogger(),

  // Pool size, preset, or timeout and recycling options
  pool: { size: 8, idleTimeoutMs: 60_000 },

  // Bind a bare Date in sql`...` as TIMESTAMPTZ instead of a naive TIMESTAMP
  dateParams: 'timestamptz', // Default: 'timestamp'

  // Preserve DECIMAL values as strings in raw, streaming and nested reads
  decimalMode: 'string', // Default: 'number'

  // Legacy raw SQL join qualification heuristic, opt in only if needed
  qualifyRawJoinColumns: false,

  // Throw on Postgres-style array literals like '{1,2,3}' (default: false)
  rejectStringArrayLiterals: false,

  // Map camelCase keys to snake_case column names
  casing: 'snake_case',

  // Schema for relational queries
  schema: mySchema,
});

pool and ducklake apply only to the path and { connection } forms. The other options also work with drizzle(connection, { ... }). See Configuration for the full list.

DuckDB Types

DuckDB-specific column helpers: duckDbList, duckDbArray, duckDbStruct, duckDbUnion, duckDbMap, duckDbJson, duckDbBlob, duckDbInet, duckDbInterval, duckDbTimestamp, duckDbDate and duckDbTime.

  • duckDbTimestamp and duckDbTime can keep storage variants such as TIMESTAMP_NS, TIMESTAMP_MS, TIMESTAMP_S, TIME_NS and TIME WITH TIME ZONE through the duckDbType and withTimezone options.
  • Postgres json and jsonb columns are rejected. Use duckDbJson().
  • Browser-safe imports live under @duckdbfan/drizzle-duckdb/helpers. Introspection emits this path.

See Column Types for the full API.

Arrays

DuckDB supports @>, <@ and && on lists and fixed-size arrays, so Drizzle's arrayContains, arrayContained and arrayOverlaps work unchanged. The DuckDB helpers emit array_has_all and array_has_any:

import {
  duckDbArrayContained,
  duckDbArrayContains,
  duckDbArrayOverlaps,
} from '@duckdbfan/drizzle-duckdb';

// Tags include every value
db.select().from(products).where(duckDbArrayContains(products.tags, ['electronics', 'sale']));

// Tags are a subset of the values
db.select().from(products).where(duckDbArrayContained(products.tags, ['electronics', 'sale', 'featured']));

// Tags share at least one value
db.select().from(products).where(duckDbArrayOverlaps(products.tags, ['electronics', 'books']));

First-dimension array_lower(a, 1) and array_upper(a, 1) calls are rewritten to array_length expressions, because DuckDB lacks those functions.

Transactions

await db.transaction(async (tx) => {
  await tx.insert(accounts).values({ balance: 100 });
  await tx.update(accounts).set({ balance: 50 }).where(eq(accounts.id, 1));
});

DuckDB differs from Postgres here:

  • There is no SAVEPOINT. Nested transactions reuse the outer one, so an inner rollback aborts everything.
  • Without a pool, other db queries wait while a transaction is open on the shared connection, instead of joining it.
  • Any failed statement aborts the whole transaction. Catching the error inside the callback does not keep earlier writes. db.transaction() rolls back and rejects.
  • The config argument (isolationLevel, accessMode, deferrable) is deprecated and ignored with a one-time warning, because DuckDB has no SET TRANSACTION.

Migrations

import { migrate } from '@duckdbfan/drizzle-duckdb';

await migrate(db, { migrationsFolder: './drizzle' });

Metadata goes to drizzle.__drizzle_migrations by default. Concurrent migrate() calls apply each migration once, and DuckLake works as the default catalog. See Migrations for configuration.

Schema Introspection

Generate a Drizzle schema from an existing database with the CLI:

bunx duckdb-introspect --url ./my-database.duckdb --out ./drizzle/schema.ts

Or from code:

import { introspect } from '@duckdbfan/drizzle-duckdb';

const result = await introspect(db, {
  schemas: ['public', 'analytics'],
  includeViews: true,
});

console.log(result.files.schemaTs);

See Introspection for all options.

Analytics and MotherDuck Helpers

The package ships composable SQL helpers for analytical work:

  • OLAP helpers such as sumN, percentileCont, window helpers and the olap() grouped measures builder.
  • Lance vector, full-text and hybrid search.
  • MotherDuck table functions for Dives, Flights, file listings and access tokens, plus session identity scalars such as mdCurrentEmail() and mdIsRoleInSession().
  • Typed MotherDuck AI builders: mdPromptJev() classifies text or images and mdPrompt() generates text or structured output.
  • duckLakeMergeAdjacentFiles() for DuckLake compaction.
  • Batch and Arrow reads through db.executeBatches(), db.executeBatchesRaw() and db.executeArrow().
  • Fast bulk loads through db.appendRows(), which uses DuckDB's appender instead of an INSERT statement.
import { sql } from 'drizzle-orm';
import { mdCreateFlight, mdListDives, mdRunFlight } from '@duckdbfan/drizzle-duckdb';

const dives = await db.execute(sql`
  select id, title, updated_at
  from ${mdListDives({ limit: 10, includeOrgShares: true })}
  order by updated_at desc
`);

const [flight] = await db.execute(sql`
  select flight_id, status
  from ${mdCreateFlight({
    name: 'daily-refresh',
    sourceCode: 'print("hello")',
    scheduleCron: '0 0 * * *',
    maxRuntimeSec: 1_800,
    instanceType: 'F16',
  })}
`);

await db.execute(sql`
  select run_number, status
  from ${mdRunFlight(String(flight.flight_id), { config: { region: 'eu-west-1' } })}
`);

The older mdJobs() and mdFlights() helper names remain as deprecated aliases. See OLAP Helpers for the full list, Flight options and log pagination, and MotherDuck for the AI builders.

Known Limitations

FeatureStatus
Basic CRUD operationsFull support
Joins and subqueriesFull support
TransactionsNo savepoints (nested transactions reuse the outer one). Config is ignored
JSON/JSONB columnsUse duckDbJson() instead
Prepared statementsPrepared on every run. No statement cache and no named statements
Streaming resultsChunked reads via executeBatches(), no cursor streaming
Concurrent queriesOne query per connection. Use pooling for parallelism

See Limitations for details.

Examples

Run them from the repository root:

bun example/analytics-dashboard.ts
MOTHERDUCK_TOKEN=your_token bun example/motherduck-nyc-taxi.ts

See example/README.md for the full list.

Contributing

Contributions are welcome. See CONTRIBUTING.md for the guide and SECURITY.md to report a vulnerability.

bun install      # install dependencies
bun run test     # run tests (Vitest, not `bun test`)
bun run t        # watch mode with the UI
bun run build    # build dist/

Include tests for new features in test/<feature>.test.ts, note any DuckDB quirks you hit, and use short imperative commit messages.

License

Apache-2.0

版本与发布记录

@duckdbfan/drizzle-duckdb 共发布 45 个版本,首次发布于 2025/03/18;过去 12 个月发布了 38 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.5.0latest2026/11/103 天前
2.4.02026/11/094 天前
2.3.02026/11/0211 天前
2.2.02026/10/3014 天前
2.1.22026/10/2915 天前
2.1.12026/10/2321 天前

关于 @duckdbfan/drizzle-duckdb 的常见问题

@duckdbfan/drizzle-duckdb 是什么?

A drizzle ORM client for use with DuckDB. Based on drizzle's Postgres client.

如何安装 @duckdbfan/drizzle-duckdb?

在项目目录运行 npm install @duckdbfan/drizzle-duckdb,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:drizzle-orm(>=0.40.1 <0.46.0)、@duckdb/node-api(>=1.4.4 <1.6.0 || >=1.4.4-r.1 <1.4.5 || >=1.4.5-r.1 <1.4.6 || >=1.5.0-r.1 <1.5.1 || >=1.5.1-r.1 <1.5.2 || >=1.5.2-r.1 <1.5.3 || >=1.5.3-r.1 <1.5.4 || >=1.5.4-r.1 <1.5.5 || >=1.5.5-r.1 <1.5.6 || >=1.5.6-r.1 <1.5.7)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。它还提供命令行工具 duckdb-introspect,可以用 npx duckdb-introspect 直接运行。

@duckdbfan/drizzle-duckdb 支持 TypeScript 吗?

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

@duckdbfan/drizzle-duckdb 支持 ESM 还是 CommonJS?

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

@duckdbfan/drizzle-duckdb 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18.17。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@duckdbfan/drizzle-duckdb 可以商用吗?

@duckdbfan/drizzle-duckdb 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@duckdbfan/drizzle-duckdb 的下载量有多少?

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

@duckdbfan/drizzle-duckdb 还在维护吗?

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