Skip to main content
doc0blade47/drizzle-ormdocumentation home
Sign in

Overview

Last updated Oct 12, 2026
Relevant source files

The following files were used as context for generating this wiki page:

Overview

Drizzle ORM is a lightweight, high-performance, TypeScript-first database toolkit engineered with a headless architecture that decouples declarative schema definitions and query building logic from underlying database driver implementations. Operating across a diverse ecosystem of relational database engines including PostgreSQL, MySQL, SQLite, and Gel, the toolkit targets modern serverless, edge, and containerized runtime environments without imposing heavy runtime abstractions or native dependency bloat. Sources: drizzle-orm/package.json:4-41, drizzle-orm/src/singlestore/driver.ts:1-184

The architecture supports varied execution targets spanning standard Node.js database pools, HTTP and WebSocket-based serverless protocols, and specialized embedded environments such as Cloudflare D1 workers, Durable Objects storage, and native SQLite bindings. Through tight integration with CLI Command Architecture and validation utilities, Drizzle coordinates schema management, migration diffing, and type-safe query compilation across a unified monorepo workspace structure. Sources: drizzle-kit/src/cli/index.ts:1-46, pnpm-workspace.yaml:1-10

Headless Design and Monorepo Philosophy

Workspace Structure and Package Boundaries

The project organizes its codebase within a multi-package pnpm workspace coordinated by pnpm-workspace.yaml. The workspace decouples core ORM functionality, migration tooling, seed services, and schema validation wrappers into dedicated packages. Sources: pnpm-workspace.yaml:1-10

Workspace PackageDirectoryRole and Responsibility
drizzle-ormdrizzle-ormCore query builder, table/column models, dialects, and session abstractions
drizzle-kitdrizzle-kitCLI command architecture, database introspection, migrations, and Studio Server Bridge
drizzle-zoddrizzle-zodAutomatic generation of Zod validation schemas from table definitions
drizzle-typeboxdrizzle-typeboxJSON Schema generation via Sinclair's TypeBox library
drizzle-valibotdrizzle-valibotLightweight Valibot validation schema generator
drizzle-arktypedrizzle-arktypeRuntime validation definitions inferred via ArkType
drizzle-seeddrizzle-seedMock data generation and foreign key topological insertion ordering
integration-testsintegration-testsCross-dialect test suite executed against containerized database fixtures
eslint-plugin-drizzleeslint-plugin-drizzleAST lint rules enforcing safe delete and update query constraints

Sources: pnpm-workspace.yaml:1-10

Note

Workspace packages maintain strict separation of concerns, allowing runtime validation libraries (drizzle-zod, drizzle-typebox, drizzle-valibot, drizzle-arktype) to operate independently as optional peer or downstream dependencies atop the core drizzle-orm engine.

Driver Decoupling and Peer Dependencies

The core drizzle-orm package enforces a headless design by isolating native database client runtimes into optional peer dependencies. Rather than bundling heavy native binaries or tight vendor connections directly into the bundle, drizzle-orm declares drivers via peerDependencies combined with peerDependenciesMeta set to optional. Sources: drizzle-orm/package.json:47-169

"peerDependenciesMeta": {
	"mysql2": {
		"optional": true
	},
	"@vercel/postgres": {
		"optional": true
	},
	"@xata.io/client": {
		"optional": true
	},
	"better-sqlite3": {
		"optional": true
	},
	"@types/better-sqlite3": {
		"optional": true
	},
	"sqlite3": {
		"optional": true
	},
	"sql.js": {
		"optional": true
	},
	"@types/sql.js": {
		"optional": true
	},
	"@cloudflare/workers-types": {
		"optional": true
	},
	"pg": {
		"optional": true
	},
	"@types/pg": {
		"optional": true
	},
	"postgres": {
		"optional": true
	},
	"@neondatabase/serverless": {
		"optional": true
	},
	"@netlify/db": {
		"optional": true
	},
	"bun-types": {
		"optional": true
	},
	"@aws-sdk/client-rds-data": {
		"optional": true
	},
	"@planetscale/database": {
		"optional": true
	},
	"knex": {
		"optional": true
	},
	"kysely": {
		"optional": true
	},
	"@libsql/client": {
		"optional": true
	},
	"@libsql/client-wasm": {
		"optional": true
	},
	"@opentelemetry/api": {
		"optional": true
	},
	"expo-sqlite": {
		"optional": true
	},
	"gel": {
		"optional": true
	},
	"@op-engineering/op-sqlite": {
		"optional": true
	},
	"@electric-sql/pglite": {
		"optional": true
	},
	"@tidbcloud/serverless": {

Sources: drizzle-orm/package.json:78-169

Important

Because drivers such as pg, mysql2, better-sqlite3, and @neondatabase/serverless are marked as optional peer dependencies, consumers load only the specific client required by their target runtime, keeping bundle footprints minimal across serverless and edge deployments.

Database Engine and Dialect Support

PostgreSQL, PGlite, and Postgres-js Drivers

Drizzle ORM provides first-class support for PostgreSQL through specialized dialect compilation in PgDialect and dedicated session handlers. The postgres-js driver connects via the postgres package, configuring transparent parsers for PostgreSQL data types (such as OIDs 1184, 1082, 1083, 1114, 1182, 1185, 1115, 1231, 114, and 3802) to bypass unexpected transformations on dates and JSON fields. Sources: drizzle-orm/src/postgres-js/driver.ts:1-38

const transparentParser = (val: any) => val;
 
// Override postgres.js default date parsers: https://github.com/porsager/postgres/discussions/761
for (const type of ['1184', '1082', '1083', '1114', '1182', '1185', '1115', '1231']) {
	client.options.parsers[type as any] = transparentParser;
	client.options.serializers[type as any] = transparentParser;
}
client.options.serializers['114'] = transparentParser;
client.options.serializers['3802'] = transparentParser;

Sources: drizzle-orm/src/postgres-js/driver.ts:28-36

Additionally, embedded PostgreSQL is supported via PGlite through @electric-sql/pglite, handling local data directories and client instances within PgliteDriver and PgliteDatabase. Sources: drizzle-orm/src/pglite/driver.ts:1-47

Note

The postgres-js driver explicitly overrides default date and json parsers by assigning a transparent identity parser (val => val) to ensure raw wire formats pass directly into Drizzle's type casting layer without premature serialization.

MySQL2 and SQLite Engine Adaptations

For MySQL environments, the mysql2 driver abstracts connection pools and individual client connections using MySql2Driver and MySql2Database. It inspects client instances to verify whether they provide a callback or promise interface, automatically invoking .promise() on callback-based clients to normalize asynchronous execution. Sources: drizzle-orm/src/mysql2/driver.ts:1-120

const clientForInstance = isCallbackClient(client) ? client.promise() : client;

Sources: drizzle-orm/src/mysql2/driver.ts:77-77

SQLite dialects target diverse runtimes, ranging from Node.js bindings like better-sqlite3 and Bun's built-in bun:sqlite to edge-native targets such as Cloudflare D1 databases (D1Database) and Cloudflare Durable Objects storage (DurableObjectStorage). Sources: drizzle-orm/type-tests/sqlite/db.ts:1-16

Warning

When providing a schema configuration alongside the mysql2 driver, you must explicitly specify the mode property as either 'planetscale' or 'default' to avoid runtime configuration errors. Sources: drizzle-orm/src/mysql2/driver.ts:80-86

Gel Database Integration

Drizzle extends its dialect breadth to Gel via GelDialect, GelDriver, and GelJsDatabase, bridging the Gel client ecosystem (gel) into standard Drizzle query building and relational session semantics. Sources: drizzle-orm/src/gel/driver.ts:1-47

Driver ModuleTarget Engine / ClientPrimary Artifacts
postgres-jsPostgreSQL (postgres)PostgresJsDatabase, PostgresJsSession, postgres client
pgliteEmbedded PostgreSQL (@electric-sql/pglite)PgliteDatabase, PgliteSession, PGlite client
mysql2MySQL / PlanetScale (mysql2)MySql2Database, MySql2Session, Pool/Connection
better-sqlite3 / bun-sqliteSQLite (Node / Bun)BetterSQLite3Database, BunSQLiteDatabase
d1 / durable-sqliteCloudflare Workers & Durable ObjectsD1Database, DurableObjectStorage wrappers
gelGel DB (gel)GelJsDatabase, GelDriver, GelClient

Sources: drizzle-orm/src/gel/driver.ts:1-47, drizzle-orm/src/mysql2/driver.ts:1-68, drizzle-orm/src/pglite/driver.ts:1-47, drizzle-orm/src/postgres-js/driver.ts:1-38, drizzle-orm/type-tests/sqlite/db.ts:1-16

Caution

Calling drizzle.mock() on dialect drivers returns a mock database instance where $client is either uninitialized or set to a placeholder string (e.g. '$client is not available on drizzle.mock()'), preventing accidental production queries from executing against stubbed connections. Sources: drizzle-orm/src/gel/driver.ts:131-138, drizzle-orm/src/pglite/driver.ts:153-160, drizzle-orm/src/postgres-js/driver.ts:120-132

Serverless and Edge Runtimes

Cloudflare Durable Objects and Bun Integrations

Drizzle provides dedicated database driver modules tailored for modern serverless and edge computing environments, including Cloudflare Durable Objects and the Bun runtime. For Cloudflare Durable Objects, the durable-sqlite driver exports DrizzleSqliteDODatabase alongside a drizzle initialization function that accepts a DurableObjectStorage client instance and a DrizzleConfig object, configuring a synchronous SQLite dialect (SQLiteSyncDialect) and a SQLiteDOSession without requiring manual polling or network roundtrips. Sources: drizzle-orm/src/durable-sqlite/driver.ts:16-60

Similarly, the Bun ecosystem is supported through two specialized driver packages: bun-sqlite and bun-sql. The bun-sqlite driver builds upon Bun's native bun:sqlite engine by wrapping Database instances into BunSQLiteDatabase, supporting flexible connection options such as readonly, create, and readwrite flags. The bun-sql driver targets Bun's PostgreSQL capabilities, instantiating BunSQLDatabase instances over Bun's native SQL client and automatically wiring query parsers, serializers, and caching hooks. Sources: drizzle-orm/src/bun-sqlite/driver.ts:17-152, drizzle-orm/src/bun-sql/driver.ts:19-125

Note

When initializing drizzle with bun-sqlite or bun-sql, invoking drizzle.mock() constructs a stubbed database instance where the $client property is assigned either a placeholder object with empty option maps or an uninitialized handle, keeping test mocks completely isolated from native runtime bindings. Sources: drizzle-orm/src/bun-sqlite/driver.ts:145-152, drizzle-orm/src/bun-sql/driver.ts:113-125

Neon Serverless and Vercel Postgres Protocols

Serverless PostgreSQL deployments across Neon and Vercel Postgres rely on lightweight HTTP and WebSocket connection managers that bypass traditional persistent connection pools. The Neon serverless driver package provides two distinct client modes: WebSocket-driven connection pooling via NeonDriver and Pool configurations from @neondatabase/serverless, and HTTP-based stateless querying via NeonHttpDriver and neon() query functions. The HTTP driver initializes explicit type parsers for PostgreSQL temporal and geometric types—such as TIMESTAMPTZ, TIMESTAMP, DATE, and INTERVAL—ensuring raw string representations are preserved across serverless boundaries. Sources: drizzle-orm/src/neon-serverless/driver.ts:18-41, drizzle-orm/src/neon-http/driver.ts:15-51

Vercel Postgres integrates similarly through the vercel-postgres driver, which wraps the @vercel/postgres sql client into VercelPgDatabase instances and supports optional caching layers and custom logging through VercelPgDriver. Both Neon HTTP and Vercel Postgres driver configurations accept schema definitions, extraction helpers, and custom cache invalidation callbacks (onMutate) directly within their initialization objects. Sources: drizzle-orm/src/vercel-postgres/driver.ts:17-85, drizzle-orm/src/neon-http/driver.ts:124-169

Important

The NeonHttpDatabase class exposes a $withAuth(token) method that returns a proxied database instance intercepting query execution and with clauses to dynamically inject fine-grained authentication tokens into Neon HTTP requests. Sources: drizzle-orm/src/neon-http/driver.ts:80-112

Serverless Driver ModuleTarget Protocol / Client SDKPrimary Database ClassKey Configuration Options
durable-sqliteCloudflare Durable Objects (DurableObjectStorage)DrizzleSqliteDODatabaseclient, schema, casing, logger
bun-sqliteBun Native SQLite (bun:sqlite)BunSQLiteDatabaseconnection (string/object with readonly, create, readwrite), client, schema
bun-sqlBun Native PostgreSQL (bun)BunSQLDatabaseconnection (string/object with URL & SQLOptions), client, schema
neon-serverlessNeon WebSocket / Pool (@neondatabase/serverless)NeonDatabaseconnection (string/PoolConfig), client, ws, cache, logger
neon-httpNeon HTTP Query (@neondatabase/serverless)NeonHttpDatabaseconnection (string/HTTPTransactionOptions), client, cache, logger
vercel-postgresVercel Postgres (@vercel/postgres)VercelPgDatabaseclient, cache, logger, casing

Sources: drizzle-orm/src/durable-sqlite/driver.ts:16-55, drizzle-orm/src/bun-sqlite/driver.ts:17-124, drizzle-orm/src/bun-sql/driver.ts:19-95, drizzle-orm/src/neon-serverless/driver.ts:43-111, drizzle-orm/src/neon-http/driver.ts:80-208, drizzle-orm/src/vercel-postgres/driver.ts:42-108

Caution

When configuring the Neon serverless driver via an options object, providing a ws property automatically overrides the global neonConfig.webSocketConstructor constructor for all underlying WebSocket connections. Sources: drizzle-orm/src/neon-serverless/driver.ts:124-134

Unified LibSQL Transport Adapters

LibSQL Driver Modularity

Drizzle ORM provides a modular set of entrypoints for LibSQL, decoupling database operations from specific client bindings across seven dedicated transport packages. Each entrypoint exports a specialized drizzle initialization function that accepts either a connection string, a pre-configured client instance, or a unified configuration object containing connection parameters and schema definitions.

export function drizzle<
	TSchema extends Record<string, unknown> = Record<string, never>,
	TClient extends Client = Client,
>(
	...params: [
		TClient | string,
	] | [
		TClient | string,
		DrizzleConfig<TSchema>,
	] | [
		(
			& DrizzleConfig<TSchema>
			& ({
				connection: string | Config;
			} | {
				client: TClient;
			})
		),
	]
): LibSQLDatabase<TSchema> & {

Sources: drizzle-orm/src/libsql/driver.ts:7-26

The initialization function handles three distinct parameter signatures: passing a connection string directly, passing a configuration object with a connection string or Config object or an existing client instance, or passing a pre-instantiated client directly alongside an optional DrizzleConfig object.

	if (typeof params[0] === 'string') {
		const instance = createClient({
			url: params[0],
		});
 
		return construct(instance, params[1]) as any;
	}
 
	if (isConfig(params[0])) {
		const { connection, client, ...drizzleConfig } = params[0] as
			& { connection?: Config; client?: TClient }
			& DrizzleConfig<TSchema>;
 
		if (client) return construct(client, drizzleConfig) as any;
 
		const instance = typeof connection === 'string' ? createClient({ url: connection }) : createClient(connection!);
 
		return construct(instance, drizzleConfig) as any;
	}
 
	return construct(params[0] as TClient, params[1] as DrizzleConfig<TSchema> | undefined) as any;
}

Sources: drizzle-orm/src/libsql/http/index.ts:27-48

Note

All LibSQL driver entrypoints export a static drizzle.mock() helper method that constructs a type-safe LibSQLDatabase instance without binding to a live client, assigning $client the literal type string '$client is not available on drizzle.mock()'. Sources: drizzle-orm/src/libsql/http/index.ts:50-57, drizzle-orm/src/libsql/node/index.ts:50-57, drizzle-orm/src/libsql/sqlite3/index.ts:50-57, drizzle-orm/src/libsql/driver.ts:52-59, drizzle-orm/src/libsql/web/index.ts:50-57, drizzle-orm/src/libsql/wasm/index.ts:50-57, drizzle-orm/src/libsql/ws/index.ts:50-57

Transport Module PathUnderlying Package ImportTarget Environment / Protocol
drizzle-orm/libsql@libsql/clientDefault / Generic LibSQL Client
drizzle-orm/libsql/node@libsql/client/nodeNode.js native bindings
drizzle-orm/libsql/http@libsql/client/httpHTTP protocol serverless transport
drizzle-orm/libsql/ws@libsql/client/wsWebSocket protocol serverless transport
drizzle-orm/libsql/web@libsql/client/webWeb standard fetch environments
drizzle-orm/libsql/wasm@libsql/client-wasmWebAssembly SQLite runtime
drizzle-orm/libsql/sqlite3@libsql/client/sqlite3Native sqlite3 driver bindings

Sources: drizzle-orm/src/libsql/http/index.ts:1, drizzle-orm/src/libsql/node/index.ts:1, drizzle-orm/src/libsql/sqlite3/index.ts:1, drizzle-orm/src/libsql/driver.ts:1, drizzle-orm/src/libsql/web/index.ts:1, drizzle-orm/src/libsql/wasm/index.ts:1, drizzle-orm/src/libsql/ws/index.ts:1

Tooling Ecosystem and Schema Coordination

CLI Commands and Schema Management

Drizzle Kit orchestrates schema generation, migration lifecycle management, database inspection, and local studio hosting through a set of CLI commands defined using @drizzle-team/brocli. Each command validates inputs, enforces version compatibility with drizzle-orm, and dispatches dialect-specific handlers across PostgreSQL, MySQL, SQLite, Turso, SingleStore, and Gel.

CLI CommandDescription / ActionTarget Dialects / Handlers
generatePrepares migration files and differential schemaspostgresql, mysql, sqlite, turso, singlestore
dropRemoves the most recent migration file from the output folderValidated against V1 output directory layout
studioLaunches local Drizzle Studio server with TLS certificatespostgresql, mysql, sqlite, turso, singlestore (Gel throws error)
exportGenerates a raw SQL diff between the current and empty statepostgresql, mysql, sqlite, turso, singlestore

Sources: drizzle-kit/src/cli/schema.ts:50-67, drizzle-kit/src/cli/schema.ts:633-650, drizzle-kit/src/cli/schema.ts:652-805, drizzle-kit/src/cli/schema.ts:807-856

Warning

Attempting to execute the studio or export commands with the gel dialect will cause the CLI to log an error message via error() and immediately terminate process execution with process.exit(1). Sources: drizzle-kit/src/cli/schema.ts:743-750, drizzle-kit/src/cli/schema.ts:845-852

Driver Interoperability and Runtime Checks

The tooling and runtime packages coordinate closely to ensure proper driver wiring. For example, Netlify DB initialization inspects connection parameters to select between serverless Neon HTTP/Pool configurations and native Node.js Postgres pools, automatically mapping built-in types such as TIMESTAMPTZ, TIMESTAMP, DATE, and INTERVAL.

	initMappers() {
		types.setTypeParser(types.builtins.TIMESTAMPTZ, (val: any) => val);
		types.setTypeParser(types.builtins.TIMESTAMP, (val: any) => val);
		types.setTypeParser(types.builtins.DATE, (val: any) => val);
		types.setTypeParser(types.builtins.INTERVAL, (val: any) => val);
		types.setTypeParser(1231, (val: any) => val);
		types.setTypeParser(1115, (val: any) => val);
		types.setTypeParser(1185, (val: any) => val);
		types.setTypeParser(1187, (val: any) => val);
		types.setTypeParser(1182, (val: any) => val);
	}
}

Sources: drizzle-orm/src/netlify-db/driver.ts:58-69

Note

When starting Drizzle Studio with specific underlying drivers such as aws-data-api or pglite, the CLI verifies that the installed drizzle-orm package meets minimum version thresholds (> 0.30.10 and > 0.30.6 respectively) before allowing the server to start. Sources: drizzle-kit/src/cli/schema.ts:691-712

Where to go next

I want to…Read
Walk through minimal, copy-pasteable examples to declare schemas, establish a connection with popular drivers, execute type-safe queries, and apply migrations.Quick Start
Navigate the monorepo directory layout, understanding the boundary and responsibility of drizzle-orm, drizzle-kit, drizzle-seed, validation wrappers, and integration tests.Project Structure
How raw SQL expressions, parameterized chunks, dialect-aware operators, condition trees, and SQL functions are constructed and safely parameterized.SQL Template Engine
How table definitions, column builder abstractions, primary keys, indexes, foreign keys, aliases, and naming conventions are implemented and inferred across dialects.Table and Column Models
How the Relational Query Builder (RQB) parses declarative relation definitions (1:1, 1:N, M:N), models nested graph queries, and builds consolidated execution payloads.Relational Query Engine
How core query builders, Select/Insert/Update/Delete base abstractions, thenable query promises, and subquery wrappers compile high-level operations into executable ASTs.Query Builder Foundation
How database sessions, driver connection wrappers, transaction semantics, savepoints, batch execution, and migration runners coordinate across asynchronous runtimes.Sessions and Transactions
How query result caching interfaces are structured and integrated with external distributed cache stores such as Upstash Redis.Query Caching
How query execution logging, OpenTelemetry-compatible spans, tracer hooks, and diagnostic telemetry are wired through internal query execution paths.Logging and Tracing
How to define schemas, tables, standard columns, PostGIS geometry, pgvector types, sequences, check constraints, indexes, unique constraints, and row-level security policies in PostgreSQL.Dialects And Schema Schema Definition
How PostgreSQL-specific dialect compilation, select/insert/update/delete operations, returning clauses, conflict resolution (upsert), and materialized view refreshes are implemented.Dialects And Schema Query Builders
How HTTP and WebSocket-based serverless PostgreSQL clients (Neon HTTP/Serverless, Supabase, Vercel Postgres, AWS Data API, Netlify DB, and Xata HTTP) maintain connectionless or pooled execution.Drivers And Runtimes
How Drizzle operates inside Cloudflare D1 workers, Durable Objects storage, Expo SQLite mobile environments, and OP-SQLite on React Native.Edge and Mobile SQLite
How Drizzle schemas and sessions integrate with Prisma client instances, Knex query runners, and Kysely adapters for incremental migrations.Knex Kysely and Prisma Interop
How drizzle-kit parses CLI arguments, dispatches migrate, check, drop, and up commands, prompts interactive choices, and displays formatted terminal output.CLI Command Architecture
How TypeScript schema definitions are serialized into normalized JSON migration snapshots and journals across PostgreSQL, MySQL, SQLite, SingleStore, and Gel.Migration Toolkit Schema
How live database catalogs (information schema, system tables, pragma statements) are inspected to reverse-engineer Drizzle schema code for all supported engines.Database Introspection
How drizzle-kit serves Drizzle Studio locally, provisions TLS certificates, exposes schema metadata, and proxies query inspection over a local HTTP server.Studio Server Bridge
How drizzle.config.ts files are parsed, validated, and normalized for dialect options, connection parameters, extensions, and schema glob paths.Configuration and Validations
How to automatically generate Zod schemas from Drizzle table definitions, customize insert/select schemas, refine constraints, and validate forms.Drizzle Zod Integration
How JSON Schema validation objects are derived from Drizzle column types using Sinclair's TypeBox library.Drizzle TypeBox Integration
How modular and lightweight Valibot validation schemas are automatically generated from Drizzle ORM table definitions.Drizzle Valibot Integration
How ArkType runtime validation definitions are inferred from database table schemas.Drizzle ArkType Integration
How drizzle-seed inspects database schemas, orders insertion sequences respecting foreign key topological dependencies, and seeds mock records.Seed Service Engine
How realistic mock data (names, addresses, jobs, lorem ipsum, phone numbers) and weighted distribution generators produce mock values for column types.Seed Data Generators
How AST lint rules enforce safety practices, such as requiring WHERE clauses on delete and update queries to avoid accidental whole-table wipes.ESLint Plugin Drizzle
How Turborepo, Rollup, tsup, and custom fix-imports scripts coordinate package bundling, ESM/CJS exports, and bundle size constraints.Monorepo Build Pipeline
How Vitest, Docker containers, SST cloud fixtures, and real database drivers run cross-dialect integration tests across MySQL, PostgreSQL, SQLite, and SingleStore.Integration Test Harness
How Drizzle ORM verifies compile-time type inference, relational join typing, strict-null checks, and prevents regressions across TypeScript versions.Type System Verification
Was this page helpful?