# blade47/drizzle-orm Wiki
## Technical docs: Overview
URL: https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/getting-started/overview
Relevant source files
The following files were used as context for generating this wiki page:
- [drizzle-kit/src/api.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/api.ts)
- [drizzle-orm/package.json](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/package.json)
- [drizzle-kit/src/serializer/studio.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/serializer/studio.ts)
- [drizzle-kit/src/cli/connections.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/cli/connections.ts)
- [drizzle-orm/src/libsql/http/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/http/index.ts)
- [drizzle-orm/src/gel/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel/driver.ts)
- [drizzle-orm/src/pglite/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pglite/driver.ts)
- [drizzle-orm/src/libsql/node/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/node/index.ts)
- [drizzle-orm/src/durable-sqlite/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/durable-sqlite/driver.ts)
- [drizzle-orm/src/libsql/sqlite3/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/sqlite3/index.ts)
- [drizzle-kit/src/cli/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/cli/index.ts)
- [drizzle-orm/src/libsql/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/driver.ts)
- [drizzle-orm/src/libsql/web/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/web/index.ts)
- [drizzle-orm/src/libsql/wasm/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/wasm/index.ts)
- [drizzle-orm/src/libsql/ws/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/ws/index.ts)
- [drizzle-orm/src/netlify-db/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/netlify-db/driver.ts)
- [pnpm-workspace.yaml](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/pnpm-workspace.yaml)
- [drizzle-orm/src/neon-serverless/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-serverless/driver.ts)
- [drizzle-orm/src/bun-sqlite/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/bun-sqlite/driver.ts)
- [drizzle-kit/src/cli/schema.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/cli/schema.ts)
- [drizzle-orm/src/bun-sql/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/bun-sql/driver.ts)
- [drizzle-orm/type-tests/sqlite/db.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/sqlite/db.ts)
- [drizzle-orm/src/neon-http/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-http/driver.ts)
- [drizzle-orm/src/mysql2/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql2/driver.ts)
- [drizzle-orm/src/postgres-js/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/postgres-js/driver.ts)
- [drizzle-orm/src/vercel-postgres/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/vercel-postgres/driver.ts)
- [drizzle-orm/src/singlestore/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore/driver.ts)
- [drizzle-orm/type-tests/geldb/db.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/geldb/db.ts)
- [turbo.json](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/turbo.json)
- [drizzle-orm/src/d1/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/d1/index.ts)
## 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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/package.json#L4-L41), [drizzle-orm/src/singlestore/driver.ts:1-184](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore/driver.ts#L1-L184)
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](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/migration-toolkit/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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/cli/index.ts#L1-L46), [pnpm-workspace.yaml:1-10](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/pnpm-workspace.yaml#L1-L10)
## 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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/pnpm-workspace.yaml#L1-L10)
| Workspace Package | Directory | Role and Responsibility |
| :--- | :--- | :--- |
| `drizzle-orm` | `drizzle-orm` | Core query builder, table/column models, dialects, and session abstractions |
| `drizzle-kit` | `drizzle-kit` | CLI command architecture, [database introspection](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/migration-toolkit/database-introspection), migrations, and [Studio Server Bridge](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/migration-toolkit/studio-server-bridge) |
| `drizzle-zod` | `drizzle-zod` | Automatic generation of Zod validation schemas from table definitions |
| `drizzle-typebox` | `drizzle-typebox` | JSON Schema generation via Sinclair's TypeBox library |
| `drizzle-valibot` | `drizzle-valibot` | Lightweight Valibot validation schema generator |
| `drizzle-arktype` | `drizzle-arktype` | Runtime validation definitions inferred via ArkType |
| `drizzle-seed` | `drizzle-seed` | Mock data generation and foreign key topological insertion ordering |
| `integration-tests` | `integration-tests` | Cross-dialect test suite executed against containerized database fixtures |
| `eslint-plugin-drizzle` | `eslint-plugin-drizzle` | AST lint rules enforcing safe delete and update query constraints |
Sources: [pnpm-workspace.yaml:1-10](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/pnpm-workspace.yaml#L1-L10)
> [!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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/package.json#L47-L169)
```json
"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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/package.json#L78-L169)
> [!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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/postgres-js/driver.ts#L1-L38)
```typescript
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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/postgres-js/driver.ts#L28-L36)
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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pglite/driver.ts#L1-L47)
> [!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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql2/driver.ts#L1-L120)
```typescript
const clientForInstance = isCallbackClient(client) ? client.promise() : client;
```
Sources: [drizzle-orm/src/mysql2/driver.ts:77-77](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql2/driver.ts#L77-L77)
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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/sqlite/db.ts#L1-L16)
> [!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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql2/driver.ts#L80-L86)
### 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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel/driver.ts#L1-L47)
| Driver Module | Target Engine / Client | Primary Artifacts |
| :--- | :--- | :--- |
| `postgres-js` | PostgreSQL (`postgres`) | `PostgresJsDatabase`, `PostgresJsSession`, `postgres` client |
| `pglite` | Embedded PostgreSQL (`@electric-sql/pglite`) | `PgliteDatabase`, `PgliteSession`, `PGlite` client |
| `mysql2` | MySQL / PlanetScale (`mysql2`) | `MySql2Database`, `MySql2Session`, Pool/Connection |
| `better-sqlite3` / `bun-sqlite` | SQLite (Node / Bun) | `BetterSQLite3Database`, `BunSQLiteDatabase` |
| `d1` / `durable-sqlite` | Cloudflare Workers & Durable Objects | `D1Database`, `DurableObjectStorage` wrappers |
| `gel` | Gel DB (`gel`) | `GelJsDatabase`, `GelDriver`, `GelClient` |
Sources: [drizzle-orm/src/gel/driver.ts:1-47](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel/driver.ts#L1-L47), [drizzle-orm/src/mysql2/driver.ts:1-68](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql2/driver.ts#L1-L68), [drizzle-orm/src/pglite/driver.ts:1-47](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pglite/driver.ts#L1-L47), [drizzle-orm/src/postgres-js/driver.ts:1-38](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/postgres-js/driver.ts#L1-L38), [drizzle-orm/type-tests/sqlite/db.ts:1-16](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/sqlite/db.ts#L1-L16)
> [!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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel/driver.ts#L131-L138), [drizzle-orm/src/pglite/driver.ts:153-160](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pglite/driver.ts#L153-L160), [drizzle-orm/src/postgres-js/driver.ts:120-132](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/postgres-js/driver.ts#L120-L132)
## 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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/durable-sqlite/driver.ts#L16-L60)
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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/bun-sqlite/driver.ts#L17-L152), [drizzle-orm/src/bun-sql/driver.ts:19-125](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/bun-sql/driver.ts#L19-L125)
> [!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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/bun-sqlite/driver.ts#L145-L152), [drizzle-orm/src/bun-sql/driver.ts:113-125](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/bun-sql/driver.ts#L113-L125)
### 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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-serverless/driver.ts#L18-L41), [drizzle-orm/src/neon-http/driver.ts:15-51](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-http/driver.ts#L15-L51)
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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/vercel-postgres/driver.ts#L17-L85), [drizzle-orm/src/neon-http/driver.ts:124-169](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-http/driver.ts#L124-L169)
> [!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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-http/driver.ts#L80-L112)
| Serverless Driver Module | Target Protocol / Client SDK | Primary Database Class | Key Configuration Options |
| :--- | :--- | :--- | :--- |
| `durable-sqlite` | Cloudflare Durable Objects (`DurableObjectStorage`) | `DrizzleSqliteDODatabase` | `client`, `schema`, `casing`, `logger` |
| `bun-sqlite` | Bun Native SQLite (`bun:sqlite`) | `BunSQLiteDatabase` | `connection` (string/object with `readonly`, `create`, `readwrite`), `client`, `schema` |
| `bun-sql` | Bun Native PostgreSQL (`bun`) | `BunSQLDatabase` | `connection` (string/object with URL & `SQLOptions`), `client`, `schema` |
| `neon-serverless` | Neon WebSocket / Pool (`@neondatabase/serverless`) | `NeonDatabase` | `connection` (string/`PoolConfig`), `client`, `ws`, `cache`, `logger` |
| `neon-http` | Neon HTTP Query (`@neondatabase/serverless`) | `NeonHttpDatabase` | `connection` (string/`HTTPTransactionOptions`), `client`, `cache`, `logger` |
| `vercel-postgres` | Vercel Postgres (`@vercel/postgres`) | `VercelPgDatabase` | `client`, `cache`, `logger`, `casing` |
Sources: [drizzle-orm/src/durable-sqlite/driver.ts:16-55](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/durable-sqlite/driver.ts#L16-L55), [drizzle-orm/src/bun-sqlite/driver.ts:17-124](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/bun-sqlite/driver.ts#L17-L124), [drizzle-orm/src/bun-sql/driver.ts:19-95](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/bun-sql/driver.ts#L19-L95), [drizzle-orm/src/neon-serverless/driver.ts:43-111](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-serverless/driver.ts#L43-L111), [drizzle-orm/src/neon-http/driver.ts:80-208](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-http/driver.ts#L80-L208), [drizzle-orm/src/vercel-postgres/driver.ts:42-108](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/vercel-postgres/driver.ts#L42-L108)
> [!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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-serverless/driver.ts#L124-L134)
## 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.
```typescript
export function drizzle<
TSchema extends Record = Record,
TClient extends Client = Client,
>(
...params: [
TClient | string,
] | [
TClient | string,
DrizzleConfig,
] | [
(
& DrizzleConfig
& ({
connection: string | Config;
} | {
client: TClient;
})
),
]
): LibSQLDatabase & {
```
Sources: [drizzle-orm/src/libsql/driver.ts:7-26](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/driver.ts#L7-L26)
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.
```typescript
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;
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 | undefined) as any;
}
```
Sources: [drizzle-orm/src/libsql/http/index.ts:27-48](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/http/index.ts#L27-L48)
> [!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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/http/index.ts#L50-L57), [drizzle-orm/src/libsql/node/index.ts:50-57](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/node/index.ts#L50-L57), [drizzle-orm/src/libsql/sqlite3/index.ts:50-57](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/sqlite3/index.ts#L50-L57), [drizzle-orm/src/libsql/driver.ts:52-59](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/driver.ts#L52-L59), [drizzle-orm/src/libsql/web/index.ts:50-57](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/web/index.ts#L50-L57), [drizzle-orm/src/libsql/wasm/index.ts:50-57](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/wasm/index.ts#L50-L57), [drizzle-orm/src/libsql/ws/index.ts:50-57](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/ws/index.ts#L50-L57)
| Transport Module Path | Underlying Package Import | Target Environment / Protocol |
| :--- | :--- | :--- |
| `drizzle-orm/libsql` | `@libsql/client` | Default / Generic LibSQL Client |
| `drizzle-orm/libsql/node` | `@libsql/client/node` | Node.js native bindings |
| `drizzle-orm/libsql/http` | `@libsql/client/http` | HTTP protocol serverless transport |
| `drizzle-orm/libsql/ws` | `@libsql/client/ws` | WebSocket protocol serverless transport |
| `drizzle-orm/libsql/web` | `@libsql/client/web` | Web standard fetch environments |
| `drizzle-orm/libsql/wasm` | `@libsql/client-wasm` | WebAssembly SQLite runtime |
| `drizzle-orm/libsql/sqlite3` | `@libsql/client/sqlite3` | Native `sqlite3` driver bindings |
Sources: [drizzle-orm/src/libsql/http/index.ts:1](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/http/index.ts#L1), [drizzle-orm/src/libsql/node/index.ts:1](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/node/index.ts#L1), [drizzle-orm/src/libsql/sqlite3/index.ts:1](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/sqlite3/index.ts#L1), [drizzle-orm/src/libsql/driver.ts:1](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/driver.ts#L1), [drizzle-orm/src/libsql/web/index.ts:1](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/web/index.ts#L1), [drizzle-orm/src/libsql/wasm/index.ts:1](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/wasm/index.ts#L1), [drizzle-orm/src/libsql/ws/index.ts:1](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/ws/index.ts#L1)
## 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 Command | Description / Action | Target Dialects / Handlers |
| :--- | :--- | :--- |
| `generate` | Prepares migration files and differential schemas | `postgresql`, `mysql`, `sqlite`, `turso`, `singlestore` |
| `drop` | Removes the most recent migration file from the output folder | Validated against V1 output directory layout |
| `studio` | Launches local Drizzle Studio server with TLS certificates | `postgresql`, `mysql`, `sqlite`, `turso`, `singlestore` (Gel throws error) |
| `export` | Generates a raw SQL diff between the current and empty state | `postgresql`, `mysql`, `sqlite`, `turso`, `singlestore` |
Sources: [drizzle-kit/src/cli/schema.ts:50-67](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/cli/schema.ts#L50-L67), [drizzle-kit/src/cli/schema.ts:633-650](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/cli/schema.ts#L633-L650), [drizzle-kit/src/cli/schema.ts:652-805](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/cli/schema.ts#L652-L805), [drizzle-kit/src/cli/schema.ts:807-856](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/cli/schema.ts#L807-L856)
> [!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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/cli/schema.ts#L743-L750), [drizzle-kit/src/cli/schema.ts:845-852](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/cli/schema.ts#L845-L852)
### 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`.
```typescript
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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/netlify-db/driver.ts#L58-L69)
> [!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](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/cli/schema.ts#L691-L712)
## 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](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/getting-started/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](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/getting-started/project-structure) |
| How raw SQL expressions, parameterized chunks, dialect-aware operators, condition trees, and SQL functions are constructed and safely parameterized. | [SQL Template Engine](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/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](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/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](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/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](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/query-builder-foundation) |
| How database sessions, driver connection wrappers, transaction semantics, savepoints, batch execution, and migration runners coordinate across asynchronous runtimes. | [Sessions and Transactions](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/sessions-and-transactions) |
| How query result caching interfaces are structured and integrated with external distributed cache stores such as Upstash Redis. | [Query Caching](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/query-caching) |
| How query execution logging, OpenTelemetry-compatible spans, tracer hooks, and diagnostic telemetry are wired through internal query execution paths. | [Logging and Tracing](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/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](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/dialects-and-schema/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](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/dialects-and-schema/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](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/drivers-and-runtimes/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](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/drivers-and-runtimes/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](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/drivers-and-runtimes/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](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/migration-toolkit/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](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/migration-toolkit/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](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/migration-toolkit/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](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/migration-toolkit/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](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/migration-toolkit/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](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/ecosystem-packages/drizzle-zod-integration) |
| How JSON Schema validation objects are derived from Drizzle column types using Sinclair's TypeBox library. | [Drizzle TypeBox Integration](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/ecosystem-packages/drizzle-typebox-integration) |
| How modular and lightweight Valibot validation schemas are automatically generated from Drizzle ORM table definitions. | [Drizzle Valibot Integration](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/ecosystem-packages/drizzle-valibot-integration) |
| How ArkType runtime validation definitions are inferred from database table schemas. | [Drizzle ArkType Integration](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/ecosystem-packages/drizzle-arktype-integration) |
| How drizzle-seed inspects database schemas, orders insertion sequences respecting foreign key topological dependencies, and seeds mock records. | [Seed Service Engine](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/ecosystem-packages/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](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/ecosystem-packages/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](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/ecosystem-packages/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](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/testing-and-tooling/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](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/testing-and-tooling/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](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/testing-and-tooling/type-system-verification) |
## Related
- [Quick Start](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/getting-started/quick-start)
- [Project Structure](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/getting-started/project-structure)
- [SQL Template Engine](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/sql-template-engine)
---
## Technical docs: Database Migration Query Merger
URL: https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/how-it-works/database-migration-query-merger
Relevant source files
The following files were used as context for generating this wiki page:
- [drizzle-orm/src/netlify-db/migrator.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/netlify-db/migrator.ts)
- [drizzle-orm/src/node-postgres/migrator.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/node-postgres/migrator.ts)
- [drizzle-orm/src/pg-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/dialect.ts)
- [drizzle-orm/src/pg-core/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/session.ts)
- [drizzle-orm/src/sql/sql.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts)
## Overview
### Introduction
The **Migrate -> MergeQueries** execution flow represents the end-to-end lifecycle of schema migration execution within Drizzle ORM's PostgreSQL and Netlify Database adapters. When a user triggers database migrations, migration files are parsed, converted into executable `SQL` templates, compiled into database-ready query strings with parameterized values, and finally merged into cohesive query batches executed via a database session transaction.
Sources: [drizzle-orm/src/netlify-db/migrator.ts:8-18](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/netlify-db/migrator.ts#L8-L18), [drizzle-orm/src/node-postgres/migrator.ts:5-11](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/node-postgres/migrator.ts#L5-L11), [drizzle-orm/src/pg-core/dialect.ts:73-112](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/dialect.ts#L73-L112)
---
## Step-by-Step Execution Trace
### Step 1: Netlify-DB Migration Entrypoint
The migration process can initiate from the Netlify Database adapter's `migrate` function. It checks whether the provided database instance is an instance of `NodePgDatabase`. If so, it delegates execution directly to the Node-Postgres migrator; otherwise, it reads migration files from disk/configuration and passes them to the underlying database session dialect.
Sources: [drizzle-orm/src/netlify-db/migrator.ts:8-18](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/netlify-db/migrator.ts#L8-L18)
### Step 2: Node-Postgres Migration Entrypoint
For standard Node-Postgres setups, the `migrate` function loads the migration metadata using `readMigrationFiles(config)` and invokes `db.dialect.migrate(...)` with the parsed migrations, database session, and configuration.
Sources: [drizzle-orm/src/node-postgres/migrator.ts:5-11](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/node-postgres/migrator.ts#L5-L11)
### Step 3: PostgreSQL Dialect Migration Handler
The `PgDialect.migrate` method sets up the migrations tracking table (`__drizzle_migrations`), checks existing records in the database, opens a transaction, and loops through unapplied migration scripts, executing individual statements inside a transaction block.
Sources: [drizzle-orm/src/pg-core/dialect.ts:73-112](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/dialect.ts#L73-L112)
### Step 4: Session Execution & Query Preparation
When `tx.execute(...)` is called with an `SQL` template object, the `PgSession` wraps the operation inside active telemetry spans, turning the raw `SQL` object into a prepared query via `this.dialect.sqlToQuery(query)`.
Sources: [drizzle-orm/src/pg-core/session.ts:190-207](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/session.ts#L190-L207)
### Step 5: Dialect SQL-to-Query Conversion
`PgDialect.sqlToQuery` acts as a bridge, invoking `sql.toQuery(...)` with dialect-specific configurations such as custom casing rules, parameter escaping, and typing functions.
Sources: [drizzle-orm/src/pg-core/dialect.ts:609-618](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/dialect.ts#L609-L618)
### Step 6: SQL Object Query Compilation
`SQL.toQuery` initiates an active OpenTelemetry tracing span (`drizzle.buildSQL`) and invokes `buildQueryFromSourceParams` over the internal query chunks to compile textual SQL and parameter lists.
Sources: [drizzle-orm/src/sql/sql.ts:137-146](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L137-L146)
### Step 7: Building Query from Source Parameters
`buildQueryFromSourceParams` iterates through every `SQLChunk` inside the expression tree—handling strings, names, identifiers, tables, parameters, and nested `SQL` objects—producing a list of partial `QueryWithTypings` objects.
Sources: [drizzle-orm/src/sql/sql.ts:148-300](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L148-L300)
### Step 8: Merging Queries
`mergeQueries` aggregates an array of `QueryWithTypings` chunks into a single, unified `QueryWithTypings` result object by concatenating SQL strings, accumulating parameter arrays, and merging type definitions.
Sources: [drizzle-orm/src/sql/sql.ts:74-87](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L74-L87)
---
## Architecture Diagrams
### Sequence Diagram
```mermaid
sequenceDiagram
autonumber
participant NetlifyMigrator as netlify-db/migrator.ts
participant NodePgMigrator as node-postgres/migrator.ts
participant PgDialect as pg-core/dialect.ts
participant PgSession as pg-core/session.ts
participant SQLObj as sql/sql.ts (SQL)
alt Netlify DB (Non-NodePg)
NetlifyMigrator->>PgDialect: migrate(migrations, session, config)
else Node-Postgres / NodePg fallback
NetlifyMigrator->>NodePgMigrator: migrate(db, config)
NodePgMigrator->>PgDialect: migrate(migrations, session, config)
end
loop For each unapplied migration statement
PgDialect->>PgSession: tx.execute(sql)
PgSession->>PgDialect: sqlToQuery(query)
PgDialect->>SQLObj: sql.toQuery(config)
SQLObj->>SQLObj: buildQueryFromSourceParams(chunks, config)
SQLObj->>SQLObj: mergeQueries(queries)
SQLObj-->>PgDialect: QueryWithTypings
PgDialect-->>PgSession: Executed query result
end
```
Sources: [drizzle-orm/src/netlify-db/migrator.ts:8-18](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/netlify-db/migrator.ts#L8-L18), [drizzle-orm/src/node-postgres/migrator.ts:5-11](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/node-postgres/migrator.ts#L5-L11), [drizzle-orm/src/pg-core/dialect.ts:73-112](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/dialect.ts#L73-L112), [drizzle-orm/src/pg-core/session.ts:190-207](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/session.ts#L190-L207), [drizzle-orm/src/sql/sql.ts:74-146](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L74-L146)
### Flowchart
```mermaid
flowchart TD
A[Migrate Entrypoint] --> B{Is NodePgDatabase?}
B -- Yes --> C[NodePg Migrate]
B -- No --> D[Read Migration Files]
C --> D
D --> E[PgDialect.migrate]
E --> F[Execute Migration Statements]
F --> G[PgSession.execute]
G --> H[PgDialect.sqlToQuery]
H --> I[SQL.toQuery]
I --> J[buildQueryFromSourceParams]
J --> K[mergeQueries]
K --> L[Database Transaction Execution]
```
Sources: [drizzle-orm/src/netlify-db/migrator.ts:8-18](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/netlify-db/migrator.ts#L8-L18), [drizzle-orm/src/node-postgres/migrator.ts:5-11](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/node-postgres/migrator.ts#L5-L11), [drizzle-orm/src/pg-core/dialect.ts:73-112](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/dialect.ts#L73-L112), [drizzle-orm/src/pg-core/session.ts:190-207](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/session.ts#L190-L207), [drizzle-orm/src/sql/sql.ts:74-146](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L74-L146)
---
## Key Observations
- **Cross-Module Boundaries:** The execution flow seamlessly traverses driver-specific migrators (`netlify-db`, `node-postgres`), core database dialects (`pg-core`), active session managers, and core SQL query construction primitives (`sql/sql.ts`).
- **Transaction Safety:** Migration scripts are executed sequentially inside a database transaction (`session.transaction`), ensuring that schema updates are atomic and rolling back if any statement fails.
- **Telemetry & Tracing:** OpenTelemetry spans (`drizzle.operation`, `drizzle.prepareQuery`, `drizzle.buildSQL`) wrap query preparation and execution phases to monitor performance overhead.
Sources: [drizzle-orm/src/netlify-db/migrator.ts:8-18](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/netlify-db/migrator.ts#L8-L18), [drizzle-orm/src/pg-core/dialect.ts:95-111](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/dialect.ts#L95-L111), [drizzle-orm/src/pg-core/session.ts:195-206](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/session.ts#L195-L206), [drizzle-orm/src/sql/sql.ts:138-146](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L138-L146)
---
## Technical docs: Quick Start
URL: https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/getting-started/quick-start
Relevant source files
The following files were used as context for generating this wiki page:
- [drizzle-orm/type-tests/pg/tables.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/pg/tables.ts)
- [drizzle-orm/type-tests/mysql/tables.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/mysql/tables.ts)
- [drizzle-orm/type-tests/geldb/tables.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/geldb/tables.ts)
- [drizzle-orm/type-tests/singlestore/db.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/singlestore/db.ts)
- [drizzle-orm/type-tests/sqlite/tables.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/sqlite/tables.ts)
- [drizzle-kit/src/api.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/api.ts)
- [drizzle-kit/src/cli/connections.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/cli/connections.ts)
- [drizzle-orm/type-tests/singlestore/tables.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/singlestore/tables.ts)
- [drizzle-orm/type-tests/pg/select.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/pg/select.ts)
- [drizzle-orm/type-tests/kysely/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/kysely/index.ts)
- [drizzle-orm/type-tests/pg/db.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/pg/db.ts)
- [drizzle-orm/src/mysql2/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql2/driver.ts)
- [drizzle-orm/src/postgres-js/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/postgres-js/driver.ts)
- [drizzle-orm/type-tests/mysql/db.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/mysql/db.ts)
- [drizzle-orm/type-tests/geldb/select.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/geldb/select.ts)
- [drizzle-orm/type-tests/mysql/select.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/mysql/select.ts)
- [drizzle-orm/src/node-postgres/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/node-postgres/driver.ts)
- [drizzle-orm/type-tests/mysql/db-rel.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/mysql/db-rel.ts)
- [drizzle-orm/type-tests/singlestore/select.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/singlestore/select.ts)
- [drizzle-orm/type-tests/sqlite/select.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/sqlite/select.ts)
- [drizzle-orm/type-tests/geldb/db.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/geldb/db.ts)
- [drizzle-orm/type-tests/pg/db-rel.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/pg/db-rel.ts)
- [drizzle-orm/type-tests/sqlite/db.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/sqlite/db.ts)
- [drizzle-kit/src/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/index.ts)
- [drizzle-orm/src/better-sqlite3/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/better-sqlite3/index.ts)
- [drizzle-orm/src/node-postgres/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/node-postgres/index.ts)
## Overview
Get up and running with Drizzle ORM [Overview](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/getting-started/overview) by connecting schema definitions, driver initialization, and query execution across multiple database engines. This guide provides a foundational walkthrough to help developers define type-safe database tables [Type System Verification](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/testing-and-tooling/type-system-verification), establish client connections using drivers like node-postgres [Drivers And Runtimes](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/drivers-and-runtimes/drivers-and-runtimes) or mysql2, and execute complex queries with type-safe selection operators.
Sources: [drizzle-orm/src/node-postgres/driver.ts:1-140](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/node-postgres/driver.ts#L1-L140), [drizzle-orm/src/mysql2/driver.ts:1-183](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql2/driver.ts#L1-L183), [drizzle-orm/type-tests/pg/tables.ts:963-1054](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/pg/tables.ts#L963-L1054)
## Declaring Tables Across Dialects
### Dialect Table APIs
Drizzle ORM provides dialect-specific table builder functions—such as `pgTable`, `mysqlTable`, `sqliteTable`, `singlestoreTable`, and `gelTable`—to define schema structures with precise compile-time type verification [Type System Verification](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/testing-and-tooling/type-system-verification). Each table builder accepts a table name, a column mapping object (or a callback builder function returning column definitions), and an optional extra-config callback for defining table-level constraints, primary keys, and unique indexes.
Table definitions can be specified using a direct column object or a getter function callback across all supported storage engines. Column configurations support modifiers such as `.primaryKey()`, `.notNull()`, `.default()`, and dialect-specific type constraints.
```typescript
const cities1 = pgTable('cities_table', {
id: serial('id').primaryKey(),
name: text('name').notNull().primaryKey(),
role: text('role', { enum: ['admin', 'user'] }).default('user').notNull(),
population: integer('population').default(0),
});
const cities2 = pgTable('cities_table', ({ serial, text, integer }) => ({
id: serial('id').primaryKey(),
name: text('name').notNull().primaryKey(),
role: text('role', { enum: ['admin', 'user'] }).default('user').notNull(),
population: integer('population').default(0),
}));
```
Sources: [drizzle-orm/type-tests/pg/tables.ts:963-974](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/pg/tables.ts#L963-L974)
Similarly, SQLite and SingleStore support builders with advanced column mapping configurations, including explicit length constraints, enums, and generated expressions [Dialects And Schema Schema Definition](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/dialects-and-schema/dialects-and-schema-schema-definition).
```typescript
const test = sqliteTable('test', {
test1: text('test', { length: 255, enum: ['a', 'b', 'c'] as const }).notNull(),
test2: text('test', { length: 255, enum: ['a', 'b', 'c'] }).notNull(),
test3: text('test', { enum: ['a', 'b', 'c'] as const }).notNull(),
test4: text('test', { enum: ['a', 'b', 'c'] }).notNull(),
});
```
Sources: [drizzle-orm/type-tests/sqlite/tables.ts:450-455](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/sqlite/tables.ts#L450-L455)
```typescript
const emailLog = singlestoreTable(
'email_log',
{
id: int('id', { unsigned: true }).autoincrement().notNull(),
clientId: int('id_client', { unsigned: true }),
receiverEmail: varchar('receiver_email', { length: 255 }).notNull(),
messageId: varchar('message_id', { length: 255 }),
contextId: int('context_id', { unsigned: true }),
contextType: singlestoreEnum('context_type', ['test']).$type<['test']>(),
action: varchar('action', { length: 80 }).$type<['test']>(),
events: json('events').$type<{ t: 'test' }[]>(),
createdAt: timestamp('created_at', { mode: 'string' }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { mode: 'string' }).defaultNow().onUpdateNow(),
},
(table) => {
return {
emailLogId: primaryKey({ columns: [table.id], name: 'email_log_id' }),
emailLogMessageIdUnique: unique('email_log_message_id_unique').on(table.messageId),
};
},
);
```
Sources: [drizzle-orm/type-tests/singlestore/tables.ts:737-757](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/singlestore/tables.ts#L737-L757)
### Custom Types and Schema Scoping
Schema scoping functions such as `pgSchema`, `mysqlSchema`, and `singlestoreSchema` isolate tables within named database namespaces. Custom column types can be constructed using `customType`, specifying data types, driver transformations, and required configuration parameters.
> [!NOTE]
> Custom type definitions require explicitly declaring whether configuration options are mandatory via `configRequired: true` or optional in the generic configuration structure.
```typescript
const getUsersTable = (schemaName: TSchema) => {
return pgSchema(schemaName).table('users', {
id: integer('id').primaryKey(),
name: text('name').notNull(),
});
};
```
Sources: [drizzle-orm/type-tests/pg/tables.ts:1088-1093](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/pg/tables.ts#L1088-L1093)
```typescript
const customTextRequired = customType<{
data: string;
driverData: string;
config: { length: number };
configRequired: true;
}>({
dataType(config) {
Expect>;
return `varchar(${config.length})`;
},
toDriver(value) {
Expect>();
return value;
},
fromDriver(value) {
Expect>();
return value;
},
});
```
Sources: [drizzle-orm/type-tests/pg/tables.ts:904-924](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/pg/tables.ts#L904-L924)
## Initializing PostgreSQL and MySQL Clients
### PostgreSQL Client Initialization
Establishing connections to PostgreSQL and MySQL databases requires instantiating the appropriate driver client and passing it to the dialect initialization function. Drizzle supports multiple initialization signatures for both Node.js `pg`, `postgres-js`, and `mysql2` clients, accepting direct client instances, connection strings, or configuration objects containing `client`, `connection`, `schema`, `casing`, `logger`, `cache`, and driver-specific options.
The PostgreSQL driver supports connection setup via `node-postgres` and `postgres-js`. For `node-postgres`, the `drizzle` entrypoint accepts either a `Pool` or `Client` instance, a raw connection string, or a configuration object with `connection` or `client` keys [drizzle-orm/src/node-postgres/driver.ts:91-140](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/node-postgres/driver.ts#L91-L140). Similarly, `postgres-js` accepts an `Sql` instance, a connection URL string, or a configuration object [drizzle-orm/src/postgres-js/driver.ts:70-118](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/postgres-js/driver.ts#L70-L118).
```typescript
import pg from 'pg';
import { drizzle } from '~/node-postgres/index.ts';
const { Client } = pg;
export const db = drizzle(new Client());
```
Sources: [drizzle-orm/type-tests/pg/db.ts:1-6](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/pg/db.ts#L1-L6)
> [!NOTE]
> When initializing `postgres-js`, Drizzle automatically overrides default date, JSON, and binary parsers (`1184`, `1082`, `1083`, `1114`, `1182`, `1185`, `1115`, `1231`, `114`, `3802`) with transparent identity parsers to prevent unwanted timezone transformations [drizzle-orm/src/postgres-js/driver.ts:28-36](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/postgres-js/driver.ts#L28-L36).
Sources: [drizzle-orm/src/postgres-js/driver.ts:28-36](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/postgres-js/driver.ts#L28-L36)
### MySQL Client Initialization
MySQL configurations use the `mysql2` driver, accepting callback or promise-based pools and connections. Callback pools passed to `drizzle` are automatically wrapped with `.promise()` to support async query execution [drizzle-orm/src/mysql2/driver.ts:77](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql2/driver.ts#L77).
```typescript
import { createPool } from 'mysql2/promise';
import { drizzle } from '~/mysql2/index.ts';
const pool = createPool({});
export const db = drizzle(pool);
```
Sources: [drizzle-orm/type-tests/mysql/db.ts:1-6](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/mysql/db.ts#L1-L6)
> [!WARNING]
> When providing a relational `schema` object to MySQL `drizzle` configuration, you must explicitly specify a `mode` property set to either `'default'` or `'planetscale'`. Omitting the mode when a schema is present throws a runtime `DrizzleError`.
Sources: [drizzle-orm/src/mysql2/driver.ts:80-86](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql2/driver.ts#L80-L86)
## Configuring Embedded and Alternative Engines
### SQLite and Serverless Drivers
Embedded databases and alternative engines such as SQLite variants, SingleStore, and Gel use specialized driver initialization entrypoints. SQLite supports multiple runtimes including `better-sqlite3`, Bun's native SQLite, Cloudflare D1, and Durable Object storage. Each runtime requires its respective driver instance initialized before passing to the dialect-specific `drizzle` function.
```typescript
import Database from 'better-sqlite3';
import { Database as BunDatabase } from 'bun:sqlite';
import { drizzle as drizzleBetterSqlite3 } from '~/better-sqlite3/index.ts';
import { drizzle as drizzleBun } from '~/bun-sqlite/index.ts';
import { drizzle as drizzleD1 } from '~/d1/index.ts';
import { drizzle as durableSqlite } from '~/durable-sqlite/index.ts';
const client = new Database(':memory:');
const bunClient = new BunDatabase(':memory:');
declare const d1: D1Database;
declare const durableSql: DurableObjectStorage;
export const db = drizzleBetterSqlite3(client);
export const bunDb = drizzleBun(bunClient);
export const d1Db = drizzleD1(d1);
export const durableSqliteDb = durableSqlite(durableSql);
```
Sources: [drizzle-orm/type-tests/sqlite/db.ts:1-16](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/sqlite/db.ts#L1-L16)
> [!NOTE]
> SQLite initialization functions accept either a direct client instance or configuration objects, allowing memory-backed databases or persistent storage bindings like Cloudflare D1 and Durable Objects to operate transparently within type definitions.
Sources: [drizzle-orm/type-tests/sqlite/db.ts:8-16](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/sqlite/db.ts#L8-L16)
### Alternative Database Dialects
SingleStore and Gel use independent driver connectors and initialization modules. SingleStore integrates through `mysql2/promise` connection pools, accepting optional configuration objects with schema definitions. Gel connects via the official `gel` package client instance.
```typescript
import { createPool } from 'mysql2/promise';
import { drizzle } from '~/singlestore/index.ts';
const pool = createPool({});
export const db = drizzle(pool);
{
drizzle(pool);
drizzle(pool, { schema: {} });
drizzle(pool, { schema: {} });
drizzle(pool, {});
}
```
Sources: [drizzle-orm/type-tests/singlestore/db.ts:1-13](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/singlestore/db.ts#L1-L13)
```typescript
import * as gel from 'gel';
import { drizzle } from '~/gel/index.ts';
export const db = drizzle(gel.createClient());
```
Sources: [drizzle-orm/type-tests/geldb/db.ts:1-4](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/geldb/db.ts#L1-L4)
> [!TIP]
> SingleStore initialization permits passing an empty or populated schema object alongside the connection pool during setup, matching the configuration patterns used across relational database drivers.
Sources: [drizzle-orm/type-tests/singlestore/db.ts:8-13](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/singlestore/db.ts#L8-L13)
## Executing Queries with Selection Operators
### Query Construction and Joins
Selection queries start from a database table using `.select()` combined with `.from()`, and can be extended with inner joins, left joins, or full outer joins to combine related entities. Operators such as `eq`, `and`, and raw SQL fragments via the `sql` template tag define join conditions and filter predicates.
```typescript
const join4 = await db
.select({
user: {
id: users.id,
},
city: {
id: cities.id,
},
class: classes,
friend: friends,
})
.from(users)
.innerJoin(cities, sql`${users.id} = ${cities.id}`)
.innerJoin(classes, sql`${cities.id} = ${classes.id}`)
.innerJoin(friends, sql`${friends.id} = ${users.id}`)
.where(sql`${users.age1} > 0`);
```
Sources: [drizzle-orm/type-tests/geldb/select.ts:817-832](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/geldb/select.ts#L817-L832), [drizzle-orm/type-tests/singlestore/select.ts:548-563](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/singlestore/select.ts#L548-L563)
> [!WARNING]
> Attempting to chain multiple `.where()` clauses on the same select statement triggers a TypeScript compilation error because query builders restrict filtering to a single invocation per statement.
Sources: [drizzle-orm/type-tests/geldb/select.ts:923-943](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/geldb/select.ts#L923-L943), [drizzle-orm/type-tests/singlestore/select.ts:657-677](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/singlestore/select.ts#L657-L677)
### Row Locking and Modifiers
Queries support row-level locking modifiers via the `.for()` method to handle concurrent transactions. Depending on the dialect and requirements, locking strategies can specify exclusivity, wait behavior, or lock skipping.
```typescript
await db.select().from(users).for('update');
await db.select().from(users).for('no key update', { of: users });
await db.select().from(users).for('no key update', { of: users, skipLocked: true });
await db.select().from(users).for('share', { of: users, noWait: true });
```
Sources: [drizzle-orm/type-tests/geldb/select.ts:885-904](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/geldb/select.ts#L885-L904), [drizzle-orm/type-tests/singlestore/select.ts:615-617](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/singlestore/select.ts#L615-L617)
> [!CAUTION]
> Combining both `skipLocked: true` and `noWait: true` in the same `.for()` options object causes a TypeScript type error and is disallowed by locking constraint rules.
Sources: [drizzle-orm/type-tests/geldb/select.ts:905-910](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/geldb/select.ts#L905-L910), [drizzle-orm/type-tests/singlestore/select.ts:619-623](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/singlestore/select.ts#L619-L623)
## Querying Relational Schemas with Relations
### Relational Queries and Schema Definition
Relational queries access structured graphs of data via `db.query..findMany()` by bundling schema definitions directly into client initialization. When configuring a PostgreSQL or MySQL client via `drizzle(client, { schema })`, `extractTablesRelationalConfig` and `createTableRelationsHelpers` process the passed schema object to map relationships, table configurations, and name lookups.
```typescript
import pg from 'pg';
import { drizzle } from '~/node-postgres/index.ts';
import * as schema from './tables-rel.ts';
const { Pool } = pg;
const pdb = new Pool({ connectionString: process.env['PG_CONNECTION_STRING'] });
const db = drizzle(pdb, { schema });
```
Sources: [drizzle-orm/src/node-postgres/driver.ts:67-77](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/node-postgres/driver.ts#L67-L77), [drizzle-orm/type-tests/pg/db-rel.ts:1-10](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/pg/db-rel.ts#L1-L10)
> [!NOTE]
> MySQL2 database instances require `config.mode` to be explicitly set to either `'planetscale'` or `'default'` when a schema is provided, otherwise an error is thrown during initialization.
>
> Sources: [drizzle-orm/src/mysql2/driver.ts:80-86](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql2/driver.ts#L80-L86)
### Filtering, Pagination, and Column Selection
The relational query builder accepts `where`, `limit`, `orderBy`, `columns`, and `with` options to filter records and shape nested tree structures. The `columns` configuration object supports boolean values or `undefined` / `false` flags to include or exclude specific fields.
```typescript
const result = await db.query.users.findMany({
where: (users, { sql }) => sql`char_length(${users.name} > 1)`,
limit: sql.placeholder('l'),
orderBy: (users, { asc, desc }) => [asc(users.name), desc(users.id)],
with: {
posts: {
columns: {
id: false,
title: undefined,
},
extras: {
lower: sql`lower(${schema.posts.title})`.as('lower_name'),
},
},
},
});
```
Sources: [drizzle-orm/type-tests/pg/db-rel.ts:13-24](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/pg/db-rel.ts#L13-L24), [drizzle-orm/type-tests/pg/db-rel.ts:92-107](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/pg/db-rel.ts#L92-L107)
> [!TIP]
> The `extras` property allows appending computed SQL expressions and custom aliases to query selections without modifying the underlying table schema definition.
Sources: [drizzle-orm/type-tests/pg/db-rel.ts:99-104](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/pg/db-rel.ts#L99-L104), [drizzle-orm/type-tests/mysql/db-rel.ts:99-101](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/mysql/db-rel.ts#L99-L101)
## Applying Migrations with Kit Entrypoints
### Configuration and DefineConfig
The `drizzle-kit` entrypoint provides the `defineConfig` utility to validate and structure options for schema management, migrations, and [database introspection](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/migration-toolkit/database-introspection) [Configuration and Validations](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/migration-toolkit/configuration-and-validations). The configuration object governs dialect selection, schema paths, migration output directories, and driver-specific credentials across multiple engines.
```typescript
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
dialect: 'postgresql',
schema: './src/schema.ts',
out: './drizzle',
breakpoints: true,
strict: true,
verbose: true,
});
```
Sources: [drizzle-kit/src/index.ts:109-132](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/index.ts#L109-L132), [drizzle-kit/src/index.ts:347-349](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/index.ts#L347-L349)
### Dialect Support and Driver Options
Drizzle-kit supports distinct database dialects alongside specialized driver integrations. The configuration schema enforces valid option combinations for connection parameters, SSL settings, and migration metadata tables.
| Dialect | Required Credentials / URL | Supported Drivers / Options |
| :--- | :--- | :--- |
| `postgresql` | `url` or `host`, `database`, optional `ssl` | `aws-data-api`, `pglite` |
| `mysql` | `url` or `host`, `database`, optional `ssl` | — |
| `sqlite` | `url` | `d1-http`, `expo`, `durable-sqlite` |
| `turso` | `url`, optional `authToken` | — |
| `singlestore` | `url` or `host`, `database`, optional `ssl` | — |
| `gel` | optional `url` or host fields, `tlsSecurity` | — |
Sources: [drizzle-kit/src/index.ts:133-255](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/index.ts#L133-L255)
> [!NOTE]
> The `breakpoints` option defaults to `true` and inserts SQL statement breakpoints into generated migrations. This is required for engines like MySQL, SQLite, and SingleStore that do not support multiple DDL alteration statements within a single transaction.
Sources: [drizzle-kit/src/index.ts:65-71](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/index.ts#L65-L71), [drizzle-kit/src/index.ts:113](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/index.ts#L113)
## Related
- [Overview](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/getting-started/overview)
- [Dialects And Schema Schema Definition](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/dialects-and-schema/dialects-and-schema-schema-definition)
- [CLI Command Architecture](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/migration-toolkit/cli-command-architecture)
---
## Technical docs: Project Structure
URL: https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/getting-started/project-structure
Relevant source files
The following files were used as context for generating this wiki page:
- [drizzle-kit/src/api.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/api.ts)
- [turbo.json](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/turbo.json)
- [drizzle-kit/src/utils.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/utils.ts)
- [drizzle-orm/src/d1/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/d1/index.ts)
- [pnpm-workspace.yaml](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/pnpm-workspace.yaml)
- [drizzle-kit/src/serializer/studio.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/serializer/studio.ts)
- [drizzle-orm/src/neon/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon/index.ts)
- [package.json](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/package.json)
- [drizzle-seed/src/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-seed/src/index.ts)
- [drizzle-orm/src/gel-core/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/index.ts)
- [drizzle-kit/src/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/index.ts)
- [drizzle-orm/src/singlestore-core/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/index.ts)
- [drizzle-kit/package.json](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/package.json)
- [drizzle-orm/src/singlestore/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore/index.ts)
- [drizzle-orm/src/gel/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel/index.ts)
- [drizzle-orm/src/durable-sqlite/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/durable-sqlite/index.ts)
- [drizzle-orm/src/libsql/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/index.ts)
- [drizzle-seed/package.json](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-seed/package.json)
- [drizzle-orm/src/pg-core/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/index.ts)
- [drizzle-kit/src/serializer/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/serializer/index.ts)
- [drizzle-orm/src/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/index.ts)
- [drizzle-orm/src/mysql-proxy/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-proxy/index.ts)
- [drizzle-orm/src/prisma/sqlite/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/prisma/sqlite/index.ts)
- [drizzle-orm/src/prisma/pg/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/prisma/pg/index.ts)
- [drizzle-orm/src/sqlite-proxy/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-proxy/index.ts)
- [drizzle-orm/src/pglite/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pglite/index.ts)
- [drizzle-orm/src/pg-proxy/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-proxy/index.ts)
- [drizzle-orm/src/singlestore-proxy/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-proxy/index.ts)
- [drizzle-orm/src/mysql-core/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/index.ts)
- [drizzle-orm/src/op-sqlite/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/op-sqlite/index.ts)
## Overview
Drizzle ORM and its tooling ecosystem are structured as an integrated monorepo workspace containing packages such as `drizzle-orm`, `drizzle-kit`, validation companions (`drizzle-zod`, `drizzle-typebox`, `drizzle-valibot`, `drizzle-arktype`), seeding engines (`drizzle-seed`), and internal development utilities. Managed through a Turborepo build pipeline and pnpm workspaces, the repository enforces strict dependency isolation and build ordering between core relational abstractions, engine-specific dialect modules, and runtime drivers.
Sources: [turbo.json:1-210](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/turbo.json#L1-L210), [pnpm-workspace.yaml:1-11](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/pnpm-workspace.yaml#L1-L11), [package.json:1-42](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/package.json#L1-L42)
## Monorepo Workspace Organization
### Workspace Members and Configuration
The repository uses `pnpm` workspaces to govern ten distinct packages under a private root manifest named `drizzle-root` with `pnpm@10.6.3`. The workspace layout includes core database relational abstractions, migration CLI infrastructure, schema validation generators, mock data seeding utilities, integration test suites, and internal linting plugins.
```yaml
packages:
- drizzle-orm
- drizzle-kit
- drizzle-zod
- drizzle-typebox
- drizzle-valibot
- drizzle-arktype
- drizzle-seed
- integration-tests
- eslint-plugin-drizzle
onlyBuiltDependencies:
```
Sources: [pnpm-workspace.yaml:1-11](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/pnpm-workspace.yaml#L1-L11)
| Workspace Member | Description |
| :--- | :--- |
| `drizzle-orm` | Core ORM runtime and query builder library |
| `drizzle-kit` | Migration CLI and tooling suite |
| `drizzle-zod` | Zod schema generation companion |
| `drizzle-typebox` | TypeBox schema generation companion |
| `drizzle-valibot` | Valibot schema generation companion |
| `drizzle-arktype` | ArkType schema generation companion |
| `drizzle-seed` | Database mock seeding engine |
| `integration-tests` | Comprehensive database integration tests |
| `eslint-plugin-drizzle` | Custom ESLint rules for Drizzle codebases |
Sources: [pnpm-workspace.yaml:1-10](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/pnpm-workspace.yaml#L1-L10)
> [!NOTE]
> The root `package.json` configures development dependencies including `typescript` (5.6.3), `tsup` (8.3.5), `turbo` (2.2.3), and `dprint` (0.46.2), while defining workspace aliases such as `drizzle-orm` pointing directly to its distribution output (`workspace:./drizzle-orm/dist`).
Sources: [package.json:1-42](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/package.json#L1-L42)
### Build and Test Scripts
Orchestration tasks are driven by Turborepo filters and root scripts defined in the root configuration. These tasks coordinate type-checking, builds, formatting, and test execution across workspace boundaries.
```json
"scripts": {
"build:orm": "turbo run build --filter drizzle-orm --color",
"build": "turbo run build test:types //#lint --color",
"b": "pnpm build",
"pack": "turbo run pack --color",
"test": "turbo run test --color",
"t": "pnpm test",
"test:types": "turbo run test:types --color",
"lint": "dprint check --list-different",
"lint:fix": "dprint fmt"
},
```
Sources: [package.json:4-14](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/package.json#L4-L14)
| Script Name | Command | Purpose |
| :--- | :--- | :--- |
| `build:orm` | `turbo run build --filter drizzle-orm --color` | Builds only the core `drizzle-orm` package via Turbo |
| `build` | `turbo run build test:types //#lint --color` | Executes full monorepo build, type tests, and linting |
| `b` | `pnpm build` | Shorthand alias for full monorepo build |
| `pack` | `turbo run pack --color` | Packs workspace packages into distributable archives |
| `test` | `turbo run test --color` | Runs test suites across all workspace members |
| `t` | `pnpm test` | Shorthand alias for test execution |
| `test:types` | `turbo run test:types --color` | Executes type-checking across workspace packages |
| `lint` | `dprint check --list-different` | Checks code formatting using dprint |
| `lint:fix` | `dprint fmt` | Auto-formats codebase files using dprint |
Sources: [package.json:4-14](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/package.json#L4-L14)
> [!IMPORTANT]
> The root `pnpm-workspace.yaml` specifies an explicit `onlyBuiltDependencies` array to restrict native compilation during dependency installation, isolating binary packages such as `better-sqlite3`, `esbuild`, `prisma`, `sqlite3`, and `workerd`.
Sources: [pnpm-workspace.yaml:11-27](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/pnpm-workspace.yaml#L11-L27)
### Package Isolation and Entry Points
Individual workspace packages enforce strict encapsulation via targeted `package.json` configurations, declaring precise exports maps for CommonJS and ESM consumers, as well as peer dependency constraints.
```json
"exports": {
".": {
"import": {
"types": "./index.d.mts",
"default": "./index.mjs"
},
"require": {
"types": "./index.d.ts",
"default": "./index.js"
},
"types": "./index.d.mts",
"default": "./index.mjs"
},
"./api": {
"import": {
"types": "./api.d.mts",
"default": "./api.mjs"
},
"require": {
"types": "./api.d.ts",
"default": "./api.js"
},
"types": "./api.d.mts",
"default": "./api.mjs"
}
}
```
Sources: [drizzle-kit/package.json:118-143](https://github.com/blade47/drizzle-kit/package.json#L118-L143)
> [!WARNING]
> Packages like `drizzle-seed` declare `drizzle-orm` as an optional peer dependency (`>=0.36.4`) while consuming workspace references during development builds (`workspace:./drizzle-orm/dist`), requiring correct build ordering enforced by Turborepo pipelines.
Sources: [drizzle-seed/package.json:67-74](https://github.com/blade47/drizzle-seed/package.json#L67-L74), [drizzle-seed/package.json:90-90](https://github.com/blade47/drizzle-seed/package.json#L90-L90)
## Drizzle ORM Core Subsystem
### Core Subsystem Module Exports
The core query builder library exports its primary abstractions and runtime modules from the entry point `drizzle-orm/src/index.ts`. These modules provide the foundational contracts for schema definition, column construction, expression handling, and query execution.
| Export Module | Source File | Purpose |
| :--- | :--- | :--- |
| Table alias definitions | `./alias.ts` | Provides mechanisms for aliasing database tables and relational expressions |
| Column builders | `./column-builder.ts` | Defines fluent builders and configuration APIs for table columns |
| Column primitives | `./column.ts` | Implements core column properties, data types, and mapping logic |
| Entity abstractions | `./entity.ts` | Base definitions for relational entities and schema components |
| Error handling | `./errors.ts` | Core library exceptions and runtime error types |
| Logging infrastructure | `./logger.ts` | Query logging abstractions and formatting interfaces |
| Query operations | `./operations.ts` | Universal operator contracts and filter expression builders |
| Query promises | `./query-promise.ts` | Thenable query objects supporting async execution and chaining |
| Relations mapping | `./relations.ts` | Relational schema definitions, foreign key links, and relation helpers |
| SQL AST subsystem | `./sql/index.ts` | Abstract syntax tree nodes, SQL template literal tags, and token serialization |
| Subqueries | `./subquery.ts` | Derived table wrappers and subquery construction contracts |
| Table primitives | `./table.ts` | Core table definition structures and schema metadata containers |
| Utilities | `./utils.ts` | Internal helper functions and shared type utilities |
| View abstractions | `./view-common.ts` | Common interfaces for database views and materialized representations |
Sources: [drizzle-orm/src/index.ts:1-14](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/index.ts#L1-L14)
> [!NOTE]
> The core subsystem operates as a zero-dependency headless library, relying entirely on exported TypeScript modules to build AST representations that are later translated into engine-specific SQL by dialect drivers.
Sources: [drizzle-orm/src/index.ts:1-14](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/index.ts#L1-L14)
## Dialect Specialization Boundaries
### Engine-Specific Core Modules
Dialect specialization directories organize engine-specific primitives, mapping abstractions, and query structures across supported database backends. PostgreSQL, MySQL, SingleStore, and Gel maintain isolated core index entry points under their respective directories in `drizzle-orm/src/`.
| Core Module Export | PostgreSQL (`pg-core`) | MySQL (`mysql-core`) | SingleStore (`singlestore-core`) | Gel (`gel-core`) |
| :--- | :--- | :--- | :--- | :--- |
| Table alias | `export * from './alias.ts'` | `export * from './alias.ts'` | `export * from './alias.ts'` | `export * from './alias.ts'` |
| Check constraints | `export * from './checks.ts'` | `export * from './checks.ts'` | — | `export * from './checks.ts'` |
| Column definitions | `export * from './columns/index.ts'` | `export * from './columns/index.ts'` | `export * from './columns/index.ts'` | `export * from './columns/index.ts'` |
| Database instance | `export * from './db.ts'` | `export * from './db.ts'` | `export * from './db.ts'` | `export * from './db.ts'` |
| Dialect implementation | `export * from './dialect.ts'` | `export * from './dialect.ts'` | `export * from './dialect.ts'` | `export * from './dialect.ts'` |
| Foreign keys | `export * from './foreign-keys.ts'` | `export * from './foreign-keys.ts'` | — | `export * from './foreign-keys.ts'` |
| Index definitions | `export * from './indexes.ts'` | `export * from './indexes.ts'` | `export * from './indexes.ts'` | `export * from './indexes.ts'` |
| Access policies | `export * from './policies.ts'` | — | — | `export * from './policies.ts'` |
| Primary keys | `export * from './primary-keys.ts'` | `export * from './primary-keys.ts'` | `export * from './primary-keys.ts'` | `export * from './primary-keys.ts'` |
| Query builders | `export * from './query-builders/index.ts'` | `export * from './query-builders/index.ts'` | `export * from './query-builders/index.ts'` | `export * from './query-builders/index.ts'` |
| Roles | `export * from './roles.ts'` | — | — | `export * from './roles.ts'` |
| Schema container | `export * from './schema.ts'` | `export * from './schema.ts'` | `export * from './schema.ts'` | `export * from './schema.ts'` |
| Sequences | `export * from './sequence.ts'` | — | — | `export * from './sequence.ts'` |
| Session interface | `export * from './session.ts'` | `export * from './session.ts'` | `export * from './session.ts'` | `export * from './session.ts'` |
| Subqueries | `export * from './subquery.ts'` | `export * from './subquery.ts'` | `export * from './subquery.ts'` | `export * from './subquery.ts'` |
| Table structures | `export * from './table.ts'` | `export * from './table.ts'` | `export * from './table.ts'` | `export * from './table.ts'` |
| Unique constraints | `export * from './unique-constraint.ts'` | `export * from './unique-constraint.ts'` | `export * from './unique-constraint.ts'` | `export * from './unique-constraint.ts'` |
| Utilities | `export * from './utils.ts'`, `export * from './utils/index.ts'` | `export * from './utils.ts'` | `export * from './utils.ts'` | `export * from './utils.ts'` |
| Views and common view types | `export * from './view-common.ts'`, `export * from './view.ts'` | `export * from './view-common.ts'`, `export * from './view.ts'` | Commented out / disabled | `export * from './view-common.ts'`, `export * from './view.ts'` |
Sources: [drizzle-orm/src/pg-core/index.ts:1-21](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/index.ts#L1-L21), [drizzle-orm/src/mysql-core/index.ts:1-17](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/index.ts#L1-L17), [drizzle-orm/src/singlestore-core/index.ts:1-14](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/index.ts#L1-L14), [drizzle-orm/src/gel-core/index.ts:1-20](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/index.ts#L1-L20)
> [!CAUTION]
> SingleStore core explicitly disables view exports via block comments inside `drizzle-orm/src/singlestore-core/index.ts`, omitting view-common and view modules from its public dialect API surface.
Sources: [drizzle-orm/src/singlestore-core/index.ts:14-14](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/index.ts#L14-L14)
> [!NOTE]
> PostgreSQL (`pg-core`) maintains an additional internal utility sub-index (`export * from './utils/index.ts'`) alongside its root `utils.ts` module to handle advanced PostgreSQL-specific type and expression helpers.
Sources: [drizzle-orm/src/pg-core/index.ts:18-19](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/index.ts#L18-L19)
## Runtime Driver Bindings
### LibSQL Driver and Session Exports
```typescript
export * from './driver.ts';
export * from './session.ts';
```
Sources: [drizzle-orm/src/libsql/index.ts:1-2](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/index.ts#L1-L2)
The LibSQL runtime integration layer re-exports all binding declarations from its constituent driver and session modules.
```typescript
export * from './driver.ts';
export * from './session.ts';
```
Sources: [drizzle-orm/src/libsql/index.ts:1-2](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/index.ts#L1-L2)
> [!NOTE]
> LibSQL driver bindings maintain a strict separation between connection initialization logic in `driver.ts` and execution context management in `session.ts`.
Sources: [drizzle-orm/src/libsql/index.ts:1-2](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/index.ts#L1-L2)
### PGlite Driver and Session Exports
```typescript
export * from './driver.ts';
export * from './session.ts';
```
Sources: [drizzle-orm/src/pglite/index.ts:1-2](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pglite/index.ts#L1-L2)
Similarly, the PGlite in-memory and embedded PostgreSQL runtime integration aggregates its entry point by consuming module exports from local driver and session sources.
```typescript
export * from './driver.ts';
export * from './session.ts';
```
Sources: [drizzle-orm/src/pglite/index.ts:1-2](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pglite/index.ts#L1-L2)
> [!TIP]
> Both LibSQL and PGlite package entry points intentionally expose flat module namespaces via star-export declarations to streamline consumer imports across diverse serverless and edge targets.
Sources: [drizzle-orm/src/libsql/index.ts:1-2](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/index.ts#L1-L2), [drizzle-orm/src/pglite/index.ts:1-2](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pglite/index.ts#L1-L2)
## Tooling and Utility Infrastructure
### CLI Validation Layers and Migration Utilities
```typescript
const validatorForDialect = (dialect: Dialect) => {
switch (dialect) {
case 'postgresql':
return { validator: backwardCompatiblePgSchema, version: 7 };
case 'sqlite':
return { validator: backwardCompatibleSqliteSchema, version: 6 };
case 'turso':
return { validator: backwardCompatibleSqliteSchema, version: 6 };
case 'mysql':
return { validator: backwardCompatibleMysqlSchema, version: 5 };
case 'singlestore':
return { validator: backwardCompatibleSingleStoreSchema, version: 1 };
case 'gel':
return { validator: backwardCompatibleGelSchema, version: 1 };
}
};
```
Sources: [drizzle-kit/src/utils.ts:115-130](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/utils.ts#L115-L130)
The `drizzle-kit` utility infrastructure inspects and validates database schemas across various SQL dialects by mapping each dialect to a compatible schema validator and expected version number. The `validatorForDialect` helper function evaluates the target dialect and returns the corresponding parser alongside its required schema version integer.
| Dialect | Validator Function | Version | Sources |
| :--- | :--- | :---: | :--- |
| `postgresql` | `backwardCompatiblePgSchema` | 7 | [drizzle-kit/src/utils.ts:117-118](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/utils.ts#L117-L118) |
| `sqlite` | `backwardCompatibleSqliteSchema` | 6 | [drizzle-kit/src/utils.ts:119-120](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/utils.ts#L119-L120) |
| `turso` | `backwardCompatibleSqliteSchema` | 6 | [drizzle-kit/src/utils.ts:121-122](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/utils.ts#L121-L122) |
| `mysql` | `backwardCompatibleMysqlSchema` | 5 | [drizzle-kit/src/utils.ts:123-124](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/utils.ts#L123-L124) |
| `singlestore` | `backwardCompatibleSingleStoreSchema` | 1 | [drizzle-kit/src/utils.ts:125-126](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/utils.ts#L125-L126) |
| `gel` | `backwardCompatibleGelSchema` | 1 | [drizzle-kit/src/utils.ts:127-128](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/utils.ts#L127-L128) |
Sources: [drizzle-kit/src/utils.ts:115-130](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/utils.ts#L115-L130)
> [!WARNING]
> If a snapshot file specifies a version number exceeding the validator's configured version threshold, `validateWithReport` logs an unsupported version message and terminates execution via `process.exit(0)`.
Sources: [drizzle-kit/src/utils.ts:145-152](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/utils.ts#L145-L152)
### Shared Runtime Configuration Boundaries
```typescript
export type Config =
& {
dialect: Dialect;
out?: string;
breakpoints?: boolean;
tablesFilter?: string | string[];
extensionsFilters?: 'postgis'[];
schemaFilter?: string | string[];
schema?: string | string[];
verbose?: boolean;
strict?: boolean;
casing?: 'camelCase' | 'snake_case';
migrations?: {
table?: string;
schema?: string;
prefix?: Prefix;
};
introspect?: {
casing: 'camel' | 'preserve';
};
entities?: {
roles?: boolean | { provider?: 'supabase' | 'neon' | string & {}; exclude?: string[]; include?: string[] };
};
}
```
Sources: [drizzle-kit/src/index.ts:109-132](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/index.ts#L109-L132)
Configuration definitions for `drizzle-kit` establish strict typing boundaries across options such as `dialect`, `out`, `breakpoints`, `tablesFilter`, `extensionsFilters`, `schemaFilter`, `schema`, `verbose`, `strict`, `casing`, `migrations`, `introspect`, and `entities`. Connection parameters enforce disjoint credentials based on the selected database dialect, requiring specific credential shapes for engines like Turso, SQLite, PostgreSQL, and MySQL.
> [!NOTE]
> The `breakpoints` configuration parameter defaults to true and controls whether SQL statement breakpoints are embedded in generated migration files to support sequential execution on engines lacking multi-statement transaction DDL.
Sources: [drizzle-kit/src/index.ts:65-70](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/index.ts#L65-L70), [drizzle-kit/src/index.ts:113](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/index.ts#L113)
## Related
- [Overview](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/getting-started/overview)
- [Monorepo Build Pipeline](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/testing-and-tooling/monorepo-build-pipeline)
---
## Technical docs: SQL Template Engine
URL: https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/sql-template-engine
Relevant source files
The following files were used as context for generating this wiki page:
- [drizzle-orm/src/sql/sql.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts)
- [drizzle-orm/src/gel-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/dialect.ts)
- [drizzle-orm/src/singlestore-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/dialect.ts)
- [drizzle-orm/src/sql/expressions/conditions.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/expressions/conditions.ts)
- [drizzle-orm/src/pg-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/dialect.ts)
- [drizzle-orm/src/sqlite-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/dialect.ts)
- [drizzle-orm/src/gel-core/expressions.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/expressions.ts)
- [drizzle-orm/src/singlestore-core/expressions.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/expressions.ts)
- [drizzle-orm/src/mysql-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/dialect.ts)
- [drizzle-orm/src/gel-core/query-builders/select.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/select.ts)
- [drizzle-orm/src/gel-core/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/session.ts)
- [drizzle-orm/type-tests/sqlite/select.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/sqlite/select.ts)
- [drizzle-orm/type-tests/geldb/select.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/geldb/select.ts)
- [drizzle-orm/src/sql/expressions/select.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/expressions/select.ts)
- [drizzle-orm/src/sql/functions/aggregate.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/aggregate.ts)
- [drizzle-orm/src/sql/functions/vector.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/vector.ts)
- [drizzle-orm/src/d1/migrator.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/d1/migrator.ts)
- [drizzle-orm/src/durable-sqlite/migrator.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/durable-sqlite/migrator.ts)
- [drizzle-orm/src/libsql/migrator.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/migrator.ts)
## Overview
The SQL template engine in Drizzle ORM provides a powerful programmatic foundation for constructing typesafe SQL queries, expressions, and database operations through tagged template literals and abstract syntax tree (AST) nodes. It solves the complexity of dynamic query composition by turning nested SQL chunks, parameters, tables, columns, and subqueries into structured trees that compile cleanly into driver-ready queries with proper parameter binding and escaping. Core classes like `SQL`, `StringChunk`, and `Param` manage query structures, while helper functions for conditions, aggregates, and vector operations enable expressive query building across dialects.
Sources: [drizzle-orm/src/sql/sql.ts:1-73](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L1-L73), [drizzle-orm/src/sql/sql.ts:89-130](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L89-L130), [drizzle-orm/src/sql/expressions/conditions.ts:1-35](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/expressions/conditions.ts#L1-L35), [drizzle-orm/src/sql/functions/aggregate.ts:1-21](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/aggregate.ts#L1-L21), [drizzle-orm/src/sql/functions/vector.ts:1-39](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/vector.ts#L1-L39)
## SQL Chunks and AST Structure
### Chunk Union and AST Node Types
The core AST representation revolves around the `Chunk` union type and the `SQL` class, which hold fragments, metadata, and nested child nodes. Every part of a compiled query starts as a chunk or a wrapper implementing the `SQLWrapper` interface.
The `Chunk` type defines all valid nodes that can be assembled inside an `SQL` statement tree. These include raw string pieces, database tables, views, columns, raw name identifiers, parameters, placeholders, and nested `SQL` instances.
```typescript
export type Chunk =
| string
| Table
| View
| AnyColumn
| Name
| Param
| Placeholder
| SQL;
```
Sources: [drizzle-orm/src/sql/sql.ts:22-30](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L22-L30)
Any value or schema model implementing the `getSQL()` method satisfies the `SQLWrapper` interface, allowing custom builders and database constructs to integrate directly into query compilation trees.
```typescript
export interface SQLWrapper {
getSQL(): SQL;
shouldOmitSQLParens?(): boolean;
}
```
Sources: [drizzle-orm/src/sql/sql.ts:65-68](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L65-L68)
The table below lists the core AST classes and wrappers, their entity kinds, and their runtime roles during query generation.
| Class / Interface | Entity Kind | Role in AST |
| :--- | :--- | :--- |
| `SQL` | `'SQL'` | Root or nested container holding an array of `SQLChunk` instances, track-used tables, and driver encoders. |
| `StringChunk` | `'StringChunk'` | Holds raw literal SQL string arrays that require no escaping or parameterization. |
| `SQLWrapper` | N/A (Interface) | Protocol implemented by entities capable of returning an internal `SQL` AST via `getSQL()`. |
| `FakePrimitiveParam` | `'FakePrimitiveParam'` | Type-level marker indicating a primitive parameter used in templates; never instantiated at runtime. |
Sources: [drizzle-orm/src/sql/sql.ts:18-20](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L18-L20), [drizzle-orm/src/sql/sql.ts:89-96](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L89-L96), [drizzle-orm/src/sql/sql.ts:103-110](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L103-L110)
> [!NOTE]
> `FakePrimitiveParam` exists strictly at the TypeScript type level to represent primitive parameter values within `sql` template tags, remaining completely uninstantiated during runtime execution.
Sources: [drizzle-orm/src/sql/sql.ts:13-17](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L13-L17)
### SQL Container and Used Tables Tracking
The `SQL` class manages an array of query chunks (`queryChunks: SQLChunk[]`). Upon instantiation, the constructor inspects each chunk; if the chunk is a `Table` instance, it extracts schema prefixes and table names, registering them in the `usedTables` array for reference tracking.
```typescript
constructor(readonly queryChunks: SQLChunk[]) {
for (const chunk of queryChunks) {
if (is(chunk, Table)) {
const schemaName = chunk[Table.Symbol.Schema];
this.usedTables.push(
schemaName === undefined
? chunk[Table.Symbol.Name]
: schemaName + '.' + chunk[Table.Symbol.Name],
);
}
}
}
```
Sources: [drizzle-orm/src/sql/sql.ts:118-130](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L118-L130)
> [!IMPORTANT]
> When compiling subqueries or nested expressions, `SQL` instances propagate their `shouldInlineParams` flag down the tree during recursive query building to override default parameter placeholder behavior.
Sources: [drizzle-orm/src/sql/sql.ts:188-193](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L188-L193)
## Template Tag and Parameter Binding
### Query Configuration and Typings Values
Query building configurations dictate how placeholders, parameters, escape sequences, and casing rules are processed during AST compilation. The `BuildQueryConfig` interface provides the required callbacks and state containers for name escaping, parameter formatting, string literals, casing caches, and index generation contexts.
```typescript
export interface BuildQueryConfig {
casing: CasingCache;
escapeName(name: string): string;
escapeParam(num: number, value: unknown): string;
escapeString(str: string): string;
prepareTyping?: (encoder: DriverValueEncoder) => QueryTypingsValue;
paramStartIndex?: { value: number };
inlineParams?: boolean;
invokeSource?: 'indexes' | undefined;
}
```
Sources: [drizzle-orm/src/sql/sql.ts:32-41](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L32-L41)
Supported driver typing annotations determine how database parameter values are serialized or cast across driver boundaries. The table below outlines every allowed `QueryTypingsValue` constant recognized by the query compiler.
| Query Typing Value | Description / Driver Mapping |
| :--- | :--- |
| `'json'` | Indicates JSON-encoded columns or payload structures. |
| `'decimal'` | Represents arbitrary-precision numeric decimal types. |
| `'time'` | Designates time-of-day temporal values. |
| `'timestamp'` | Represents combined date and time stamps. |
| `'uuid'` | Designates universally unique identifier types. |
| `'date'` | Represents calendar date values. |
| `'none'` | Default untyped driver parameter binding. |
Sources: [drizzle-orm/src/sql/sql.ts:43-43](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L43-L43)
> [!NOTE]
> `FakePrimitiveParam` serves as a type-level marker representing primitive parameters inside template string literals without incurring runtime instantiation overhead.
Sources: [drizzle-orm/src/sql/sql.ts:13-17](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L13-L17)
### Parameter Binding and Inline Mapping
Parameter processing inspects chunks during query building to determine whether values should be bound via driver parameters or serialized directly into the SQL text string. When `inlineParams` is active, or when dealing with unmapped parameters, values are converted via `mapInlineParam`.
```typescript
private mapInlineParam(
chunk: unknown,
{ escapeString }: BuildQueryConfig,
): string {
if (chunk === null) {
return 'null';
}
if (typeof chunk === 'number' || typeof chunk === 'boolean') {
return chunk.toString();
}
if (typeof chunk === 'string') {
return escapeString(chunk);
}
if (typeof chunk === 'object') {
const mappedValueAsString = chunk.toString();
if (mappedValueAsString === '[object Object]') {
return escapeString(JSON.stringify(chunk));
}
return escapeString(mappedValueAsString);
}
throw new Error('Unexpected param value: ' + chunk);
}
```
Sources: [drizzle-orm/src/sql/sql.ts:302-323](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L302-L323)
> [!WARNING]
> Object parameters whose `toString()` representation evaluates to `[object Object]` are automatically serialized via `JSON.stringify` before string escaping when parameter inlining is enabled.
Sources: [drizzle-orm/src/sql/sql.ts:315-321](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L315-L321)
## Query Resolution and Placeholder Substitution
### Query Building Control Flow
The `buildQueryFromSourceParams` method processes arrays of query chunks recursively, dispatching each node type through specialized serialization branches. Telemetry spans wrap query generation via `tracer.startActiveSpan`, emitting query text and parameters to tracing diagnostics.
```typescript
toQuery(config: BuildQueryConfig): QueryWithTypings {
return tracer.startActiveSpan('drizzle.buildSQL', (span) => {
const query = this.buildQueryFromSourceParams(this.queryChunks, config);
span?.setAttributes({
'drizzle.query.text': query.sql,
'drizzle.query.params': JSON.stringify(query.params),
});
return query;
});
}
```
Sources: [drizzle-orm/src/sql/sql.ts:137-146](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L137-L146)
> [!IMPORTANT]
> When query chunks contain arrays, the compiler automatically parenthesizes the items and joins them with commas, constructing an expanded chunk array before re-invoking `buildQueryFromSourceParams`.
Sources: [drizzle-orm/src/sql/sql.ts:176-186](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L176-L186)
### Chunk Serialization Handlers
Different AST chunk types trigger distinct formatting rules during query generation, handling identifiers, schemas, parameters, and wrapper structures.
| Chunk Type | Serialization Behavior |
| :--- | :--- |
| `StringChunk` | Concatenates literal string segments with empty parameter arrays. |
| `Name` | Escapes identifier names using `escapeName`. |
| `Table` | Formats schema-qualified table names or bare names when aliased. |
| `Column` | Resolves column casing via `casing.getColumnCasing` and prefixes table identifiers unless queried within `indexes`. |
| `View` | Formats schema-qualified view identifiers or alias names. |
| `Param` | Binds parameters through `escapeParam`, tracking parameter indices and driver encoders. |
| `Placeholder` | Generates parameter placeholders using the active `paramStartIndex`. |
| `Subquery` | Formats inline subqueries with parentheses and aliases, or referenced CTE names when `isWith` is set. |
Sources: [drizzle-orm/src/sql/sql.ts:164-282](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L164-L282)
> [!NOTE]
> If a `Param` chunk contains a nested `SQL` instance after encoder mapping, the compiler unwraps and processes it recursively via `buildQueryFromSourceParams`.
Sources: [drizzle-orm/src/sql/sql.ts:238-242](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts#L238-L242)
## Comparison and Logical Expressions
### Parameter Binding and Condition Operators
Condition tree constructors leverage template literals and helper functions defined in `drizzle-orm/src/sql/expressions/conditions.ts` to build SQL AST nodes. The `bindIfParam` function inspects values against column encoders, wrapping raw values into `Param` instances when appropriate while leaving columns, tables, views, placeholders, parameters, and SQL wrappers unhindered.
```typescript
export function bindIfParam(value: unknown, column: SQLWrapper): SQLChunk {
if (
isDriverValueEncoder(column)
&& !isSQLWrapper(value)
&& !is(value, Param)
&& !is(value, Placeholder)
&& !is(value, Column)
&& !is(value, Table)
&& !is(value, View)
) {
return new Param(value, column);
}
return value as SQLChunk;
}
```
Sources: [drizzle-orm/src/sql/expressions/conditions.ts:17-30](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/expressions/conditions.ts#L17-L30)
Binary operators construct equality, inequality, and directional comparisons using `sql`` template tags combined with `bindIfParam`.
| Operator Function | SQL Expression Generated | Description |
| :--- | :--- | :--- |
| `eq` | `${left} = ${bindIfParam(right, left)}` | Tests equality between two expressions. |
| `ne` | `${left} <> ${bindIfParam(right, left)}` | Tests inequality between two expressions. |
| `gt` | `${left} > ${bindIfParam(right, left)}` | Tests strictly greater-than. |
| `gte` | `${left} >= ${bindIfParam(right, left)}` | Tests greater-than or equal-to. |
| `lt` | `${left} < ${bindIfParam(right, left)}` | Tests strictly less-than. |
| `lte` | `${left} <= ${bindIfParam(right, left)}` | Tests less-than or equal-to. |
Sources: [drizzle-orm/src/sql/expressions/conditions.ts:62-86](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/expressions/conditions.ts#L62-L86), [drizzle-orm/src/sql/expressions/conditions.ts:195-253](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/expressions/conditions.ts#L195-L253)
> [!WARNING]
> The SQL standard specifies that two `NULL` values are not equal. To check for `NULL` values, developers should use `isNull` instead of `eq(column, null)`.
Sources: [drizzle-orm/src/sql/expressions/conditions.ts:46-51](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/expressions/conditions.ts#L46-L51)
### Logical and Array Membership Combinators
Logical combinators filter out `undefined` conditions dynamically before assembling expression trees. If an `and` or `or` call receives an empty list of valid conditions, it returns `undefined`. If it receives a single valid condition, it returns that `SQL` instance directly without wrapping parentheses.
```typescript
export function and(
...unfilteredConditions: (SQLWrapper | undefined)[]
): SQL | undefined {
const conditions = unfilteredConditions.filter(
(c): c is Exclude => c !== undefined,
);
if (conditions.length === 0) {
return undefined;
}
if (conditions.length === 1) {
return new SQL(conditions);
}
return new SQL([
new StringChunk('('),
sql.join(conditions, new StringChunk(' and ')),
new StringChunk(')'),
]);
}
```
Sources: [drizzle-orm/src/sql/expressions/conditions.ts:105-125](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/expressions/conditions.ts#L105-L125)
Negation, array membership, and null checks complete the condition toolkit. The `not` function prefixes any expression with the `not` keyword. Array checks handle empty arrays specially for `notInArray`, returning a literal `true` expression when no values are provided.
```typescript
export function notInArray(
column: SQLWrapper,
values: (unknown | Placeholder)[] | SQLWrapper,
): SQL {
if (Array.isArray(values)) {
if (values.length === 0) {
return sql`true`;
}
return sql`${column} not in ${values.map((v) => bindIfParam(v, column))}`;
}
return sql`${column} not in ${bindIfParam(values, column)}`;
}
```
Sources: [drizzle-orm/src/sql/expressions/conditions.ts:322-334](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/expressions/conditions.ts#L322-L334)
> [!NOTE]
> Passing an empty array to `notInArray` evaluates to `true` to preserve valid SQL syntax when filtering dynamically.
Sources: [drizzle-orm/src/sql/expressions/conditions.ts:326-329](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/expressions/conditions.ts#L326-L329)
## Dialect Expressions and String Functions
### Dialect Expression Helpers and String Operations
Dialect-specific modules provide specialized string manipulation helpers that integrate driver parameter binding with database-native string syntax. Both the Gel and SingleStore core modules export custom `concat` and `substring` functions that accept column references or aliased fields along with string values, placeholders, or wrapped SQL fragments.
```typescript
export function concat(column: GelColumn | SQL.Aliased, value: string | Placeholder | SQLWrapper): SQL {
return sql`${column} || ${bindIfParam(value, column)}`;
}
export function substring(
column: GelColumn | SQL.Aliased,
{ from, for: _for }: { from?: number | Placeholder | SQLWrapper; for?: number | Placeholder | SQLWrapper },
): SQL {
const chunks: SQLChunk[] = [sql`substring(`, column];
if (from !== undefined) {
chunks.push(sql` from `, bindIfParam(from, column));
}
if (_for !== undefined) {
chunks.push(sql` for `, bindIfParam(_for, column));
}
chunks.push(sql`)`);
return sql.join(chunks);
}
```
Sources: [drizzle-orm/src/gel-core/expressions.ts:8-25](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/expressions.ts#L8-L25), [drizzle-orm/src/singlestore-core/expressions.ts:8-25](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/expressions.ts#L8-L25)
The `concat` helper utilizes the standard concatenation operator (`||`) and passes the right-hand value through `bindIfParam` to ensure proper encoder mapping and driver parameterization. The `substring` helper constructs dynamic chunk lists for extraction queries, conditionally appending `from` and `for` modifiers when defined.
> [!NOTE]
> Both Gel and SingleStore implement identical signatures and AST assembly logic for `concat` and `substring`, utilizing `sql.join` to merge fragmented expression chunks into valid parameterized statements.
Sources: [drizzle-orm/src/gel-core/expressions.ts:8-25](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/expressions.ts#L8-L25), [drizzle-orm/src/singlestore-core/expressions.ts:8-25](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/expressions.ts#L8-L25)
## Aggregate and Vector Functions
### Standard Aggregate Builders
Drizzle provides standard aggregate function wrappers constructed via the `sql` template literal. The `count` function accepts an optional `expression` and defaults to `*` via `sql.raw('*')` when omitted, mapping its resulting type to `number`. Distinct variants such as `countDistinct`, `avgDistinct`, and `sumDistinct` prepend the `distinct` keyword inside the expression block.
```typescript
export function count(expression?: SQLWrapper): SQL {
return sql`count(${expression || sql.raw('*')})`.mapWith(Number);
}
export function countDistinct(expression: SQLWrapper): SQL {
return sql`count(distinct ${expression})`.mapWith(Number);
}
```
Sources: [drizzle-orm/src/sql/functions/aggregate.ts:19-37](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/aggregate.ts#L19-L37)
The following table summarizes the available aggregate functions, their SQL template structures, and their return type mappings:
| Function | Template Expression | Return Type | Source Lines |
| :--- | :--- | :--- | :--- |
| `count` | `count(${expression \|\| sql.raw('*')})` | `number` | [aggregate.ts:19-21](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/aggregate.ts#L19-L21) |
| `countDistinct` | `count(distinct ${expression})` | `number` | [aggregate.ts:35-37](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/aggregate.ts#L35-L37) |
| `avg` | `avg(${expression})` | `string \| null` | [aggregate.ts:51-53](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/aggregate.ts#L51-L53) |
| `avgDistinct` | `avg(distinct ${expression})` | `string \| null` | [aggregate.ts:67-69](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/aggregate.ts#L67-L69) |
| `sum` | `sum(${expression})` | `string \| null` | [aggregate.ts:83-85](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/aggregate.ts#L83-L85) |
| `sumDistinct` | `sum(distinct ${expression})` | `string \| null` | [aggregate.ts:99-101](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/aggregate.ts#L99-L101) |
| `max` | `max(${expression})` | Column data type or `string \| null` | [aggregate.ts:113-115](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/aggregate.ts#L113-L115) |
| `min` | `min(${expression})` | Column data type or `string \| null` | [aggregate.ts:127-129](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/aggregate.ts#L127-L129) |
> [!NOTE]
> Functions like `max` and `min` dynamically inspect whether the passed expression is an instance of `Column`. If so, they map the result to the column's native data type; otherwise, they fall back to `String`.
Sources: [drizzle-orm/src/sql/functions/aggregate.ts:113-115](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/aggregate.ts#L113-L115), [drizzle-orm/src/sql/functions/aggregate.ts:127-129](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/aggregate.ts#L127-L129)
### Vector Distance Operator Abstractions
Vector distance operations combine column references or SQL wrappers with distance operators and target values. The internal helper `toSql` serializes array inputs via `JSON.stringify`, while non-array inputs are embedded directly into the template string.
```typescript
function toSql(value: number[] | string[]): string {
return JSON.stringify(value);
}
export function l2Distance(
column: SQLWrapper | AnyColumn,
value: number[] | string[] | TypedQueryBuilder | string,
): SQL {
if (Array.isArray(value)) {
return sql`${column} <-> ${toSql(value)}`;
}
return sql`${column} <-> ${value}`;
}
```
Sources: [drizzle-orm/src/sql/functions/vector.ts:5-39](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/vector.ts#L5-L39)
The vector distance helpers and their corresponding operators are mapped below:
| Function Name | Operator | Description | Source Lines |
| :--- | :--- | :--- | :--- |
| `l2Distance` | `<->` | Euclidean (L2) distance | [vector.ts:31-39](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/vector.ts#L31-L39) |
| `l1Distance` | `<+>` | Taxicab (L1) distance | [vector.ts:61-69](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/vector.ts#L61-L69) |
| `innerProduct` | `<#>` | Negative inner product | [vector.ts:93-101](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/vector.ts#L93-L101) |
| `cosineDistance` | `<=>` | Cosine distance | [vector.ts:125-133](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/vector.ts#L125-L133) |
| `hammingDistance` | `<~>` | Hamming distance | [vector.ts:150-158](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/vector.ts#L150-L158) |
| `jaccardDistance` | `<%>` | Jaccard distance | [vector.ts:170-178](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/vector.ts#L170-L178) |
> [!WARNING]
> Passing raw JavaScript arrays to vector distance functions triggers `JSON.stringify` serialization via `toSql`, whereas passing query builders or string expressions embeds them directly into the generated AST without JSON wrapping.
Sources: [drizzle-orm/src/sql/functions/vector.ts:5-39](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/functions/vector.ts#L5-L39)
## Related
- [Query Builder Foundation](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/query-builder-foundation)
- [Table and Column Models](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/table-and-column-models)
---
## Technical docs: Table and Column Models
URL: https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/table-and-column-models
Relevant source files
The following files were used as context for generating this wiki page:
- [drizzle-orm/src/sqlite-core/columns/common.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/columns/common.ts)
- [drizzle-kit/src/introspect-pg.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/introspect-pg.ts)
- [drizzle-orm/type-tests/sqlite/tables.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/sqlite/tables.ts)
- [drizzle-orm/src/sqlite-core/table.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/table.ts)
- [drizzle-kit/src/introspect-gel.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/introspect-gel.ts)
- [drizzle-orm/src/column-builder.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/column-builder.ts)
- [drizzle-orm/src/pg-core/indexes.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/indexes.ts)
- [drizzle-kit/src/introspect-singlestore.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/introspect-singlestore.ts)
- [drizzle-kit/src/introspect-mysql.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/introspect-mysql.ts)
- [drizzle-kit/src/sqlgenerator.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/sqlgenerator.ts)
- [drizzle-orm/src/gel-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/dialect.ts)
- [drizzle-orm/src/sqlite-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/dialect.ts)
- [drizzle-orm/src/singlestore-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/dialect.ts)
- [drizzle-orm/src/gel-core/columns/common.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/columns/common.ts)
- [drizzle-orm/src/sqlite-core/primary-keys.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/primary-keys.ts)
- [drizzle-orm/src/table.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/table.ts)
- [drizzle-orm/src/gel-core/indexes.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/indexes.ts)
- [drizzle-orm/src/pg-core/columns/common.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/columns/common.ts)
- [drizzle-kit/src/introspect-sqlite.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/introspect-sqlite.ts)
- [drizzle-orm/src/sqlite-core/indexes.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/indexes.ts)
- [drizzle-orm/src/pg-core/table.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/table.ts)
- [drizzle-orm/src/mysql-core/columns/common.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/columns/common.ts)
- [drizzle-orm/src/alias.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/alias.ts)
- [drizzle-orm/src/sqlite-core/db.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/db.ts)
- [drizzle-orm/src/sqlite-core/columns/integer.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/columns/integer.ts)
- [drizzle-orm/src/mysql-core/table.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/table.ts)
- [drizzle-orm/src/gel-core/table.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/table.ts)
- [drizzle-orm/src/sqlite-core/foreign-keys.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/foreign-keys.ts)
- [drizzle-orm/src/mysql-core/indexes.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/indexes.ts)
- [drizzle-orm/src/sqlite-core/utils.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/utils.ts)
## Overview
Table and Column Models supply the core structural foundation for defining database entities, column definitions, and schema metadata across all supported dialects. They provide the base abstractions and symbol branding needed to construct typed tables, configure column builders, establish foreign keys, and map driver values.
Sources: [drizzle-orm/src/table.ts:42-118](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/table.ts#L42-L118)
By combining declarative TypeScript types with runtime column transformers and table proxy handlers, this system bridges high-level schema definitions with low-level SQL query generation and relational query execution.
Sources: [drizzle-orm/src/alias.ts:10-75](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/alias.ts#L10-L75), [drizzle-orm/src/column-builder.ts:11-26](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/column-builder.ts#L11-L26)
## Core Table Architecture and Invariants
### Base Table Class and Symbol Branding
The `Table` class serves as the root abstraction for all schema entities, implementing `SQLWrapper` and carrying static metadata alongside internal symbol properties. Each table instance is branded at runtime using `IsDrizzleTable` and maintains configuration traits through TypeScript mapped types (`TableConfig`, `InferSelectModel`, and `InferInsertModel`).
Internal state tracking relies on a set of exported symbols located on `Table.Symbol`. These symbols isolate metadata properties from user-defined column names, preserving clean namespace separation for table names, schemas, and alias mapping flags.
```typescript
export class Table implements SQLWrapper {
static readonly [entityKind]: string = 'Table';
declare readonly _: {
readonly brand: 'Table';
readonly config: T;
readonly name: T['name'];
readonly schema: T['schema'];
readonly columns: T['columns'];
readonly inferSelect: InferSelectModel>;
readonly inferInsert: InferInsertModel>;
};
...
```
Sources: [drizzle-orm/src/table.ts:42-60](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/table.ts#L42-L60)
| Symbol Name | Runtime Symbol Key | Purpose |
| :--- | :--- | :--- |
| `Name` | `drizzle:TableName` | Stores the active table name (modifiable during aliasing). |
| `Schema` | `drizzle:Schema` | Stores the optional database schema identifier. |
| `OriginalName` | `drizzle:OriginalName` | Preserves the initial unaliased table name. |
| `Columns` | `drizzle:Columns` | Holds the record mapping column keys to column definitions. |
| `ExtraConfigColumns` | `drizzle:ExtraConfigColumns` | Stores extra configuration columns during table building. |
| `BaseName` | `drizzle:BaseName` | Preserves the pre-transformation name before `tableCreator` hooks. |
| `IsAlias` | `drizzle:IsAlias` | Boolean flag indicating whether the table instance is an alias. |
| `ExtraConfigBuilder` | `drizzle:ExtraConfigBuilder` | Callback reference for evaluating extra table constraints and indexes. |
Sources: [drizzle-orm/src/table.ts:20-40](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/table.ts#L20-L40), [drizzle-orm/src/table.ts:65-112](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/table.ts#L65-L112)
> [!NOTE]
> The `isTable` runtime check validates table instances exclusively by inspecting whether `IsDrizzleTable` exists on the target object, ensuring fast identification without relying on `instanceof` checks that can fail across module boundary versions.
>
> Sources: [drizzle-orm/src/table.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/table.ts#L120-L122)
### Entity Metadata and Relational Inference
Tables expose inference utilities (`$inferSelect` and `$inferInsert`) that evaluate column definitions to construct strict TypeScript models. The `InferModelFromColumns` type maps column configurations, handling database column name remapping when `dbColumnNames` is enabled and distinguishing required versus optional insert keys using column operation markers (`RequiredKeyOnly` and `OptionalKeyOnly`).
```typescript
export type InferModelFromColumns<
TColumns extends Record,
TInferMode extends 'select' | 'insert' = 'select',
TConfig extends { dbColumnNames: boolean; override?: boolean } = { dbColumnNames: false; override: false },
> = Simplify<
TInferMode extends 'insert' ?
& {
[
Key in keyof TColumns & string as RequiredKeyOnly<
MapColumnName,
TColumns[Key]
>
]: GetColumnData;
}
& {
[
Key in keyof TColumns & string as OptionalKeyOnly<
MapColumnName,
TColumns[Key],
TConfig['override']
>
]?: GetColumnData | undefined;
}
: {
[
Key in keyof TColumns & string as MapColumnName<
Key,
TColumns[Key],
TConfig['dbColumnNames']
>
]: GetColumnData;
}
>;
```
Sources: [drizzle-orm/src/table.ts:155-187](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/table.ts#L155-L187)
Functions such as `getTableName` and `getTableUniqueName` extract structural metadata directly from table symbols, providing fully qualified namespace strings (`schema.tablename`) for query builders and the [relational query engine](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/relational-query-engine).
```typescript
export function getTableName(table: T): T['_']['name'] {
return table[TableName];
}
export function getTableUniqueName(table: T): `${T['_']['schema']}.${T['_']['name']}` {
return `${table[Schema] ?? 'public'}.${table[TableName]}`;
}
```
Sources: [drizzle-orm/src/table.ts:143-149](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/table.ts#L143-L149)
## Column Builder Lifecycle and Configuration
### Configuration Contracts and Type Mapping
Column builders manage the definition and serialization attributes of database columns before they are materialized into table columns. The core configuration contract relies on `ColumnBuilderBaseConfig`, which enforces properties such as column name, data type, column type, driver parameters, and enumerated values. The `MakeColumnConfig` utility type processes these base configurations to determine nullability, default presence, primary key status, autoincrement flags, and generated identity configurations across table columns.
```typescript
export interface ColumnBuilderBaseConfig {
name: string;
dataType: TDataType;
columnType: TColumnType;
data: unknown;
driverParam: unknown;
enumValues: string[] | undefined;
}
export type MakeColumnConfig<
T extends ColumnBuilderBaseConfig,
TTableName extends string,
TData = T extends { $type: infer U } ? U : T['data'],
> = {
name: T['name'];
tableName: TTableName;
dataType: T['dataType'];
columnType: T['columnType'];
data: TData;
driverParam: T['driverParam'];
notNull: T extends { notNull: true } ? true : false;
hasDefault: T extends { hasDefault: true } ? true : false;
isPrimaryKey: T extends { isPrimaryKey: true } ? true : false;
isAutoincrement: T extends { isAutoincrement: true } ? true : false;
hasRuntimeDefault: T extends { hasRuntimeDefault: true } ? true : false;
enumValues: T['enumValues'];
baseColumn: T extends { baseBuilder: infer U extends ColumnBuilderBase } ? BuildColumn
: never;
identity: T extends { identity: 'always' } ? 'always' : T extends { identity: 'byDefault' } ? 'byDefault' : undefined;
generated: T extends { generated: infer G } ? unknown extends G ? undefined
: G extends undefined ? undefined
: G
: undefined;
} & {};
```
Sources: [drizzle-orm/src/column-builder.ts:46-79](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/column-builder.ts#L46-L79)
Supported primitive data types span string, number, boolean, array, json, date, bigint, custom, buffer, dateDuration, duration, relDuration, localTime, localDate, and localDateTime. Dialect targets are explicitly restricted to pg, mysql, sqlite, singlestore, common, and gel.
```typescript
export type ColumnDataType =
| 'string'
| 'number'
| 'boolean'
| 'array'
| 'json'
| 'date'
| 'bigint'
| 'custom'
| 'buffer'
| 'dateDuration'
| 'duration'
| 'relDuration'
| 'localTime'
| 'localDate'
| 'localDateTime';
export type Dialect = 'pg' | 'mysql' | 'sqlite' | 'singlestore' | 'common' | 'gel';
```
Sources: [drizzle-orm/src/column-builder.ts:11-28](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/column-builder.ts#L11-L28)
> [!NOTE]
> `ColumnBuilderRuntimeConfig` stores active runtime flags such as `keyAsName`, `notNull`, `hasDefault`, `default`, `defaultFn`, and `onUpdateFn` to evaluate column behaviors during schema building and statement generation.
>
> Sources: [drizzle-orm/src/column-builder.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/column-builder.ts#L102-L109)
### SQLite Integer, Timestamp, and Boolean Builders
SQLite columns demonstrate specialized builder lifecycles and driver value transformations through `SQLiteBaseIntegerBuilder` and its concrete extensions. The `integer` factory function parses optional names and configurations, branching to construct `SQLiteIntegerBuilder`, `SQLiteTimestampBuilder`, or `SQLiteBooleanBuilder` depending on the selected mode.
```typescript
export interface IntegerConfig<
TMode extends 'number' | 'timestamp' | 'timestamp_ms' | 'boolean' =
| 'number'
| 'timestamp'
| 'timestamp_ms'
| 'boolean',
> {
mode: TMode;
}
export function integer(): SQLiteIntegerBuilderInitial<''>;
export function integer(
config?: IntegerConfig,
): Or, Equal> extends true ? SQLiteTimestampBuilderInitial<''>
: Equal extends true ? SQLiteBooleanBuilderInitial<''>
: SQLiteIntegerBuilderInitial<''>;
export function integer(
name: TName,
config?: IntegerConfig,
): Or, Equal> extends true ? SQLiteTimestampBuilderInitial
: Equal extends true ? SQLiteBooleanBuilderInitial
: SQLiteIntegerBuilderInitial;
export function integer(a?: string | IntegerConfig, b?: IntegerConfig) {
const { name, config } = getColumnNameAndConfig(a, b);
if (config?.mode === 'timestamp' || config?.mode === 'timestamp_ms') {
return new SQLiteTimestampBuilder(name, config.mode);
}
if (config?.mode === 'boolean') {
return new SQLiteBooleanBuilder(name, config.mode);
}
return new SQLiteIntegerBuilder(name);
}
export const int = integer;
```
Sources: [drizzle-orm/src/sqlite-core/columns/integer.ts:204-237](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/columns/integer.ts#L204-L237)
| Column Type | Mode Parameter | Driver Parameter Type | Mapped JavaScript Type | Driver Mapping Logic |
| :--- | :--- | :--- | :--- | :--- |
| `SQLiteInteger` | `number` (default) | `number` | `number` | Direct integer storage. |
| `SQLiteTimestamp` | `timestamp` | `number` | `Date` | Multiplies or divides by `1000` for epoch seconds. |
| `SQLiteTimestamp` | `timestamp_ms` | `number` | `Date` | Preserves millisecond epoch numbers directly. |
| `SQLiteBoolean` | `boolean` | `number` | `boolean` | Translates integer `1` and `0` to boolean values. |
Sources: [drizzle-orm/src/sqlite-core/columns/integer.ts:66-202](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/columns/integer.ts#L66-L202)
```mermaid
flowchart TD
A["integer(name, config)"] --> B{config?.mode}
B -->|timestamp / timestamp_ms| C["SQLiteTimestampBuilder"]
B -->|boolean| D["SQLiteBooleanBuilder"]
B -->|undefined / number| E["SQLiteIntegerBuilder"]
C --> F["SQLiteTimestamp.mapFromDriverValue / mapToDriverValue"]
D --> G["SQLiteBoolean.mapFromDriverValue / mapToDriverValue"]
E --> H["SQLiteInteger"]
```
Sources: [drizzle-orm/src/sqlite-core/columns/integer.ts:143-202](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/columns/integer.ts#L143-L202), [drizzle-orm/src/sqlite-core/columns/integer.ts:228-235](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/columns/integer.ts#L228-L235)
> [!CAUTION]
> Calling `defaultNow()` on a `SQLiteTimestampBuilder` is deprecated; column defaults should be assigned using `.default()` with custom SQL expressions instead.
>
> Sources: [drizzle-orm/src/sqlite-core/columns/integer.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/columns/integer.ts#L117-L124)
## Dialect Table Instantiation and Normalization
### Table Creation Functions and Schemas
Table instantiation across database engines relies on dialect-specific table classes that extend the core `Table` abstraction while managing engine-specific symbols and configuration types. The `SQLiteTable` class defines `InlineForeignKeys` symbol branding to track foreign keys declared within column definitions SQLiteTable:
```typescript
export const InlineForeignKeys = Symbol.for('drizzle:SQLiteInlineForeignKeys');
export class SQLiteTable extends Table {
static override readonly [entityKind]: string = 'SQLiteTable';
/** @internal */
static override readonly Symbol = Object.assign({}, Table.Symbol, {
InlineForeignKeys: InlineForeignKeys as typeof InlineForeignKeys,
});
/** @internal */
override [Table.Symbol.Columns]!: NonNullable;
/** @internal */
[InlineForeignKeys]: ForeignKey[] = [];
/** @internal */
override [Table.Symbol.ExtraConfigBuilder]:
| ((self: Record) => SQLiteTableExtraConfig)
| undefined = undefined;
}
```
Sources: [drizzle-orm/src/sqlite-core/table.ts:27-47](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/table.ts#L27-L47)
Similarly, `PgTable` in PostgreSQL and `GelTable` in Gel introduce both `InlineForeignKeys` and `EnableRLS` symbols to support row-level security policy toggles and inline constraints PgTable, GelTable:
```typescript
/** @internal */
export const InlineForeignKeys = Symbol.for('drizzle:PgInlineForeignKeys');
/** @internal */
export const EnableRLS = Symbol.for('drizzle:EnableRLS');
export class PgTable extends Table {
static override readonly [entityKind]: string = 'PgTable';
/** @internal */
static override readonly Symbol = Object.assign({}, Table.Symbol, {
InlineForeignKeys: InlineForeignKeys as typeof InlineForeignKeys,
EnableRLS: EnableRLS as typeof EnableRLS,
});
/**@internal */
[InlineForeignKeys]: ForeignKey[] = [];
/** @internal */
[EnableRLS]: boolean = false;
/** @internal */
override [Table.Symbol.ExtraConfigBuilder]: ((self: Record) => PgTableExtraConfig) | undefined =
undefined;
/** @internal */
override [Table.Symbol.ExtraConfigColumns]: Record = {};
}
```
Sources: [drizzle-orm/src/pg-core/table.ts:28-54](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/table.ts#L28-L54)
```typescript
/** @internal */
export const InlineForeignKeys = Symbol.for('drizzle:GelInlineForeignKeys');
/** @internal */
export const EnableRLS = Symbol.for('drizzle:EnableRLS');
export class GelTable extends Table {
static override readonly [entityKind]: string = 'GelTable';
/** @internal */
static override readonly Symbol = Object.assign({}, Table.Symbol, {
InlineForeignKeys: InlineForeignKeys as typeof InlineForeignKeys,
EnableRLS: EnableRLS as typeof EnableRLS,
});
/**@internal */
[InlineForeignKeys]: ForeignKey[] = [];
/** @internal */
[EnableRLS]: boolean = false;
/** @internal */
override [Table.Symbol.ExtraConfigBuilder]: ((self: Record) => GelTableExtraConfig) | undefined =
undefined;
/** @internal */
override [Table.Symbol.ExtraConfigColumns]: Record = {};
}
```
Sources: [drizzle-orm/src/gel-core/table.ts:28-54](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/table.ts#L28-L54)
`MySqlTable` implements equivalent symbol tracking for MySQL environments MySqlTable:
```typescript
/** @internal */
export const InlineForeignKeys = Symbol.for('drizzle:MySqlInlineForeignKeys');
export class MySqlTable extends Table {
static override readonly [entityKind]: string = 'MySqlTable';
declare protected $columns: T['columns'];
/** @internal */
static override readonly Symbol = Object.assign({}, Table.Symbol, {
InlineForeignKeys: InlineForeignKeys as typeof InlineForeignKeys,
});
/** @internal */
override [Table.Symbol.Columns]!: NonNullable;
/** @internal */
[InlineForeignKeys]: ForeignKey[] = [];
/** @internal */
override [Table.Symbol.ExtraConfigBuilder]:
| ((self: Record) => MySqlTableExtraConfig)
| undefined = undefined;
}
```
Sources: [drizzle-orm/src/mysql-core/table.ts:26-49](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/table.ts#L26-L49)
### Column Builder Parsing and Normalization
During table construction, column definitions can be provided either as a static record map or via a callback function receiving engine-specific column builders (`SQLiteColumnBuilders`, `PgColumnsBuilders`, `MySqlColumnBuilders`, or `GelColumnsBuilders`). The normalization routine resolves these definitions, sets column names, and instantiates the underlying column objects pgTableWithSchema, mysqlTableWithSchema, gelTableWithSchema:
```typescript
export function pgTableWithSchema<
TTableName extends string,
TSchemaName extends string | undefined,
TColumnsMap extends Record,
>(
name: TTableName,
columns: TColumnsMap | ((columnTypes: PgColumnsBuilders) => TColumnsMap),
extraConfig:
| ((self: BuildExtraConfigColumns) => PgTableExtraConfig | PgTableExtraConfigValue[])
| undefined,
schema: TSchemaName,
baseName = name,
): PgTableWithColumns<{
name: TTableName;
schema: TSchemaName;
columns: BuildColumns;
dialect: 'pg';
}> {
const rawTable = new PgTable<{
name: TTableName;
schema: TSchemaName;
columns: BuildColumns;
dialect: 'pg';
}>(name, schema, baseName);
const parsedColumns: TColumnsMap = typeof columns === 'function' ? columns(getPgColumnBuilders()) : columns;
const builtColumns = Object.fromEntries(
Object.entries(parsedColumns).map(([name, colBuilderBase]) => {
const colBuilder = colBuilderBase as PgColumnBuilder;
colBuilder.setName(name);
const column = colBuilder.build(rawTable);
rawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable));
return [name, column];
}),
) as unknown as BuildColumns;
const builtColumnsForExtraConfig = Object.fromEntries(
Object.entries(parsedColumns).map(([name, colBuilderBase]) => {
const colBuilder = colBuilderBase as PgColumnBuilder;
colBuilder.setName(name);
const column = colBuilder.buildExtraConfigColumn(rawTable);
return [name, column];
}),
) as unknown as BuildExtraConfigColumns;
const table = Object.assign(rawTable, builtColumns);
table[Table.Symbol.Columns] = builtColumns;
table[Table.Symbol.ExtraConfigColumns] = builtColumnsForExtraConfig;
if (extraConfig) {
table[PgTable.Symbol.ExtraConfigBuilder] = extraConfig as any;
}
return Object.assign(table, {
enableRLS: () => {
table[PgTable.Symbol.EnableRLS] = true;
return table as PgTableWithColumns<{
name: TTableName;
schema: TSchemaName;
columns: BuildColumns;
dialect: 'pg';
}>;
},
});
}
```
Sources: [drizzle-orm/src/pg-core/table.ts:71-137](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/table.ts#L71-L137)
```typescript
export function mysqlTableWithSchema<
TTableName extends string,
TSchemaName extends string | undefined,
TColumnsMap extends Record,
>(
name: TTableName,
columns: TColumnsMap | ((columnTypes: MySqlColumnBuilders) => TColumnsMap),
extraConfig:
| ((
self: BuildColumns,
) => MySqlTableExtraConfig | MySqlTableExtraConfigValue[])
| undefined,
schema: TSchemaName,
baseName = name,
): MySqlTableWithColumns<{
name: TTableName;
schema: TSchemaName;
columns: BuildColumns;
dialect: 'mysql';
}> {
const rawTable = new MySqlTable<{
name: TTableName;
schema: TSchemaName;
columns: BuildColumns;
dialect: 'mysql';
}>(name, schema, baseName);
const parsedColumns: TColumnsMap = typeof columns === 'function' ? columns(getMySqlColumnBuilders()) : columns;
const builtColumns = Object.fromEntries(
Object.entries(parsedColumns).map(([name, colBuilderBase]) => {
const colBuilder = colBuilderBase as MySqlColumnBuilder;
colBuilder.setName(name);
const column = colBuilder.build(rawTable);
rawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable));
return [name, column];
}),
) as unknown as BuildColumns;
const table = Object.assign(rawTable, builtColumns);
table[Table.Symbol.Columns] = builtColumns;
table[Table.Symbol.ExtraConfigColumns] = builtColumns as unknown as BuildExtraConfigColumns<
TTableName,
TColumnsMap,
'mysql'
>;
if (extraConfig) {
table[MySqlTable.Symbol.ExtraConfigBuilder] = extraConfig as unknown as (
self: Record,
) => MySqlTableExtraConfig;
}
return table;
}
```
Sources: [drizzle-orm/src/mysql-core/table.ts:61-116](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/table.ts#L61-L116)
```typescript
export function gelTableWithSchema<
TTableName extends string,
TSchemaName extends string | undefined,
TColumnsMap extends Record,
>(
name: TTableName,
columns: TColumnsMap | ((columnTypes: GelColumnsBuilders) => TColumnsMap),
extraConfig:
| ((
self: BuildExtraConfigColumns,
) => GelTableExtraConfig | GelTableExtraConfigValue[])
| undefined,
schema: TSchemaName,
baseName = name,
): GelTableWithColumns<{
name: TTableName;
schema: TSchemaName;
columns: BuildColumns;
dialect: 'gel';
}> {
const rawTable = new GelTable<{
name: TTableName;
schema: TSchemaName;
columns: BuildColumns;
dialect: 'gel';
}>(name, schema, baseName);
const parsedColumns: TColumnsMap = typeof columns === 'function' ? columns(getGelColumnBuilders()) : columns;
const builtColumns = Object.fromEntries(
Object.entries(parsedColumns).map(([name, colBuilderBase]) => {
const colBuilder = colBuilderBase as GelColumnBuilder;
colBuilder.setName(name);
const column = colBuilder.build(rawTable);
rawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable));
return [name, column];
}),
) as unknown as BuildColumns;
const builtColumnsForExtraConfig = Object.fromEntries(
Object.entries(parsedColumns).map(([name, colBuilderBase]) => {
const colBuilder = colBuilderBase as GelColumnBuilder;
colBuilder.setName(name);
const column = colBuilder.buildExtraConfigColumn(rawTable);
return [name, column];
}),
) as unknown as BuildExtraConfigColumns;
const table = Object.assign(rawTable, builtColumns);
table[Table.Symbol.Columns] = builtColumns;
table[Table.Symbol.ExtraConfigColumns] = builtColumnsForExtraConfig;
if (extraConfig) {
table[GelTable.Symbol.ExtraConfigBuilder] = extraConfig as any;
}
return Object.assign(table, {
enableRLS: () => {
table[GelTable.Symbol.EnableRLS] = true;
return table as GelTableWithColumns<{
name: TTableName;
schema: TSchemaName;
columns: BuildColumns;
dialect: 'gel';
}>;
},
});
}
```
Sources: [drizzle-orm/src/gel-core/table.ts:73-141](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/table.ts#L73-L141)
> [!NOTE]
> PostgreSQL and Gel table factories build both standard columns and extra config columns (`buildExtraConfigColumn`), enabling table-level constraints to reference column metadata prior to schema serialization.
>
> Sources: [drizzle-orm/src/pg-core/table.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/table.ts#L98-L120), [drizzle-orm/src/gel-core/table.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/table.ts#L102-L124)
> [!WARNING]
> Passing an object instead of an array as the third parameter (`extraConfig`) to table builder functions is deprecated and will be removed in future releases across SQLite, MySQL, and Gel.
>
> Sources: [drizzle-orm/src/sqlite-core/table.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/table.ts#L89-L110), [drizzle-orm/src/mysql-core/table.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/table.ts#L148-L169), [drizzle-orm/src/gel-core/table.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/table.ts#L143-L165)
## Table Proxies and Alias Remapping
### Proxy Handlers and Identifier Aliasing
Table and column aliasing leverage JavaScript `Proxy` objects to intercept property access, symbol evaluation, and schema traversal across query builders and dialect runtimes. The `TableAliasProxyHandler` intercepts core table symbols such as `Table.Symbol.IsAlias`, `Table.Symbol.Name`, and `Table.Symbol.OriginalName` to substitute alias strings while mapping column property accesses through `ColumnAliasProxyHandler` drizzle-orm/src/alias.ts.
```typescript
export class TableAliasProxyHandler implements ProxyHandler {
static readonly [entityKind]: string = 'TableAliasProxyHandler';
constructor(private alias: string, private replaceOriginalName: boolean) {}
get(target: T, prop: string | symbol): any {
if (prop === Table.Symbol.IsAlias) {
return true;
}
if (prop === Table.Symbol.Name) {
return this.alias;
}
if (this.replaceOriginalName && prop === Table.Symbol.OriginalName) {
return this.alias;
}
if (prop === ViewBaseConfig) {
return {
...target[ViewBaseConfig as keyof typeof target],
name: this.alias,
isAlias: true,
};
}
if (prop === Table.Symbol.Columns) {
const columns = (target as Table)[Table.Symbol.Columns];
if (!columns) {
return columns;
}
const proxiedColumns: { [key: string]: any } = {};
Object.keys(columns).map((key) => {
proxiedColumns[key] = new Proxy(
columns[key]!,
new ColumnAliasProxyHandler(new Proxy(target, this)),
);
});
return proxiedColumns;
}
const value = target[prop as keyof typeof target];
if (is(value, Column)) {
return new Proxy(value as AnyColumn, new ColumnAliasProxyHandler(new Proxy(target, this)));
}
return value;
}
}
```
Sources: [drizzle-orm/src/alias.ts:24-75](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/alias.ts#L24-L75)
The proxy mechanism ensures that references to columns or nested relations inherit the modified table context without mutating the underlying schema definitions. Dialect query builders such as SQLiteDialect incorporate these proxy utilities to handle self-joins, derived tables, and subquery projections drizzle-orm/src/sqlite-core/dialect.ts, drizzle-orm/src/singlestore-core/dialect.ts.
```typescript
export function aliasedTable(
table: T,
tableAlias: string,
): T {
return new Proxy(table, new TableAliasProxyHandler(tableAlias, false)) as any;
}
export function aliasedRelation(relation: T, tableAlias: string): T {
return new Proxy(relation, new RelationTableAliasProxyHandler(tableAlias));
}
export function aliasedTableColumn(column: T, tableAlias: string): T {
return new Proxy(
column,
new ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false))),
);
}
```
Sources: [drizzle-orm/src/alias.ts:91-108](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/alias.ts#L91-L108)
> [!NOTE]
> `TableAliasProxyHandler` conditionally overrides `Table.Symbol.OriginalName` based on the boolean flag `replaceOriginalName`, allowing subqueries to retain or overwrite their underlying table identifier during compilation.
>
> Sources: [drizzle-orm/src/alias.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/alias.ts#L27-L40)
### SQL Expression Rewrites
When queries contain nested expressions, subqueries, or aliased chunks, column references within the AST must be recursively updated to match the active table alias. The `mapColumnsInSQLToAlias` function inspects query chunks and wraps columns and subqueries with the designated alias proxy drizzle-orm/src/alias.ts.
```typescript
export function mapColumnsInSQLToAlias(query: SQL, alias: string): SQL {
return sql.join(query.queryChunks.map((c) => {
if (is(c, Column)) {
return aliasedTableColumn(c, alias);
}
if (is(c, SQL)) {
return mapColumnsInSQLToAlias(c, alias);
}
if (is(c, SQL.Aliased)) {
return mapColumnsInAliasedSQLToAlias(c, alias);
}
return c;
}));
}
```
Sources: [drizzle-orm/src/alias.ts:113-126](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/alias.ts#L113-L126)
| Proxy Handler | Target Entity | Intercepted Symbols / Properties | Purpose |
| --- | --- | --- | --- |
| `ColumnAliasProxyHandler` | `Column` | `'table'` | Binds column references to the aliased table or view container. |
| `TableAliasProxyHandler` | `Table` \| `View` | `IsAlias`, `Name`, `OriginalName`, `Columns`, `ViewBaseConfig` | Remaps table identifiers, flags, and column maps to use alias names. |
| `RelationTableAliasProxyHandler` | `Relation` | `'sourceTable'` | Recursively proxies relation source tables for relational graph queries. |
Sources: [drizzle-orm/src/alias.ts:10-89](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/alias.ts#L10-L89)
## Constraint Resolution and Schema Utilities
### Runtime Table Configuration and Entity Inspection
Table configurations, schema constraints, and builder metadata are inspected and resolved at runtime via utility functions like `getTableConfig`. For SQLite tables, this function iterates over column definitions, inline foreign keys, and extra configuration builders, instantiating and categorizing indexes, checks, unique constraints, primary keys, and foreign keys into a unified configuration object drizzle-orm/src/sqlite-core/utils.ts.
```typescript
export function getTableConfig(table: TTable) {
const columns = Object.values(table[SQLiteTable.Symbol.Columns]);
const indexes: Index[] = [];
const checks: Check[] = [];
const primaryKeys: PrimaryKey[] = [];
const uniqueConstraints: UniqueConstraint[] = [];
const foreignKeys: ForeignKey[] = Object.values(table[SQLiteTable.Symbol.InlineForeignKeys]);
const name = table[Table.Symbol.Name];
const extraConfigBuilder = table[SQLiteTable.Symbol.ExtraConfigBuilder];
if (extraConfigBuilder !== undefined) {
const extraConfig = extraConfigBuilder(table[SQLiteTable.Symbol.Columns]);
const extraValues = Array.isArray(extraConfig) ? extraConfig.flat(1) as any[] : Object.values(extraConfig);
for (const builder of Object.values(extraValues)) {
if (is(builder, IndexBuilder)) {
indexes.push(builder.build(table));
} else if (is(builder, CheckBuilder)) {
checks.push(builder.build(table));
} else if (is(builder, UniqueConstraintBuilder)) {
uniqueConstraints.push(builder.build(table));
} else if (is(builder, PrimaryKeyBuilder)) {
primaryKeys.push(builder.build(table));
} else if (is(builder, ForeignKeyBuilder)) {
foreignKeys.push(builder.build(table));
}
}
}
return {
columns,
indexes,
foreignKeys,
checks,
primaryKeys,
uniqueConstraints,
name,
};
}
```
Sources: [drizzle-orm/src/sqlite-core/utils.ts:19-57](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/utils.ts#L19-L57)
Entity resolution checks use type guards to differentiate builder instances such as `IndexBuilder`, `CheckBuilder`, `UniqueConstraintBuilder`, `PrimaryKeyBuilder`, and `ForeignKeyBuilder`, ensuring each constraint is correctly built against the target table instance prior to AST compilation drizzle-orm/src/sqlite-core/utils.ts.
```typescript
for (const builder of Object.values(extraValues)) {
if (is(builder, IndexBuilder)) {
indexes.push(builder.build(table));
} else if (is(builder, CheckBuilder)) {
checks.push(builder.build(table));
} else if (is(builder, UniqueConstraintBuilder)) {
uniqueConstraints.push(builder.build(table));
} else if (is(builder, PrimaryKeyBuilder)) {
primaryKeys.push(builder.build(table));
} else if (is(builder, ForeignKeyBuilder)) {
foreignKeys.push(builder.build(table));
}
}
```
Sources: [drizzle-orm/src/sqlite-core/utils.ts:33-45](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/utils.ts#L33-L45)
> [!NOTE]
> `extractUsedTable` evaluates table inputs across `SQLiteTable`, `Subquery`, `SQLiteViewBase`, and `SQL` expression instances to resolve base table names and used table arrays during AST traversal.
>
> Sources: [drizzle-orm/src/sqlite-core/utils.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/utils.ts#L59-L70)
### Index Builders and Dialect-Specific Options
Index configuration differs across dialects to accommodate specialized storage parameters, concurrency flags, and locking algorithms. PostgreSQL index builders support partial index conditions via `where`, storage options via `with`, access methods, and concurrency modifiers via `concurrently` and `only` drizzle-orm/src/pg-core/indexes.ts.
```typescript
interface IndexConfig {
name?: string;
columns: Partial[];
/**
* If true, the index will be created as `create unique index` instead of `create index`.
*/
unique: boolean;
/**
* If true, the index will be created as `create index concurrently` instead of `create index`.
*/
concurrently?: boolean;
/**
* If true, the index will be created as `create index ... on only ` instead of `create index ... on `.
*/
only: boolean;
/**
* Condition for partial index.
*/
where?: SQL;
/**
* The optional WITH clause specifies storage parameters for the index
*/
with?: Record;
/**
* The optional WITH clause method for the index
*/
method?: 'btree' | string;
}
```
Sources: [drizzle-orm/src/pg-core/indexes.ts:8-42](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/indexes.ts#L8-L42)
MySQL index builders manage index construction algorithms and locks directly within their configuration contracts drizzle-orm/src/mysql-core/indexes.ts.
```typescript
interface IndexConfig {
name: string;
columns: IndexColumn[];
/**
* If true, the index will be created as `create unique index` instead of `create index`.
*/
unique?: boolean;
/**
* If set, the index will be created as `create index ... using { 'btree' | 'hash' }`.
*/
using?: 'btree' | 'hash';
/**
* If set, the index will be created as `create index ... algorithm { 'default' | 'inplace' | 'copy' }`.
*/
algorithm?: 'default' | 'inplace' | 'copy';
/**
* If set, adds locks to the index creation.
*/
lock?: 'default' | 'none' | 'shared' | 'exclusive';
}
```
Sources: [drizzle-orm/src/mysql-core/indexes.ts:6-30](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/indexes.ts#L6-L30)
| Index Configuration Property | Dialects Supported | Purpose / Values |
| --- | --- | --- |
| `name` | PostgreSQL, MySQL | Optional or required string identifier for the index. |
| `columns` | PostgreSQL, MySQL | Array of indexed columns or raw `SQL` expressions. |
| `unique` | PostgreSQL, MySQL | Boolean flag creating a unique index. |
| `concurrently` | PostgreSQL | Creates the index without locking concurrent writes (`create index concurrently`). |
| `only` | PostgreSQL | Restricts index creation to the specified table without inheritance children. |
| `where` | PostgreSQL | Defines a partial index condition using a `SQL` expression. |
| `method` | PostgreSQL, MySQL | Index access method (e.g., `'btree'`, `'hash'`, `'gist'`, `'gin'`, `'brin'`, `'hnsw'`, `'ivfflat'`). |
| `algorithm` | MySQL | Specifies index creation algorithm: `'default'`, `'inplace'`, `'copy'`. |
| `lock` | MySQL | Adds concurrency locks during index creation: `'default'`, `'none'`, `'shared'`, `'exclusive'`. |
Sources: [drizzle-orm/src/pg-core/indexes.ts:8-42](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/indexes.ts#L8-L42), [drizzle-orm/src/mysql-core/indexes.ts:6-30](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/indexes.ts#L6-L30)
## Related
- [Dialects And Schema Schema Definition](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/dialects-and-schema/dialects-and-schema-schema-definition)
- [Relational Query Engine](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/relational-query-engine)
---
## Technical docs: Column Types
URL: https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/database-schema/column-types
Relevant source files
The following files were used as context for generating this wiki page:
* [drizzle-kit/src/introspect-mysql.ts](https://github.com/blade47/drizzle-orm/blob/main/drizzle-kit/src/introspect-mysql.ts)
* [drizzle-kit/src/introspect-gel.ts](https://github.com/blade47/drizzle-orm/blob/main/drizzle-kit/src/introspect-gel.ts)
* [drizzle-kit/src/introspect-singlestore.ts](https://github.com/blade47/drizzle-orm/blob/main/drizzle-kit/src/introspect-singlestore.ts)
* [drizzle-orm/src/pg-core/columns/common.ts](https://github.com/blade47/drizzle-orm/blob/main/drizzle-orm/src/pg-core/columns/common.ts)
* [drizzle-orm/src/pg-core/columns/numeric.ts](https://github.com/blade47/drizzle-orm/blob/main/drizzle-orm/src/pg-core/columns/numeric.ts)
* [drizzle-orm/src/singlestore-core/columns/decimal.ts](https://github.com/blade47/drizzle-orm/blob/main/drizzle-orm/src/singlestore-core/columns/decimal.ts)
* [drizzle-orm/src/column-builder.ts](https://github.com/blade47/drizzle-orm/blob/main/drizzle-orm/src/column-builder.ts)
* [drizzle-orm/src/sqlite-core/columns/numeric.ts](https://github.com/blade47/drizzle-orm/blob/main/drizzle-orm/src/sqlite-core/columns/numeric.ts)
* [drizzle-orm/src/sqlite-core/columns/blob.ts](https://github.com/blade47/drizzle-orm/blob/main/drizzle-orm/src/sqlite-core/columns/blob.ts)
* [drizzle-orm/src/sqlite-core/columns/integer.ts](https://github.com/blade47/drizzle-orm/blob/main/drizzle-orm/src/sqlite-core/columns/integer.ts)
* [drizzle-orm/src/singlestore-core/columns/datetime.ts](https://github.com/blade47/drizzle-orm/blob/main/drizzle-orm/src/singlestore-core/columns/datetime.ts)
* [drizzle-orm/src/singlestore-core/columns/custom.ts](https://github.com/blade47/drizzle-orm/blob/main/drizzle-orm/src/singlestore-core/columns/custom.ts)
* [drizzle-orm/src/gel-core/columns/custom.ts](https://github.com/blade47/drizzle-orm/blob/main/drizzle-orm/src/gel-core/columns/custom.ts)
* [drizzle-orm/src/sqlite-core/columns/custom.ts](https://github.com/blade47/drizzle-orm/blob/main/drizzle-orm/src/sqlite-core/columns/custom.ts)
Column Types in Drizzle provide a robust, type-safe interface for mapping database schemas to TypeScript objects. By defining a set of core builders and runtime definitions, Drizzle ensures that every column in a table can be accurately queried, validated, and serialized to the underlying database dialect, whether it is PostgreSQL, MySQL, SQLite, Gel, or SingleStore.
The system is architected around a separation between the build phase and the runtime phase. Builder classes, such as those derived from `PgColumnBuilder` or `SQLiteColumnBuilder`, manage configurations—such as nullability, default values, and primary key constraints—during the schema definition phase. When a table is built, these builders transition into runtime column instances, which hold the logic for data transformation between the driver's raw output and the application's domain types.
Design decisions within this subsystem prioritize type inference and dialect-specific abstraction. Builders use generics to track data types (e.g., `'string'`, `'number'`, `'boolean'`), while the column classes handle dialect-specific serialization quirks, such as different integer representations or JSON/Blob handling. This layered design allows Drizzle to expose a unified API surface while maintaining the performance and flexibility required for cross-dialect database management.
## Core Builder Infrastructure
The `PgColumnBuilder` or `SQLiteColumnBuilder` classes (and their equivalents) are the roots for column definitions in their respective dialects. Their primary purpose is to collect configuration metadata before a table is fully realized. They implement the chainable API used in table definitions, such as `.notNull()`, `.default()`, and `.primaryKey()`.
Internally, the `config` object acts as a state container. When you call `.notNull()`, the builder simply sets `this.config.notNull = true` and returns `this` cast to a specific type, ensuring the TypeScript compiler reflects this state change for subsequent chain calls.
Sources: [drizzle-orm/src/pg-core/columns/common.ts:38-43](https://github.com/blade47/drizzle-orm/blob/main/drizzle-orm/src/pg-core/columns/common.ts#L38-L43), [drizzle-orm/src/sqlite-core/columns/common.ts:6](https://github.com/blade47/drizzle-orm/blob/main/drizzle-orm/src/sqlite-core/columns/common.ts#L6)
## Dialect-Specific Column Implementations
While building interfaces share commonality, actual data type implementation is split by dialect. For example, `PgNumericBuilder` and `SQLiteNumericBuilder` both offer numeric column support but handle the mapping logic to their respective driver's outputs differently.
In the `PgNumeric` implementation, the `mapFromDriverValue` function is designed to handle `unknown` inputs, converting them to `string` if they are not already, ensuring consistent behavior despite database variability. Conversely, the `SQLiteNumericNumber` implementation specifically maps its inputs to `number` type, demonstrating how builders and runtime definitions tailor the interface based on the requested `mode`.
Sources: [drizzle-orm/src/pg-core/columns/numeric.ts:40-67](https://github.com/blade47/drizzle-orm/blob/main/drizzle-orm/src/pg-core/columns/numeric.ts#L40-L67), [drizzle-orm/src/sqlite-core/columns/numeric.ts:37-49](https://github.com/blade47/drizzle-orm/blob/main/drizzle-orm/src/sqlite-core/columns/numeric.ts#L37-L49), [drizzle-orm/src/sqlite-core/columns/numeric.ts:80-94](https://github.com/blade47/drizzle-orm/blob/main/drizzle-orm/src/sqlite-core/columns/numeric.ts#L80-L94)
## Custom Type Support
Drizzle provides a `customType` function for each dialect to support proprietary or complex database types that are not explicitly covered by the core library. This subsystem allows developers to specify the underlying SQL data type via a `dataType` function and provide custom `toDriver` and `fromDriver` mapping functions.
When a column is defined via `customType`, the builder instance (e.g., `SingleStoreCustomColumnBuilder` or `SQLiteCustomColumnBuilder`) holds the configuration, while the resulting column class instance encapsulates the mapping logic. This architecture prevents core code from needing awareness of every possible niche database type while still providing seamless integration.
Sources: [drizzle-orm/src/singlestore-core/columns/custom.ts:26-59](https://github.com/blade47/drizzle-orm/blob/main/drizzle-orm/src/singlestore-core/columns/custom.ts#L26-L59), [drizzle-orm/src/sqlite-core/columns/custom.ts:25-58](https://github.com/blade47/drizzle-orm/blob/main/drizzle-orm/src/sqlite-core/columns/custom.ts#L25-L58)
## Lifecycle and Initialization Flow
The transition from a definition to a concrete database object involves a specific initialization sequence. When a table is declared, the framework instantiates the builder classes. The `build()` method is then invoked, which consumes the `config` object from the builder and initializes the runtime column class.
For example, when constructing an array column in PostgreSQL:
1. `PgArrayBuilder` is initialized with a base builder.
2. The user calls `.build(table)`.
3. `PgArrayBuilder` instantiates the base column and passes it to the `PgArray` constructor.
4. The `PgArray` constructor sets the array-specific SQL type, such as `integer[]`.
Sources: [drizzle-orm/src/pg-core/columns/common.ts:260-307](https://github.com/blade47/drizzle-orm/blob/main/drizzle-orm/src/pg-core/columns/common.ts#L260-L307)
## Serialization and Introspection Logic
Drizzle Kit performs introspection to convert raw database schema data back into Drizzle ORM TypeScript code. This involves mapping raw column types back to Drizzle function calls.
The `schemaToTypeScript` function in the MySQL introspector, for instance, iterates over table columns, patches type strings using a lookup table (`importsPatch`), and then dispatches the result to a `column()` function. This function acts as a factory, matching the string type to a constructor for the correct builder, and generating the necessary `.default()` or `.primaryKey()` chain calls.
Sources: [drizzle-kit/src/introspect-mysql.ts:133-195](https://github.com/blade47/drizzle-orm/blob/main/drizzle-kit/src/introspect-mysql.ts#L133-L195), [drizzle-kit/src/introspect-mysql.ts:386-416](https://github.com/blade47/drizzle-orm/blob/main/drizzle-kit/src/introspect-mysql.ts#L386-L416)
> [!NOTE]
> When introspecting columns, the framework maps "int unsigned" types to standard integer builders and applies an `{ unsigned: true }` parameter in the generated code.
## Data Mapping Mechanisms
Each column type contains logic to bridge the gap between driver data and application data. `mapFromDriverValue` and `mapToDriverValue` are the primary lifecycle hooks for this conversion.
For instance, the `SQLiteBlobJson` column type defines how it handles raw binary data:
```typescript
override mapFromDriverValue(value: Buffer | Uint8Array | ArrayBuffer): T['data'] {
// ... decoding logic
return JSON.parse(buf.toString('utf8'));
}
```
This is critical because SQLite doesn't have a native JSON type; it forces developers to store JSON objects in `blob` or `text` columns, and this mapping function abstracts that limitation entirely away from the developer.
Sources: [drizzle-orm/src/sqlite-core/columns/blob.ts:100-114](https://github.com/blade47/drizzle-orm/blob/main/drizzle-orm/src/sqlite-core/columns/blob.ts#L100-L114)
## Design Trade-offs
| Design Choice | Benefit | Cost |
| ----------------------------- | -------------------------------------------------- | ---------------------------------------------------------- |
| **Separate Builder Class** | Decouples runtime logic from schema configuration. | Requires double instantiation (builder → column instance). |
| **Dialect-specific Builders** | Allows for exact SQL feature mapping per database. | Increased codebase size through specialized classes. |
| **Type-safe Mapper** | Prevents runtime data corruption at the boundary. | Performance overhead during heavy read/write operations. |
Sources: [drizzle-orm/src/column-builder.ts:185-317](https://github.com/blade47/drizzle-orm/blob/main/drizzle-orm/src/column-builder.ts#L185-L317), [drizzle-orm/src/pg-core/columns/numeric.ts:17-38](https://github.com/blade47/drizzle-orm/blob/main/drizzle-orm/src/pg-core/columns/numeric.ts#L17-L38)
## Related
* \[\[Schema Declarations]]
---
## Technical docs: Relational Query Engine
URL: https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/relational-query-engine
Relevant source files
The following files were used as context for generating this wiki page:
- [drizzle-orm/src/gel-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/dialect.ts)
- [drizzle-orm/src/mysql-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/dialect.ts)
- [drizzle-orm/src/pg-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/dialect.ts)
- [drizzle-orm/src/singlestore-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/dialect.ts)
- [drizzle-orm/src/sqlite-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/dialect.ts)
- [drizzle-orm/src/relations.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/relations.ts)
- [drizzle-kit/src/introspect-pg.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/introspect-pg.ts)
- [drizzle-orm/src/pg-core/query-builders/query.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query.ts)
- [drizzle-orm/src/mysql-core/query-builders/query.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/query-builders/query.ts)
- [drizzle-orm/src/gel-core/query-builders/query.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/query.ts)
- [drizzle-orm/src/singlestore-core/query-builders/query.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/query-builders/query.ts)
- [drizzle-orm/src/sqlite-core/query-builders/query.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/query.ts)
- [drizzle-kit/src/serializer/studio.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/serializer/studio.ts)
- [drizzle-orm/type-tests/geldb/db-rel.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/geldb/db-rel.ts)
- [drizzle-orm/type-tests/mysql/db-rel.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/mysql/db-rel.ts)
- [drizzle-orm/type-tests/pg/db-rel.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/pg/db-rel.ts)
- [drizzle-orm/src/operations.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/operations.ts)
- [drizzle-orm/src/selection-proxy.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/selection-proxy.ts)
## Overview
The Relational Query Engine serves as Drizzle's high-level declarative query layer, translating nested TypeScript query definitions into optimized, dialect-specific SQL execution plans across multiple database engines. It solves the complexity of querying graph-shaped relational data structures by bridging typed schema definitions with underlying driver sessions through dedicated query builder classes like `PgRelationalQuery`, `MySqlRelationalQuery`, `GelRelationalQuery`, `SingleStoreRelationalQuery`, and `SQLiteRelationalQuery`. Key architectural decisions include encapsulating query promises and execution lifecycles, supporting nested filtering, pagination, and sorting via `findMany` and `findFirst`, and normalizing graph relations across primary and non-primary key constraints. It interacts closely with underlying database dialects to construct lateral subqueries, manage table aliases, apply selection masks, and execute row-mapping transformations on fetched database records.
Sources: [drizzle-orm/src/pg-core/query-builders/query.ts:19-110](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query.ts#L19-L110), [drizzle-orm/src/mysql-core/query-builders/query.ts:23-74](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/query-builders/query.ts#L23-L74), [drizzle-orm/src/gel-core/query-builders/query.ts:19-63](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/query.ts#L19-L63), [drizzle-orm/src/singlestore-core/query-builders/query.ts:22-70](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/query-builders/query.ts#L22-L70), [drizzle-orm/src/sqlite-core/query-builders/query.ts:22-96](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/query.ts#L22-L96)
## Relation Declarations and Metadata Modeling
### Schema Definition and Helpers
The relational metadata layer begins with public schema definition helpers and typed relation descriptors. The `relations` function accepts a table and a callback yielding a record of `Relation` objects, automatically binding each entry to its field name via `value.withFieldName(key)`. The helpers `createOne` and `createMany` construct `One` and `Many` relation descriptors respectively, where `createOne` evaluates nullability by inspecting whether all component fields have `notNull: true`.
```typescript
export function relations<
TTableName extends string,
TRelations extends Record>,
>(
table: AnyTable<{ name: TTableName }>,
relations: (helpers: TableRelationsHelpers) => TRelations,
): Relations {
return new Relations(
table,
(helpers: TableRelationsHelpers) =>
Object.fromEntries(
Object.entries(relations(helpers)).map(([key, value]) => [
key,
value.withFieldName(key),
]),
) as TRelations,
);
}
```
Sources: [drizzle-orm/src/relations.ts:502-519](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/relations.ts#L502-L519)
The engine extracts complete relational schemas using `extractTablesRelationalConfig`, which iterates over raw schema entries, normalizes single-default schema wrappers, and resolves forward references through `relationsBuffer` when relations are declared before their target tables.
| Configuration Field | Type | Purpose |
| :--- | :--- | :--- |
| `tsName` | `string` | TypeScript schema object key for the table |
| `dbName` | `string` | Physical database table identifier name |
| `schema` | `string \| undefined` | Optional database schema namespace |
| `columns` | `Record` | Mapped column definitions |
| `relations` | `Record` | Registered table relations |
| `primaryKey` | `AnyColumn[]` | Resolved primary key column array |
Sources: [drizzle-orm/src/relations.ts:416-500](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/relations.ts#L416-L500)
> [!NOTE]
> When schema entries contain a single `'default'` property holding a nested record, `extractTablesRelationalConfig` automatically unwraps it before iterating over table and relation definitions.
> Sources: [drizzle-orm/src/relations.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/relations.ts#L422-L428)
### Graph Relation Normalization
Relation graph normalization resolves mapping fields between source and target tables when explicit join configurations are omitted. The `normalizeRelation` function inspects whether a relation is an instance of `One` containing an explicit `RelationConfig`. If explicit fields and references are present, they are returned directly. Otherwise, the engine looks up the referenced table configuration in the schema and searches for matching reverse relations.
```typescript
export function normalizeRelation(
schema: TablesRelationalConfig,
tableNamesMap: Record,
relation: Relation,
): NormalizedRelation {
if (is(relation, One) && relation.config) {
return {
fields: relation.config.fields,
references: relation.config.references,
};
}
...
```
Sources: [drizzle-orm/src/relations.ts:559-569](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/relations.ts#L559-L569)
Reverse relation matching evaluates either matching explicit `relationName` properties or linking back via `referencedTable === relation.sourceTable`. If multiple reverse relations match without a disambiguating name, an error is thrown. When a single reverse `One` relation is found, its fields and references are inverted to establish the normalized connection path.
> [!WARNING]
> Omitting an explicit `relationName` when multiple bidirectional relations exist between the same two tables causes `normalizeRelation` to throw an ambiguous match error.
> Sources: [drizzle-orm/src/relations.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/relations.ts#L608-L618)
## Relational Query Builder Classes
### Relational Query Builder Construction and Methods
Dialect-specific relational query builders coordinate schema definitions, table mappings, and session handlers to instantiate executable queries. Each dialect exports a `RelationalQueryBuilder` class that exposes `findMany` and `findFirst` methods accepting type-safe configuration objects restricted by `KnownKeysOnly`. The `findFirst` method wraps the query configuration by setting `limit: 1` and marks the internal execution mode as `'first'`, whereas `findMany` defaults to `'many'`.
| Dialect Module | Builder Class Name | Query Runner Class Name | Session Type |
| :--- | :--- | :--- | :--- |
| PostgreSQL (`pg-core`) | `RelationalQueryBuilder` | `PgRelationalQuery` | `PgSession` |
| MySQL (`mysql-core`) | `RelationalQueryBuilder` | `MySqlRelationalQuery` | `MySqlSession` |
| Gel (`gel-core`) | `RelationalQueryBuilder` | `GelRelationalQuery` | `GelSession` |
| SingleStore (`singlestore-core`) | `RelationalQueryBuilder` | `SingleStoreRelationalQuery` | `SingleStoreSession` |
| SQLite (`sqlite-core`) | `RelationalQueryBuilder` | `SQLiteRelationalQuery` / `SQLiteSyncRelationalQuery` | `SQLiteSession` |
Sources: [drizzle-orm/src/pg-core/query-builders/query.ts:19-63](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query.ts#L19-L63), [drizzle-orm/src/mysql-core/query-builders/query.ts:23-74](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/query-builders/query.ts#L23-L74), [drizzle-orm/src/gel-core/query-builders/query.ts:19-63](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/query.ts#L19-L63), [drizzle-orm/src/singlestore-core/query-builders/query.ts:22-70](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/query-builders/query.ts#L22-L70), [drizzle-orm/src/sqlite-core/query-builders/query.ts:22-96](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/query.ts#L22-L96)
```typescript
findMany>(
config?: KnownKeysOnly>,
): PgRelationalQuery[]> {
return new PgRelationalQuery(
this.fullSchema,
this.schema,
this.tableNamesMap,
this.table,
this.tableConfig,
this.dialect,
this.session,
config ? (config as DBQueryConfig<'many', true>) : {},
'many',
);
}
findFirst, 'limit'>>(
config?: KnownKeysOnly, 'limit'>>,
): PgRelationalQuery | undefined> {
return new PgRelationalQuery(
this.fullSchema,
this.schema,
this.tableNamesMap,
this.table,
this.tableConfig,
this.dialect,
this.session,
config ? { ...(config as DBQueryConfig<'many', true> | undefined), limit: 1 } : { limit: 1 },
'first',
);
}
```
Sources: [drizzle-orm/src/pg-core/query-builders/query.ts:32-62](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query.ts#L32-L62)
> [!NOTE]
> In MySQL and SingleStore builders, relational query classes are parameterized by higher-kinded types (`PreparedQueryHKTBase`) to allow engines to generate dialect-specific prepared query handles.
> Sources: [drizzle-orm/src/mysql-core/query-builders/query.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/query-builders/query.ts#L23-L43), [drizzle-orm/src/singlestore-core/query-builders/query.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/query-builders/query.ts#L22-L41)
### Execution Lifecycle and Query Compilation
Relational query runner classes inherit from `QueryPromise` and implement query compilation, statement preparation, and row mapping. When `.execute()` or `.prepare()` is invoked, the runner calls an internal compilation method such as `_toSQL()` or `_getQuery()` which delegates to the dialect to build the underlying SQL abstract syntax tree (AST). For instance, PostgreSQL and Gel invoke `dialect.buildRelationalQueryWithoutPK`, whereas MySQL checks the connection mode (`planetscale`) to determine whether to build queries without lateral subqueries.
```typescript
private _getQuery() {
const query = this.mode === 'planetscale'
? this.dialect.buildRelationalQueryWithoutLateralSubqueries({
fullSchema: this.fullSchema,
schema: this.schema,
tableNamesMap: this.tableNamesMap,
table: this.table,
tableConfig: this.tableConfig,
queryConfig: this.config,
tableAlias: this.tableConfig.tsName,
})
: this.dialect.buildRelationalQuery({
fullSchema: this.fullSchema,
schema: this.schema,
tableNamesMap: this.tableNamesMap,
table: this.table,
tableConfig: this.tableConfig,
queryConfig: this.config,
tableAlias: this.tableConfig.tsName,
});
return query;
}
```
Sources: [drizzle-orm/src/mysql-core/query-builders/query.ts:114-135](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/query-builders/query.ts#L114-L135)
Once compiled into SQL, the query is passed to the session via `prepareQuery` (or `prepareOneTimeQuery` in SQLite). The session callback processes raw database rows by executing `mapRelationalRow`, passing the schema table configuration, row selection mask, and column mapping utility. If the query execution mode is set to `'first'`, the result mapper extracts and returns the first element (`rows[0]`), otherwise returning the full array.
```typescript
(rawRows, mapColumnValue) => {
const rows = rawRows.map((row) =>
mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue)
);
if (this.mode === 'first') {
return rows[0] as TResult;
}
return rows as TResult;
},
);
```
Sources: [drizzle-orm/src/pg-core/query-builders/query.ts:99-108](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query.ts#L99-L108)
> [!WARNING]
> SQLite provides separate asynchronous (`SQLiteRelationalQuery`) and synchronous (`SQLiteSyncRelationalQuery`) classes where synchronous executions bypass promises and immediately invoke `.get()` or `.all()` through `executeRaw()`.
> Sources: [drizzle-orm/src/sqlite-core/query-builders/query.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/query.ts#L98-L207)
## Lateral Joins and Subquery Compilation
### Dialect-Specific Subquery Strategies
Different database engines impose distinct constraints on how relational joins and nested subqueries are compiled. Drizzle accommodates these engine-specific capabilities by delegating query construction to dialect methods tailored to each backend's support for lateral subqueries, correlated references, and table primary key requirements.
```typescript
private _getQuery() {
const query = this.mode === 'planetscale'
? this.dialect.buildRelationalQueryWithoutLateralSubqueries({
fullSchema: this.fullSchema,
schema: this.schema,
tableNamesMap: this.tableNamesMap,
table: this.table,
tableConfig: this.tableConfig,
queryConfig: this.config,
tableAlias: this.tableConfig.tsName,
})
: this.dialect.buildRelationalQuery({
fullSchema: this.fullSchema,
schema: this.schema,
tableNamesMap: this.tableNamesMap,
table: this.table,
tableConfig: this.tableConfig,
queryConfig: this.config,
tableAlias: this.tableConfig.tsName,
});
return query;
}
```
Sources: [drizzle-orm/src/mysql-core/query-builders/query.ts:114-135](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/query-builders/query.ts#L114-L135)
As shown in the MySQL relational query builder, the dialect branch inspection explicitly checks whether the execution target is running under PlanetScale mode. When `this.mode === 'planetscale'`, the query builder invokes `buildRelationalQueryWithoutLateralSubqueries` instead of standard `buildRelationalQuery`. This branching is required because serverless MySQL hosting environments often lack full lateral join support or enforce restrictions on correlated subquery constructs.
### Keyless and Specialized Compilation Methods
Beyond MySQL's conditional dispatch, PostgreSQL and Gel employ `buildRelationalQueryWithoutPK` to handle relational queries where primary key assumptions or table structures require specialized AST generation.
```typescript
private _getQuery() {
return this.dialect.buildRelationalQueryWithoutPK({
fullSchema: this.fullSchema,
schema: this.schema,
tableNamesMap: this.tableNamesMap,
table: this.table,
tableConfig: this.tableConfig,
queryConfig: this.config,
tableAlias: this.tableConfig.tsName,
});
}
```
Sources: [drizzle-orm/src/pg-core/query-builders/query.ts:116-126](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query.ts#L116-L126)
| Dialect / Core | Target Method | Branch Condition / Purpose |
| --- | --- | --- |
| PostgreSQL (`pg-core`) | `buildRelationalQueryWithoutPK` | Compiles relational queries without relying on explicit primary key column lookups in subquery correlations. |
| MySQL (`mysql-core`) | `buildRelationalQueryWithoutLateralSubqueries` | Executed when `mode === 'planetscale'` to avoid lateral join features unsupported by PlanetScale. |
| MySQL (`mysql-core`) | `buildRelationalQuery` | Standard MySQL path utilizing lateral subqueries and advanced join syntax. |
| SingleStore (`singlestore-core`) | `buildRelationalQuery` | Standard SingleStore path for relational query compilation. |
| SQLite (`sqlite-core`) | `buildRelationalQuery` | Standard SQLite path compiling relational selections into AST structures. |
Sources: [drizzle-orm/src/pg-core/query-builders/query.ts:116-126](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query.ts#L116-L126), [drizzle-orm/src/mysql-core/query-builders/query.ts:114-135](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/query-builders/query.ts#L114-L135), [drizzle-orm/src/gel-core/query-builders/query.ts:116-126](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/query.ts#L116-L126), [drizzle-orm/src/singlestore-core/query-builders/query.ts:109-119](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/query-builders/query.ts#L109-L119), [drizzle-orm/src/sqlite-core/query-builders/query.ts:129-138](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/query.ts#L129-L138)
> [!CAUTION]
> Attempting to execute standard lateral-join-based relational queries against a PlanetScale MySQL instance will fail at runtime unless the engine mode is explicitly configured to `'planetscale'`, which triggers `buildRelationalQueryWithoutLateralSubqueries`.
> Sources: [drizzle-orm/src/mysql-core/query-builders/query.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/query-builders/query.ts#L114-L135)
## Selection Masking and Dynamic Aliasing
### Selection Proxy Wrapping and Proxy Handlers
Selection masking and dynamic aliasing in Drizzle are governed by `SelectionProxyHandler`, which implements the JavaScript `ProxyHandler` interface across subqueries, record sets, and database views. When properties are accessed on a selection proxy, the handler intercepts symbol and string lookups to manage `_` metadata configurations, view configurations, and column selections.
```typescript
get(subquery: T, prop: string | symbol): any {
if (prop === '_') {
return {
...subquery['_' as keyof typeof subquery],
selectedFields: new Proxy(
(subquery as Subquery)._.selectedFields,
this as ProxyHandler>,
),
};
}
if (prop === ViewBaseConfig) {
return {
...subquery[ViewBaseConfig as keyof typeof subquery],
selectedFields: new Proxy(
(subquery as View)[ViewBaseConfig].selectedFields,
this as ProxyHandler>,
),
};
}
```
Sources: [drizzle-orm/src/selection-proxy.ts:47-66](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/selection-proxy.ts#L47-L66)
The proxy handler evaluates accessed properties to determine whether they represent stored columns, raw SQL expressions, aliased SQL chunks, or nested objects. When a column is encountered and an alias is configured, the handler wraps the column and its underlying table within `ColumnAliasProxyHandler` and `TableAliasProxyHandler` respectively.
```typescript
if (is(value, Column)) {
if (this.config.alias) {
return new Proxy(
value,
new ColumnAliasProxyHandler(
new Proxy(
value.table,
new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false),
),
),
);
}
return value;
}
```
Sources: [drizzle-orm/src/selection-proxy.ts:100-113](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/selection-proxy.ts#L100-L113)
### Column Projection Scoping and SQL Behavior
The configuration options accepted by `SelectionProxyHandler` control how raw SQL expressions and aliased fields behave during query building and view generation.
| Configuration Key | Type | Default / Options | Purpose |
| --- | --- | --- | --- |
| `alias` | `string` | `undefined` | Table alias applied to intercepted columns during proxy wrapping. |
| `sqlAliasedBehavior` | `'sql' \| 'alias'` | Required | Determines whether `SQL.Aliased` returns the underlying expression (`'sql'`) or the field alias (`'alias'`). |
| `sqlBehavior` | `'sql' \| 'error'` | Required | Determines whether unaliased raw `SQL` expressions return the expression or throw a type/runtime error. |
| `replaceOriginalName` | `boolean` | `false` | Replaces the original column name with its alias, primarily used when creating database views. |
Sources: [drizzle-orm/src/selection-proxy.ts:13-41](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/selection-proxy.ts#L13-L41)
> [!WARNING]
> Accessing a raw SQL field from a subquery that lacks an explicit alias will throw an error at runtime and evaluate to a Drizzle type-level error when `sqlBehavior` is set to `'error'`.
> Sources: [drizzle-orm/src/selection-proxy.ts:90-98](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/selection-proxy.ts#L90-L98)
> [!NOTE]
> `SQL.Aliased` instances that originated inside a prior subquery carry `isSelectionField: true`, preventing the proxy handler from mistakenly returning raw underlying SQL expressions when `sqlAliasedBehavior` is set to `'sql'`.
> Sources: [drizzle-orm/src/selection-proxy.ts:79-88](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/selection-proxy.ts#L79-L88)
## Result Hydration and Row Mapping
### Relational Row Transformation and Mapping Lifecycles
After database sessions execute compiled relational queries, raw tabular rows returned by drivers require structural reshaping into nested object graphs matching the user's schema and selection configuration. Across PostgreSQL, MySQL, SQLite, SingleStore, and Gel dialects, this post-query phase is driven by `mapRelationalRow`, which processes raw row data and column value mappers provided by underlying database drivers.
```typescript
(rawRows, mapColumnValue) => {
const rows = rawRows.map((row) =>
mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue)
);
if (this.mode === 'first') {
return rows[0] as TResult;
}
return rows as TResult;
},
```
Sources: [drizzle-orm/src/pg-core/query-builders/query.ts:99-107](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query.ts#L99-L107)
For asynchronous and synchronous session configurations, the execution pipeline wraps the raw rows mapper inside prepared query definitions. Depending on whether the query mode is configured as `'many'` or `'first'`, the result handler returns either an array of fully hydrated entities or extracts the initial index element.
```typescript
(rawRows, mapColumnValue) => {
const rows = rawRows.map((row) =>
mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue)
);
if (this.mode === 'first') {
return rows[0] as TResult;
}
return rows as TResult;
},
```
Sources: [drizzle-orm/src/sqlite-core/query-builders/query.ts:152-160](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/query.ts#L152-L160)
### Execution and Preparation Modalities
Different query runner implementations manage row mapping through dialect-specific prepared statements and query promises.
| Dialect Runner Class | Method / Hook | Mode Parameter | Return Processing |
| --- | --- | --- | --- |
| `PgRelationalQuery` | `_prepare` | `'many'` \| `'first'` | Maps raw rows with `mapRelationalRow`, slicing index `0` for `'first'`. |
| `MySqlRelationalQuery` | `prepare` | `'many'` \| `'first'` | Iterates over `rawRows` via `mapRelationalRow` without column value mappers. |
| `SQLiteRelationalQuery` | `_prepare` | `'many'` \| `'first'` | Dispatches to session `prepareQuery` or `prepareOneTimeQuery` with driver mappers. |
| `GelRelationalQuery` | `_prepare` | `'many'` \| `'first'` | Executes via Gel session wrapper, applying active telemetry span tracing. |
| `SingleStoreRelationalQuery` | `prepare` | `'many'` \| `'first'` | Processes result sets via SingleStore session query preparation layer. |
Sources: [drizzle-orm/src/pg-core/query-builders/query.ts:90-108](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query.ts#L90-L108), [drizzle-orm/src/mysql-core/query-builders/query.ts:99-111](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/query-builders/query.ts#L99-L111), [drizzle-orm/src/sqlite-core/query-builders/query.ts:142-161](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/query.ts#L142-L161), [drizzle-orm/src/gel-core/query-builders/query.ts:90-108](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/query.ts#L90-L108), [drizzle-orm/src/singlestore-core/query-builders/query.ts:94-106](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/query-builders/query.ts#L94-L106)
> [!NOTE]
> PostgreSQL, Gel, and SQLite sessions pass a secondary `mapColumnValue` callback into `mapRelationalRow`, enabling custom type decoding per column during row deserialization.
> Sources: [drizzle-orm/src/pg-core/query-builders/query.ts:99-102](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query.ts#L99-L102), [drizzle-orm/src/gel-core/query-builders/query.ts:99-102](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/query.ts#L99-L102), [drizzle-orm/src/sqlite-core/query-builders/query.ts:152-155](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/query.ts#L152-L155)
> [!WARNING]
> Selecting `findFirst` on any relational query builder forces the row transformation pipeline to truncate the hydrated array output, returning `undefined` if no records match the criteria.
> Sources: [drizzle-orm/src/pg-core/query-builders/query.ts:48-62](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query.ts#L48-L62), [drizzle-orm/src/sqlite-core/query-builders/query.ts:69-95](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/query.ts#L69-L95)
## Related
- [Table and Column Models](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/table-and-column-models)
- [Query Builder Foundation](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/query-builder-foundation)
---
## Technical docs: Query Builder Foundation
URL: https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/query-builder-foundation
Relevant source files
The following files were used as context for generating this wiki page:
- [drizzle-orm/src/gel-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/dialect.ts)
- [drizzle-orm/src/sqlite-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/dialect.ts)
- [drizzle-orm/src/gel-core/query-builders/select.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/select.ts)
- [drizzle-orm/src/mysql-core/query-builders/select.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/query-builders/select.ts)
- [drizzle-orm/src/sqlite-core/query-builders/select.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/select.ts)
- [drizzle-orm/src/singlestore-core/query-builders/select.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/query-builders/select.ts)
- [drizzle-orm/src/pg-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/dialect.ts)
- [drizzle-orm/src/mysql-core/query-builders/query.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/query-builders/query.ts)
- [drizzle-orm/src/gel-core/query-builders/query-builder.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/query-builder.ts)
- [drizzle-orm/src/pg-core/query-builders/select.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/select.ts)
- [drizzle-orm/src/mysql-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/dialect.ts)
- [drizzle-orm/src/gel-core/db.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/db.ts)
- [drizzle-orm/src/sql/sql.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql/sql.ts)
- [drizzle-orm/src/singlestore-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/dialect.ts)
- [drizzle-orm/src/pg-core/query-builders/query-builder.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query-builder.ts)
- [drizzle-orm/src/gel-core/query-builders/query.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/query.ts)
- [drizzle-orm/src/pg-core/query-builders/query.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query.ts)
- [drizzle-orm/src/sqlite-core/query-builders/query.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/query.ts)
- [drizzle-orm/src/gel-core/query-builders/insert.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/insert.ts)
- [drizzle-orm/src/sqlite-core/query-builders/query-builder.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/query-builder.ts)
- [drizzle-orm/type-tests/geldb/select.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/geldb/select.ts)
- [drizzle-orm/src/sqlite-core/db.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/db.ts)
- [drizzle-orm/src/singlestore-core/query-builders/query-builder.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/query-builders/query-builder.ts)
- [drizzle-orm/src/sqlite-core/query-builders/update.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/update.ts)
- [drizzle-orm/src/mysql-core/query-builders/query-builder.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/query-builders/query-builder.ts)
- [drizzle-orm/src/sqlite-core/query-builders/count.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/count.ts)
- [drizzle-orm/src/sqlite-core/query-builders/raw.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/raw.ts)
- [drizzle-orm/src/gel-core/query-builders/raw.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/raw.ts)
- [drizzle-orm/src/query-builders/query-builder.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/query-builders/query-builder.ts)
- [drizzle-orm/src/query-builders/select.types.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/query-builders/select.types.ts)
## Overview
The Query Builder Foundation defines the architectural and type-level framework for constructing, composing, and executing declarative SQL queries across all supported database dialects. It centers on foundational base classes such as `TypedQueryBuilder` and `QueryPromise` that standardize asynchronous execution, thenable resolutions, and fluent method chaining across select, insert, update, and count operations. By pairing abstract query specifications with concrete dialect implementations, the foundation enables type-safe schema selection, join nullability mapping, and expression compilation without relying on pre-instantiated database connections.
Sources: [drizzle-orm/src/query-builders/query-builder.ts:4-18](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/query-builders/query-builder.ts#L4-L18), [drizzle-orm/src/gel-core/query-builders/select.ts:1013-1060](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/select.ts#L1013-L1060), [drizzle-orm/src/sqlite-core/query-builders/select.ts:129-160](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/select.ts#L129-L160), [drizzle-orm/src/singlestore-core/query-builders/select.ts:133-160](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/query-builders/select.ts#L133-L160)
## Core Query Builder Abstractions
### Core Query Base Abstractions
### TypedQueryBuilder and Selection Contracts
The foundational contract for all query builders is established by the `TypedQueryBuilder` abstract class. It implements the `SQLWrapper` interface and exposes structural type generics for the selected fields, result shape, and builder configuration. The class defines an internal `_` property structure alongside helper methods for extracting selected fields and enforcing SQL compilation.
```typescript
export abstract class TypedQueryBuilder implements SQLWrapper {
static readonly [entityKind]: string = 'TypedQueryBuilder';
declare _: {
selectedFields: TSelection;
result: TResult;
config?: TConfig;
};
/** @internal */
getSelectedFields(): TSelection {
return this._.selectedFields;
}
abstract getSQL(): SQL;
}
```
Sources: [drizzle-orm/src/query-builders/query-builder.ts:4-18](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/query-builders/query-builder.ts#L4-L18)
Type-level calculations for queries rely on structural mapping utilities defined across select operations. These type definitions govern join semantics, result flattening, and subquery validation.
| Type Identifier | Parameters | Purpose |
| :--- | :--- | :--- |
| `JoinType` | none | Defines accepted join variations (`inner`, `left`, `right`, `full`, `cross`) |
| `JoinNullability` | none | Specifies row presence nullability (`nullable`, `not-null`) |
| `SelectMode` | none | Controls result shape categorization (`partial`, `single`, `multiple`) |
| `SetOperator` | none | Specifies set operation types (`union`, `intersect`, `except`) |
Sources: [drizzle-orm/src/query-builders/select.types.ts:9-11](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/query-builders/select.types.ts#L9-L11), [drizzle-orm/src/query-builders/select.types.ts:37-37](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/query-builders/select.types.ts#L37-L37), [drizzle-orm/src/query-builders/select.types.ts:175-175](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/query-builders/select.types.ts#L175-L175)
> [!NOTE]
> `TypedQueryBuilder` does not manage database connections or session execution directly. Concrete subclasses must implement `getSQL()` to translate internal configuration trees into parameterized `SQL` instances that drivers can execute.
## Standalone Query Builder Instantiation
### Dialect Query Builder Classes and Entity Kinds
Each database dialect provides a standalone `QueryBuilder` class that enables constructing queries without an active database session or connection pool. These classes hold an internal entity kind identifier and support lazy loading of their respective dialect instances to prevent circular dependencies during module initialization.
| Module Path | Entity Kind Identifier | Dialect Class | Config Type |
| :--- | :--- | :--- | :--- |
| `drizzle-orm/src/gel-core/query-builders/query-builder.ts` | `GelQueryBuilder` | `GelDialect` | `GelDialectConfig` |
| `drizzle-orm/src/pg-core/query-builders/query-builder.ts` | `PgQueryBuilder` | `PgDialect` | `PgDialectConfig` |
| `drizzle-orm/src/sqlite-core/query-builders/query-builder.ts` | `SQLiteQueryBuilder` | `SQLiteDialect`, `SQLiteSyncDialect` | `SQLiteDialectConfig` |
| `drizzle-orm/src/singlestore-core/query-builders/query-builder.ts` | `SingleStoreQueryBuilder` | `SingleStoreDialect` | `SingleStoreDialectConfig` |
| `drizzle-orm/src/mysql-core/query-builders/query-builder.ts` | `MySqlQueryBuilder` | `MySqlDialect` | `MySqlDialectConfig` |
Sources: [drizzle-orm/src/gel-core/query-builders/query-builder.ts:13-17](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/query-builder.ts#L13-L17), [drizzle-orm/src/pg-core/query-builders/query-builder.ts:13-17](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query-builder.ts#L13-L17), [drizzle-orm/src/sqlite-core/query-builders/query-builder.ts:12-16](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/query-builder.ts#L12-L16), [drizzle-orm/src/singlestore-core/query-builders/query-builder.ts:12-16](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/query-builders/query-builder.ts#L12-L16), [drizzle-orm/src/mysql-core/query-builders/query-builder.ts:12-16](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/query-builders/query-builder.ts#L12-L16)
> [!NOTE]
> The constructor accepts either an instantiated dialect instance or a dialect configuration object, resolving and storing them conditionally via the `is()` helper check.
Sources: [drizzle-orm/src/gel-core/query-builders/query-builder.ts:19-22](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/query-builder.ts#L19-L22), [drizzle-orm/src/pg-core/query-builders/query-builder.ts:19-22](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query-builder.ts#L19-L22)
### Proxy Initialization and Subquery Aliasing
The query builder provides `$with` and `with()` methods to construct Common Table Expressions (CTEs) and subqueries. When a subquery builder or callback is passed to `$with`, it wraps the resulting `WithSubquery` instance in a JavaScript `Proxy` managed by `SelectionProxyHandler`.
```typescript
return new Proxy(
new WithSubquery(
qb.getSQL(),
selection ?? ('getSelectedFields' in qb ? qb.getSelectedFields() ?? {} : {}) as SelectedFields,
alias,
true,
),
new SelectionProxyHandler({ alias, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }),
) as any;
```
Sources: [drizzle-orm/src/pg-core/query-builders/query-builder.ts:36-44](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query-builder.ts#L36-L44), [drizzle-orm/src/sqlite-core/query-builders/query-builder.ts:35-43](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/query-builder.ts#L35-L43), [drizzle-orm/src/singlestore-core/query-builders/query-builder.ts:35-43](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/query-builders/query-builder.ts#L35-L43), [drizzle-orm/src/mysql-core/query-builders/query-builder.ts:35-43](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/query-builders/query-builder.ts#L35-L43), [drizzle-orm/src/gel-core/query-builders/query-builder.ts:35-39](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/query-builder.ts#L35-L39)
> [!WARNING]
> `SelectionProxyHandler` configures `sqlAliasedBehavior` as `'alias'` and `sqlBehavior` as `'error'` for proxying field selections on subqueries, ensuring unaliased column references throw errors during compilation.
Sources: [drizzle-orm/src/gel-core/query-builders/query-builder.ts:36-39](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/query-builder.ts#L36-L39), [drizzle-orm/src/pg-core/query-builders/query-builder.ts:36-44](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query-builder.ts#L36-L44), [drizzle-orm/src/sqlite-core/query-builders/query-builder.ts:35-43](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/query-builder.ts#L35-L43), [drizzle-orm/src/singlestore-core/query-builders/query-builder.ts:35-43](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/query-builders/query-builder.ts#L35-L43), [drizzle-orm/src/mysql-core/query-builders/query-builder.ts:35-43](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/query-builders/query-builder.ts#L35-L43)
## Thenable Execution via QueryPromise
### Relational and Raw Query Execution Lifecycle
Relational query builders such as `MySqlRelationalQuery`, `GelRelationalQuery`, `PgRelationalQuery`, and `SQLiteRelationalQuery` extend `QueryPromise`, inheriting `then` and `catch` methods that enable them to be awaited directly as asynchronous promises. Each query class implements an `execute()` method that resolves its underlying session execution path. For PostgreSQL and Gel builders, execution wraps the query in an OpenTelemetry active span via `tracer.startActiveSpan('drizzle.operation', ...)` before triggering `_prepare().execute()`.
Sources: [drizzle-orm/src/mysql-core/query-builders/query.ts:76-79](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/query-builders/query.ts#L76-L79), [drizzle-orm/src/mysql-core/query-builders/query.ts:154-156](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/query-builders/query.ts#L154-L156), [drizzle-orm/src/gel-core/query-builders/query.ts:65-67](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/query.ts#L65-L67), [drizzle-orm/src/gel-core/query-builders/query.ts:145-149](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/query.ts#L145-L149), [drizzle-orm/src/pg-core/query-builders/query.ts:65-67](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query.ts#L65-L67), [drizzle-orm/src/pg-core/query-builders/query.ts:152-156](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query.ts#L152-L156), [drizzle-orm/src/sqlite-core/query-builders/query.ts:98-100](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/query.ts#L98-L100), [drizzle-orm/src/sqlite-core/query-builders/query.ts:196-198](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/query.ts#L196-L198)
> [!NOTE]
> `SQLiteSyncRelationalQuery` subclasses `SQLiteRelationalQuery` to provide a synchronous `.sync()` method alongside standard async promise resolution, dispatching directly to `.executeRaw()` using the driver's synchronous retrieval methods.
Sources: [drizzle-orm/src/sqlite-core/query-builders/query.ts:201-206](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/query.ts#L201-L206)
### Raw Execution and Statement Preparation
Raw query wrappers like `SQLiteRaw` and `GelRaw` extend `QueryPromise` while implementing `RunnableQuery`, `SQLWrapper`, and `PreparedQuery` simultaneously. They accept an explicit `execute` callback function during construction and supply internal query compilation methods such as `getSQL()`, `getQuery()`, and `mapResult()`.
```typescript
export class SQLiteRaw extends QueryPromise
implements RunnableQuery, SQLWrapper, PreparedQuery
{
static override readonly [entityKind]: string = 'SQLiteRaw';
declare readonly _: {
readonly dialect: 'sqlite';
readonly result: TResult;
};
/** @internal */
config: SQLiteRawConfig;
constructor(
public execute: () => Promise,
/** @internal */
public getSQL: () => SQL,
action: SQLiteRawAction,
private dialect: SQLiteAsyncDialect,
private mapBatchResult: (result: unknown) => unknown,
) {
super();
this.config = { action };
}
...
```
Sources: [drizzle-orm/src/sqlite-core/query-builders/raw.ts:15-38](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/raw.ts#L15-L38)
| Class Name | Dialect | Implemented Interfaces / Base | Execution Action Methods |
| :--- | :--- | :--- | :--- |
| `MySqlRelationalQuery` | MySQL | `QueryPromise` | `execute()`, `prepare()` |
| `GelRelationalQuery` | Gel | `QueryPromise`, `RunnableQuery`, `SQLWrapper` | `execute()`, `prepare()`, `_prepare()` |
| `PgRelationalQuery` | PostgreSQL | `QueryPromise`, `RunnableQuery`, `SQLWrapper` | `execute()`, `prepare()`, `_prepare()` |
| `SQLiteRelationalQuery` | SQLite | `QueryPromise`, `RunnableQuery`, `SQLWrapper` | `execute()`, `prepare()`, `executeRaw()` |
| `SQLiteSyncRelationalQuery` | SQLite | Extends `SQLiteRelationalQuery` | `sync()`, `executeRaw()` |
| `SQLiteRaw` | SQLite | `QueryPromise`, `RunnableQuery`, `SQLWrapper`, `PreparedQuery` | `execute()`, `mapResult()`, `getQuery()` |
| `GelRaw` | Gel | `QueryPromise`, `RunnableQuery`, `SQLWrapper`, `PreparedQuery` | `execute()`, `mapResult()`, `getQuery()` |
Sources: [drizzle-orm/src/mysql-core/query-builders/query.ts:76-79](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/query-builders/query.ts#L76-L79), [drizzle-orm/src/mysql-core/query-builders/query.ts:99-112](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/query-builders/query.ts#L99-L112), [drizzle-orm/src/gel-core/query-builders/query.ts:65-67](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/query.ts#L65-L67), [drizzle-orm/src/gel-core/query-builders/query.ts:112-114](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/query.ts#L112-L114), [drizzle-orm/src/pg-core/query-builders/query.ts:65-67](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query.ts#L65-L67), [drizzle-orm/src/pg-core/query-builders/query.ts:112-114](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query.ts#L112-L114), [drizzle-orm/src/sqlite-core/query-builders/query.ts:98-100](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/query.ts#L98-L100), [drizzle-orm/src/sqlite-core/query-builders/query.ts:164-166](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/query.ts#L164-L166), [drizzle-orm/src/sqlite-core/query-builders/query.ts:201-206](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/query.ts#L201-L206), [drizzle-orm/src/sqlite-core/query-builders/raw.ts:15-17](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/raw.ts#L15-L17), [drizzle-orm/src/sqlite-core/query-builders/raw.ts:40-47](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/raw.ts#L40-L47), [drizzle-orm/src/gel-core/query-builders/raw.ts:9-11](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/raw.ts#L9-L11), [drizzle-orm/src/gel-core/query-builders/raw.ts:33-39](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/raw.ts#L33-L39)
## Count Query Builder Foundation
### SQLWrapper and Promise Integration Mechanics
The `SQLiteCountBuilder` class extends `SQL` while implementing both `Promise` and `SQLWrapper`. This dual-contract design enables the builder to function simultaneously as a raw SQL chunk container and as an awaitable promise that resolves directly to a numeric count result via its underlying `SQLiteSession`.
```typescript
export class SQLiteCountBuilder<
TSession extends SQLiteSession,
> extends SQL implements Promise, SQLWrapper {
private sql: SQL;
static override readonly [entityKind] = 'SQLiteCountBuilderAsync';
[Symbol.toStringTag] = 'SQLiteCountBuilderAsync';
private session: TSession;
```
Sources: [drizzle-orm/src/sqlite-core/query-builders/count.ts:7-16](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/count.ts#L7-L16)
The constructor accepts a parameter object containing a table or view source, optional filter expressions, and a session instance. It initializes the superclass `SQL` instance with an embedded count representation using `buildEmbeddedCount`, while storing a separate standalone count statement generated by `buildCount` in a private `sql` property for session execution.
```typescript
constructor(
readonly params: {
source: SQLiteTable | SQLiteView | SQL | SQLWrapper;
filters?: SQL;
session: TSession;
},
) {
super(SQLiteCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
this.session = params.session;
this.sql = SQLiteCountBuilder.buildCount(
params.source,
params.filters,
);
}
```
Sources: [drizzle-orm/src/sqlite-core/query-builders/count.ts:31-46](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/count.ts#L31-L46)
> [!NOTE]
> `SQLiteCountBuilder` maintains two distinct SQL compilation methods: `buildEmbeddedCount` wraps the query inside parentheses for use as an expression, whereas `buildCount` constructs a standalone executable statement.
### Query Compilation Methods and Lifecycle Handlers
Query compilation relies on private static helper methods that dynamically inject a `where` clause only when filters are present, leveraging `sql.raw(' where ').if(filters)`.
```typescript
private static buildEmbeddedCount(
source: SQLiteTable | SQLiteView | SQL | SQLWrapper,
filters?: SQL,
): SQL {
return sql`(select count(*) from ${source}${sql.raw(' where ').if(filters)}${filters})`;
}
private static buildCount(
source: SQLiteTable | SQLiteView | SQL | SQLWrapper,
filters?: SQL,
): SQL {
return sql`select count(*) from ${source}${sql.raw(' where ').if(filters)}${filters}`;
}
```
Sources: [drizzle-orm/src/sqlite-core/query-builders/count.ts:17-30](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/count.ts#L17-L30)
Asynchronous promise resolution is implemented via standard `then`, `catch`, and `finally` methods. The `then` method delegates execution to `this.session.count(this.sql)`, resolving the returned promise with the numeric outcome of the query.
```typescript
then(
onfulfilled?: ((value: number) => TResult1 | PromiseLike) | null | undefined,
onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined,
): Promise {
return Promise.resolve(this.session.count(this.sql)).then(
onfulfilled,
onrejected,
);
}
catch(
onRejected?: ((reason: any) => never | PromiseLike) | null | undefined,
): Promise {
return this.then(undefined, onRejected);
}
finally(onFinally?: (() => void) | null | undefined): Promise {
return this.then(
(value) => {
onFinally?.();
return value;
},
(reason) => {
onFinally?.();
throw reason;
},
);
}
```
Sources: [drizzle-orm/src/sqlite-core/query-builders/count.ts:48-75](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/count.ts#L48-L75)
| Method Name | Parameters | Return Type | Purpose |
| :--- | :--- | :--- | :--- |
| `buildEmbeddedCount` | `source`, `filters` | `SQL` | Constructs a parenthesized subquery expression for SQL composition. |
| `buildCount` | `source`, `filters` | `SQL` | Constructs an executable standalone `select count(*)` query statement. |
| `then` | `onfulfilled`, `onrejected` | `Promise` | Executes session count lookup and hooks promise fulfillment. |
| `catch` | `onRejected` | `Promise` | Handles promise rejection flows. |
| `finally` | `onFinally` | `Promise` | Executes cleanup callbacks regardless of success or failure. |
Sources: [drizzle-orm/src/sqlite-core/query-builders/count.ts:17-30](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/count.ts#L17-L30), [drizzle-orm/src/sqlite-core/query-builders/count.ts:48-75](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/count.ts#L48-L75)
## Update Mutation Query Builders
### Mutation Query Builder Structure and Generic Contracts
The SQLite update infrastructure relies on `SQLiteUpdateBase` and the `SQLiteUpdate` interface to define typing boundaries, result configurations, and execution handles. The `SQLiteUpdate` interface extends `SQLWrapper` and `QueryPromise`, resolving to either `TRunResult` when no returning clause is specified, or `TReturning[]` when a returning clause is active.
```typescript
TResultType extends 'sync' | 'async' = 'sync' | 'async',
TRunResult = unknown,
TFrom extends SQLiteTable | Subquery | SQLiteViewBase | SQL | undefined = undefined,
TReturning = undefined,
TDynamic extends boolean = false,
TExcludedMethods extends string = never,
> extends SQLWrapper, QueryPromise {
readonly _: {
readonly dialect: 'sqlite';
readonly table: TTable;
readonly resultType: TResultType;
readonly runResult: TRunResult;
readonly from: TFrom;
readonly returning: TReturning;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
readonly result: TReturning extends undefined ? TRunResult : TReturning[];
};
}
```
Sources: [drizzle-orm/src/sqlite-core/query-builders/update.ts:205-223](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/update.ts#L205-L223)
The base implementation class `SQLiteUpdateBase` provides the underlying property structure and initializes the builder configuration via its constructor, storing the target table, update set mapping, session instance, dialect reference, and optional CTE with-list.
```typescript
export class SQLiteUpdateBase<
TTable extends SQLiteTable = SQLiteTable,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
TResultType extends 'sync' | 'async' = 'sync' | 'async',
TRunResult = unknown,
TFrom extends SQLiteTable | Subquery | SQLiteViewBase | SQL | undefined = undefined,
TReturning = undefined,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
TDynamic extends boolean = false,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
TExcludedMethods extends string = never,
> extends QueryPromise
implements RunnableQuery, SQLWrapper
{
static override readonly [entityKind]: string = 'SQLiteUpdate';
/** @internal */
config: SQLiteUpdateConfig;
constructor(
table: TTable,
set: UpdateSet,
private session: SQLiteSession,
private dialect: SQLiteDialect,
withList?: Subquery[],
) {
super();
this.config = { set, table, withList, joins: [] };
}
```
Sources: [drizzle-orm/src/sqlite-core/query-builders/update.ts:225-254](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/update.ts#L225-L254)
> [!NOTE]
> `SQLiteUpdateBase` enforces entity identification by overriding the static `[entityKind]` symbol with the string `'SQLiteUpdate'`.
### Update Set Mapping and Execution Lifecycle
Query construction proceeds by capturing mutation fields through the constructor's `set` parameter (`UpdateSet`) and configuring secondary clauses such as source tables via the `from` method, which returns an extended `SQLiteUpdateWithJoins` builder instance.
```typescript
from(
source: TFrom,
): SQLiteUpdateWithJoins {
this.config.from = source;
```
Sources: [drizzle-orm/src/sqlite-core/query-builders/update.ts:255-258](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/update.ts#L255-L258)
| Generic Parameter | Default Value | Purpose |
| :--- | :--- | :--- |
| `TTable` | `SQLiteTable` | Represents the target database table being updated. |
| `TResultType` | `'sync' \| 'async'` | Determines whether query resolution is synchronous or asynchronous. |
| `TRunResult` | `unknown` | Defines the raw execution result type when no returning clause is used. |
| `TFrom` | `undefined` | Models additional source tables, subqueries, views, or raw SQL fragments for joins. |
| `TReturning` | `undefined` | Specifies the shape of returned rows if a returning clause is supplied. |
| `TDynamic` | `false` | Indicates whether dynamic method chaining restrictions are relaxed. |
| `TExcludedMethods` | `never` | Tracks methods that have been disabled via prior builder chains. |
Sources: [drizzle-orm/src/sqlite-core/query-builders/update.ts:205-223](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/update.ts#L205-L223)
## Type-Level Query Composition and Typing
### Selection Validation and Nullability Mappings
Type-level composition handles join semantics, select modes, and nullability propagation through conditional mapped types. The `JoinType` union specifies supported join categories, while `JoinNullability` and `ApplyNullability` manage column and table row optionality based on join participation.
```typescript
export type JoinType = 'inner' | 'left' | 'right' | 'full' | 'cross';
export type JoinNullability = 'nullable' | 'not-null';
export type ApplyNullability = TNullability extends 'nullable' ? T | null
: TNullability extends 'null' ? null
: T;
```
Sources: [drizzle-orm/src/query-builders/select.types.ts:9-15](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/query-builders/select.types.ts#L9-L15)
| Join Type | Nullability Mapping Behavior |
| :--- | :--- |
| `inner` | Appends `'not-null'` to joined table selection. |
| `left` | Appends `'nullable'` to joined table selection. |
| `right` | Sets existing nullability map to `'nullable'` and assigns `'not-null'` to the joined table. |
| `full` | Sets all existing entries and the joined table to `'nullable'`. |
| `cross` | Appends `'not-null'` to joined table selection. |
Sources: [drizzle-orm/src/query-builders/select.types.ts:137-147](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/query-builders/select.types.ts#L137-L147)
> [!WARNING]
> Attempting to reference raw, unaliased `SQL` expressions inside subquery selections triggers a `DrizzleTypeError` requiring an explicit alias assignment via `.as()`.
Sources: [drizzle-orm/src/query-builders/select.types.ts:122-124](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/query-builders/select.types.ts#L122-L124)
### Result Inference and Dynamic Builders
Select execution results resolve dynamically across `'partial'`, `'single'`, and `'multiple'` modes using `SelectResult`. Type testing frameworks validate these inferences against expected output shapes, ensuring that chained methods like `where`, `having`, `groupBy`, `orderBy`, and `for` respect single-invocation constraints.
```typescript
export type SelectMode = 'partial' | 'single' | 'multiple';
export type SelectResult<
TResult,
TSelectMode extends SelectMode,
TNullabilityMap extends Record,
> = TSelectMode extends 'partial' ? SelectPartialResult
: TSelectMode extends 'single' ? SelectResultFields
: ApplyNotNullMapToJoins, TNullabilityMap>;
```
Sources: [drizzle-orm/src/query-builders/select.types.ts:37-45](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/query-builders/select.types.ts#L37-L45)
> [!NOTE]
> Dynamic query wrappers accept both `GelSelect` and `GelSelectQueryBuilder` instances when enabling runtime flexibility via `$dynamic()`.
Sources: [drizzle-orm/type-tests/geldb/select.ts:1004-1020](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/geldb/select.ts#L1004-L1020)
## Related
- [SQL Template Engine](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/sql-template-engine)
- [Sessions and Transactions](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/sessions-and-transactions)
---
## Technical docs: Sessions and Transactions
URL: https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/sessions-and-transactions
Relevant source files
The following files were used as context for generating this wiki page:
- [drizzle-orm/src/libsql/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/session.ts)
- [drizzle-orm/src/sqlite-proxy/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-proxy/session.ts)
- [drizzle-orm/src/singlestore/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore/session.ts)
- [drizzle-orm/src/bun-sql/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/bun-sql/session.ts)
- [drizzle-orm/src/netlify-db/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/netlify-db/session.ts)
- [drizzle-orm/src/planetscale-serverless/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/planetscale-serverless/session.ts)
- [drizzle-orm/src/neon-serverless/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-serverless/session.ts)
- [drizzle-orm/src/tidb-serverless/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tidb-serverless/session.ts)
- [drizzle-orm/src/mysql2/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql2/session.ts)
- [drizzle-orm/src/pglite/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pglite/session.ts)
- [drizzle-orm/src/postgres-js/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/postgres-js/session.ts)
- [drizzle-orm/src/node-postgres/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/node-postgres/session.ts)
- [drizzle-orm/src/singlestore-core/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/session.ts)
- [drizzle-orm/src/aws-data-api/pg/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/aws-data-api/pg/session.ts)
- [drizzle-orm/src/gel/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel/session.ts)
- [drizzle-orm/src/mysql-core/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/session.ts)
- [drizzle-orm/src/op-sqlite/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/op-sqlite/session.ts)
- [drizzle-orm/src/vercel-postgres/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/vercel-postgres/session.ts)
- [drizzle-orm/src/pg-proxy/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-proxy/session.ts)
- [drizzle-orm/src/d1/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/d1/session.ts)
- [drizzle-orm/src/neon-http/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-http/session.ts)
- [drizzle-orm/src/pg-core/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/session.ts)
- [drizzle-orm/src/bun-sqlite/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/bun-sqlite/session.ts)
- [drizzle-orm/src/pg-core/db.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/db.ts)
- [drizzle-orm/src/sqlite-core/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/session.ts)
- [drizzle-orm/src/better-sqlite3/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/better-sqlite3/session.ts)
- [drizzle-orm/src/sql-js/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql-js/session.ts)
- [drizzle-orm/src/sqlite-core/db.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/db.ts)
- [drizzle-orm/src/prisma/sqlite/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/prisma/sqlite/session.ts)
- [drizzle-orm/src/gel-core/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/session.ts)
## Overview
Sessions and transactions form the execution layer that bridges high-level query builders and low-level database drivers across diverse relational dialects and runtimes. By defining unified session abstractions like PostgreSQL Core, MySQL Core, and SQLite Core, the system standardizes statement preparation, execution pipelines, and result mapping regardless of whether queries run synchronously in Node.js or asynchronously across edge and serverless environments.
Sources: [drizzle-orm/src/pg-core/session.ts:168-234](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/session.ts#L168-L234), [drizzle-orm/src/mysql-core/session.ts:170-238](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/session.ts#L170-L238), [drizzle-orm/src/sqlite-core/session.ts:212-323](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/session.ts#L212-L323)
## Session Architecture and Prepared Queries
### Statement Execution Methods and Runtimes
The execution interface centers around dialect-specific session abstractions—such as `LibSQLSession`, `SQLiteRemoteSession`, `BunSQLSession`, `NeonSession`, `PgliteSession`, `GelDbSession`, `SQLJsSession`, and `PrismaSQLiteSession`—which inherit from shared base classes like `SQLiteSession` and `PgSession`. These sessions encapsulate database clients, configuration options, and telemetry loggers (`NoopLogger` or custom implementations), providing uniform methods for query compilation, statement preparation, and execution dispatch across diverse underlying runtimes.
Prepared statements are managed by specialized subclasses including `LibSQLPreparedQuery`, `RemotePreparedQuery`, `BunSQLPreparedQuery`, `NeonPreparedQuery`, `GelDbPreparedQuery`, `PreparedQuery` (for sql.js), and `PrismaSQLitePreparedQuery`. These query objects accept query fragments and parameters, resolve placeholder values via `fillPlaceholders`, record execution metrics through [logging and tracing](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/logging-and-tracing) hooks, and map raw driver outputs into structured domain entities.
```mermaid
graph TD
S["Session (`LibSQLSession`, `BunSQLSession`, etc.)"] -->|"prepareQuery()"| PQ["Prepared Query (`LibSQLPreparedQuery`, `BunSQLPreparedQuery`, etc.)"]
PQ -->|"fillPlaceholders()"| P["Parameterized Query"]
P -->|"logQuery()"| L["Logger / Tracer"]
P -->|"queryWithCache() / driver execute"| D["Driver Client"]
D -->|"Raw Rows"| M["mapResultRow() / customResultMapper"]
```
Sources: [drizzle-orm/src/libsql/session.ts:29-75](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/session.ts#L29-L75), [drizzle-orm/src/sqlite-proxy/session.ts:29-74](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-proxy/session.ts#L29-L74), [drizzle-orm/src/bun-sql/session.ts:19-103](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/bun-sql/session.ts#L19-L103), [drizzle-orm/src/neon-serverless/session.ts:188-233](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-serverless/session.ts#L188-L233), [drizzle-orm/src/pglite/session.ts:165-195](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pglite/session.ts#L165-L195), [drizzle-orm/src/gel/session.ts:17-102](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel/session.ts#L17-L102), [drizzle-orm/src/sql-js/session.ts:24-66](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql-js/session.ts#L24-L66), [drizzle-orm/src/prisma/sqlite/session.ts:62-83](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/prisma/sqlite/session.ts#L62-L83)
Prepared query contracts support a standard suite of execution methods—`run`, `all`, `get`, `values`, and `execute`—whose availability and return formats vary by driver implementation. For instance, synchronous sql.js prepared queries handle direct statement preparation, step iteration, result object extraction, and explicit resource freeing via `stmt.free()`, whereas asynchronous Bun SQL and Neon queries wrap execution within telemetry spans and cache layers.
| Session Class | Driver Client Type | Execution Mode | Supported Query Operations |
| :--- | :--- | :--- | :--- |
| `LibSQLSession` | `@libsql/client` `Client` | Async | `prepareQuery`, `batch`, `migrate`, `transaction` |
| `SQLiteRemoteSession` | `RemoteCallback` | Async | `prepareQuery`, `batch`, `transaction` |
| `BunSQLSession` | Bun `SQL` | Async | `prepareQuery`, `query`, `transaction`, `unsafe` |
| `NeonSession` | Neon `Pool` / `Client` | Async | `prepareQuery`, `query`, `queryObjects`, `count`, `transaction` |
| `PgliteSession` | `PgliteClient` | Async | `prepareQuery`, `transaction`, `count` |
| `GelDbSession` | Gel `Client` / `Transaction` | Async | `prepareQuery`, `transaction`, `count` |
| `SQLJsSession` | sql.js `Database` | Sync | `prepareQuery`, `transaction` |
| `PrismaSQLiteSession` | Prisma Client extension | Async | `prepareQuery`, `transaction` (unimplemented) |
Sources: [drizzle-orm/src/libsql/session.ts:29-129](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/session.ts#L29-L129), [drizzle-orm/src/sqlite-proxy/session.ts:29-105](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-proxy/session.ts#L29-L105), [drizzle-orm/src/bun-sql/session.ts:110-188](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/bun-sql/session.ts#L110-L188), [drizzle-orm/src/neon-serverless/session.ts:188-281](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-serverless/session.ts#L188-L281), [drizzle-orm/src/pglite/session.ts:165-195](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pglite/session.ts#L165-L195), [drizzle-orm/src/gel/session.ts:109-168](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel/session.ts#L109-L168), [drizzle-orm/src/sql-js/session.ts:24-66](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql-js/session.ts#L24-L66), [drizzle-orm/src/prisma/sqlite/session.ts:62-89](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/prisma/sqlite/session.ts#L62-L89)
> [!NOTE]
> In sql.js sessions, binary field values (`Uint8Array`) are automatically normalized via `normalizeFieldValue` into Node `Buffer` instances when available, or decoded using `TextDecoder` if `Buffer` is absent.
Sources: [drizzle-orm/src/sql-js/session.ts:197-210](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql-js/session.ts#L197-L210)
## Transaction Lifecycles and Rollback Semantics
### Demarcation and Scopes
Transaction boundaries are managed via driver-specific demarcation methods wrapped in session abstractions. In `BunSQLSession`, transactions use the native `client.begin()` method, supplying a transaction-scoped client to instantiate `BunSQLTransaction`. Similarly, `PgliteSession` delegates directly to the underlying `client.transaction()` API, while `AwsDataApiSession` explicitly dispatches `BeginTransactionCommand`, `CommitTransactionCommand`, and `RollbackTransactionCommand` via the AWS Data API client.
```typescript
override async transaction(
transaction: (tx: AwsDataApiTransaction) => Promise,
config?: PgTransactionConfig | undefined,
): Promise {
const { transactionId } = await this.client.send(new BeginTransactionCommand(this.rawQuery));
const session = new AwsDataApiSession(this.client, this.dialect, this.schema, this.options, transactionId);
const tx = new AwsDataApiTransaction(this.dialect, session, this.schema);
if (config) {
await tx.setTransaction(config);
}
try {
const result = await transaction(tx);
await this.client.send(new CommitTransactionCommand({ ...this.rawQuery, transactionId }));
return result;
} catch (e) {
await this.client.send(new RollbackTransactionCommand({ ...this.rawQuery, transactionId }));
throw e;
}
}
```
Sources: [drizzle-orm/src/bun-sql/session.ts:170-187](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/bun-sql/session.ts#L170-L187), [drizzle-orm/src/pglite/session.ts:170-187](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pglite/session.ts#L170-L187), [drizzle-orm/src/aws-data-api/pg/session.ts:238-256](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/aws-data-api/pg/session.ts#L238-L256)
Neon and SQL.js sessions handle transaction boundaries by executing explicit raw SQL statements (`begin`, `commit`, and `rollback`) wrapped in `try...catch` blocks. In `NeonSession`, pool connections check whether the client instance is a `Pool` to release the client back to the pool in a `finally` block.
```typescript
override async transaction(
transaction: (tx: NeonTransaction) => Promise,
config: PgTransactionConfig = {},
): Promise {
const session = this.client instanceof Pool // eslint-disable-line no-instanceof/no-instanceof
? new NeonSession(await this.client.connect(), this.dialect, this.schema, this.options)
: this;
const tx = new NeonTransaction(this.dialect, session, this.schema);
await tx.execute(sql`begin ${tx.getTransactionConfigSQL(config)}`);
try {
const result = await transaction(tx);
await tx.execute(sql`commit`);
return result;
} catch (error) {
await tx.execute(sql`rollback`);
throw error;
} finally {
if (this.client instanceof Pool) { // eslint-disable-line no-instanceof/no-instanceof
(session.client as PoolClient).release();
}
}
}
```
Sources: [drizzle-orm/src/neon-serverless/session.ts:260-281](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-serverless/session.ts#L260-L281), [drizzle-orm/src/sql-js/session.ts:51-65](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql-js/session.ts#L51-L65)
> [!NOTE]
> In `SQLJsSession`, transaction configuration behaviors (such as deferred, immediate, or exclusive) are appended dynamically to the `begin` statement using `config.behavior`.
Sources: [drizzle-orm/src/sql-js/session.ts:51-56](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql-js/session.ts#L51-L56)
### Nested Scopes and Savepoints
Nested transaction blocks within driver implementations rely on database savepoints rather than multi-tier native transactions. Each nested scope increments `nestedIndex` to generate unique savepoint identifiers matching the pattern `sp1`, `sp2`, and so forth.
| Transaction Class | Nested Implementation Mechanism | Savepoint Naming Pattern | Rollback on Error |
| :--- | :--- | :--- | :--- |
| `BunSQLTransaction` | `client.savepoint()` | Managed by Bun SQL | Automatic via driver block |
| `NeonTransaction` | `savepoint` / `rollback to savepoint` | `sp${this.nestedIndex + 1}` | Explicit SQL command |
| `TiDBServerlessTransaction` | `savepoint` / `rollback to savepoint` | `sp${this.nestedIndex + 1}` | Explicit SQL command |
| `PgliteTransaction` | `savepoint` / `rollback to savepoint` | `sp${this.nestedIndex + 1}` | Explicit SQL command |
| `AwsDataApiTransaction` | `savepoint` / `rollback to savepoint` | `sp${this.nestedIndex + 1}` | Explicit SQL command |
| `SQLJsTransaction` | `savepoint` / `rollback to savepoint` | `sp${this.nestedIndex + 1}` | Explicit SQL command |
Sources: [drizzle-orm/src/bun-sql/session.ts:206-219](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/bun-sql/session.ts#L206-L219), [drizzle-orm/src/neon-serverless/session.ts:290-302](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-serverless/session.ts#L290-L302), [drizzle-orm/src/tidb-serverless/session.ts:209-228](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tidb-serverless/session.ts#L209-L228), [drizzle-orm/src/pglite/session.ts:203-220](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pglite/session.ts#L203-L220), [drizzle-orm/src/aws-data-api/pg/session.ts:265-284](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/aws-data-api/pg/session.ts#L265-L284), [drizzle-orm/src/sql-js/session.ts:74-86](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql-js/session.ts#L74-L86)
> [!CAUTION]
> When an error occurs inside a nested transaction block utilizing savepoints, the execution path triggers `rollback to savepoint spN` and releases or throws the error, preserving the outer transaction state.
Sources: [drizzle-orm/src/neon-serverless/session.ts:298-301](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-serverless/session.ts#L298-L301), [drizzle-orm/src/sql-js/session.ts:82-85](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql-js/session.ts#L82-L85)
## Driver Connection Wrappers and Execution
### Connection Bridging and Client Execution
Drizzle abstracts disparate underlying driver connection interfaces into uniform session and prepared query instances across runtimes. In environments powered by Bun SQL (`BunSQLSession`) and Pglite (`PgliteSession`), queries are dispatched using driver-native `.unsafe()` and `.transaction()` wrappers while capturing telemetry through OpenTelemetry spans.
```typescript
async execute(placeholderValues: Record | undefined = {}): Promise {
return tracer.startActiveSpan('drizzle.execute', async (span) => {
const params = fillPlaceholders(this.params, placeholderValues);
span?.setAttributes({
'drizzle.query.text': this.queryString,
'drizzle.query.params': JSON.stringify(params),
});
this.logger.logQuery(this.queryString, params);
const { fields, queryString: query, client, joinsNotNullableMap, customResultMapper } = this;
if (!fields && !customResultMapper) {
return tracer.startActiveSpan('drizzle.driver.execute', async () => {
return await this.queryWithCache(query, params, async () => {
return await client.unsafe(query, params as any[]);
});
});
}
```
Sources: [drizzle-orm/src/bun-sql/session.ts:40-58](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/bun-sql/session.ts#L40-L58), [drizzle-orm/src/pglite/session.ts:165-187](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pglite/session.ts#L165-L187)
> [!NOTE]
> Client adapters like `PrismaSQLitePreparedQuery` bridge SQLite execution by mapping calls directly to Prisma's `$queryRawUnsafe` API, while throwing unsupported errors for raw value arrays and transaction blocks.
Sources: [drizzle-orm/src/prisma/sqlite/session.ts:33-56](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/prisma/sqlite/session.ts#L33-L56), [drizzle-orm/src/prisma/sqlite/session.ts:84-90](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/prisma/sqlite/session.ts#L84-L90)
### Synchronous and Asynchronous SQLite Execution Pipelines
SQLite runtimes split execution semantics between synchronous in-memory drivers like `sql.js` and asynchronous mobile/edge drivers like `OP-SQLite`. `SQLJsSession` utilizes explicit statement preparation, parameter binding via `BindParams`, stepping via `stmt.step()`, and manual resource freeing via `stmt.free()`.
```typescript
run(placeholderValues?: Record): void {
const stmt = this.client.prepare(this.query.sql);
const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
this.logger.logQuery(this.query.sql, params);
const result = stmt.run(params as BindParams);
stmt.free();
return result;
}
```
Sources: [drizzle-orm/src/sql-js/session.ts:106-116](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql-js/session.ts#L106-L116), [drizzle-orm/src/sql-js/session.ts:118-143](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql-js/session.ts#L118-L143)
In contrast, `OPSQLiteSession` routes execution methods through asynchronous connection bindings:
| Execution Method | OP-SQLite Driver Call | Return Type |
| :--- | :--- | :--- |
| `run` | `client.executeAsync(query, params)` | `QueryResult` |
| `all` | `client.execute(query, params).rows?._array` | `T['all']` |
| `values` | `client.executeRawAsync(query, params)` | `T['values']` |
Sources: [drizzle-orm/src/op-sqlite/session.ts:135-142](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/op-sqlite/session.ts#L135-L142), [drizzle-orm/src/op-sqlite/session.ts:144-160](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/op-sqlite/session.ts#L144-L160), [drizzle-orm/src/op-sqlite/session.ts:187-193](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/op-sqlite/session.ts#L187-L193)
> [!WARNING]
> When decoding binary results in `SQLJsSession`, `normalizeFieldValue` checks `Uint8Array` instances and converts them using `Buffer.from()` if available, or `TextDecoder` otherwise, throwing an error if neither polyfill exists.
Sources: [drizzle-orm/src/sql-js/session.ts:197-210](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql-js/session.ts#L197-L210)
## HTTP and Serverless Transaction Emulation
### Stateless HTTP Gateways and WebSocket Upgrades
Stateless HTTP gateways and serverless environments present distinct coordination challenges for transaction semantics because HTTP protocols do not inherently maintain persistent connection state between requests. Drivers such as Neon HTTP (`NeonHttpSession`) execute queries over stateless HTTPS connections using `@neondatabase/serverless`, which inherently prevents multi-statement transaction execution blocks since each query can hit a different serverless container or worker instance. Consequently, calling `transaction()` on `NeonHttpSession` throws an error explicitly stating that transactions are unsupported in the `neon-http` driver.
```typescript
override async transaction(
_transaction: (tx: NeonTransaction) => Promise,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_config: PgTransactionConfig = {},
): Promise {
throw new Error('No transactions support in neon-http driver');
}
```
Sources: [drizzle-orm/src/neon-http/session.ts:248-254](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-http/session.ts#L248-L254)
In contrast, hybrid adapters like Netlify DB (`NetlifyDbSession`) manage this limitation by bridging HTTP and WebSocket protocols. When a transaction is initiated, `NetlifyDbSession` acquires a dedicated `PoolClient` instance from an underlying connection pool, establishes a persistent WebSocket connection, executes `begin` alongside transaction configuration parameters, and executes the transactional callback inside `NetlifyDbTransaction`.
```typescript
await tx.execute(sql`begin ${tx.getTransactionConfigSQL(config)}`);
try {
const result = await transaction(tx);
await tx.execute(sql`commit`);
return result;
} catch (error) {
await tx.execute(sql`rollback`);
throw error;
} finally {
poolClient.release();
}
}
```
Sources: [drizzle-orm/src/netlify-db/session.ts:168-179](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/netlify-db/session.ts#L168-L179)
> [!WARNING]
> Netlify DB WebSocket sessions (`NetlifyDbWsSession`) explicitly throw an error if nested `transaction()` calls are invoked directly on the session instance, enforcing that inner scopes route through `NetlifyDbTransaction` savepoint handling instead.
Sources: [drizzle-orm/src/netlify-db/session.ts:259-265](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/netlify-db/session.ts#L259-L265)
### Client-Side Transaction Coordination
AWS Data API and remote proxy runtimes coordinate transactions by passing explicit transaction identifiers across stateless API requests. `AwsDataApiSession` manages transaction blocks by sending a `BeginTransactionCommand` to the AWS Data API client, receiving a unique `transactionId` string, and injecting that identifier into every subsequent prepared query statement executed within that scope.
```typescript
override async transaction(
transaction: (tx: AwsDataApiTransaction) => Promise,
config?: PgTransactionConfig | undefined,
): Promise {
const { transactionId } = await this.client.send(new BeginTransactionCommand(this.rawQuery));
const session = new AwsDataApiSession(this.client, this.dialect, this.schema, this.options, transactionId);
const tx = new AwsDataApiTransaction(this.dialect, session, this.schema);
if (config) {
await tx.setTransaction(config);
}
try {
const result = await transaction(tx);
await this.client.send(new CommitTransactionCommand({ ...this.rawQuery, transactionId }));
return result;
} catch (e) {
await this.client.send(new RollbackTransactionCommand({ ...this.rawQuery, transactionId }));
throw e;
}
}
```
Sources: [drizzle-orm/src/aws-data-api/pg/session.ts:238-256](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/aws-data-api/pg/session.ts#L238-L256)
Remote proxy drivers (`PgRemoteSession`) bypass transaction handling entirely because the underlying remote callback transport lacks stateful transaction coordination, throwing an error on invocation.
| Driver Session Class | Transaction Support Strategy | Behavior on `transaction()` |
| :--- | :--- | :--- |
| `NeonHttpSession` | None (Stateless HTTP) | Throws `'No transactions support in neon-http driver'` |
| `NetlifyDbSession` | WebSocket Pool Client | Acquires `PoolClient`, runs `begin`/`commit`/`rollback`, releases client |
| `AwsDataApiSession` | API Transaction ID | Sends `BeginTransactionCommand`, tracks `transactionId`, sends `CommitTransactionCommand` or `RollbackTransactionCommand` |
| `PgRemoteSession` | Remote Proxy Callback | Throws `'Transactions are not supported by the Postgres Proxy driver'` |
Sources: [drizzle-orm/src/neon-http/session.ts:248-254](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-http/session.ts#L248-L254), [drizzle-orm/src/netlify-db/session.ts:168-179](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/netlify-db/session.ts#L168-L179), [drizzle-orm/src/aws-data-api/pg/session.ts:238-256](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/aws-data-api/pg/session.ts#L238-L256), [drizzle-orm/src/pg-proxy/session.ts:70-75](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-proxy/session.ts#L70-L75)
> [!NOTE]
> Netlify DB explicitly verifies that a WebSocket constructor is available globally before initializing serverless query execution, assigning `WebSocket` to `neonConfig.webSocketConstructor` if unassigned.
Sources: [drizzle-orm/src/netlify-db/session.ts:39-45](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/netlify-db/session.ts#L39-L45)
## Batch Pipelines and Proxy Sessions
### Batch Item Aggregation
Batch execution models in Drizzle aggregate arrays of query items into single pipeline requests dispatched to remote drivers or database clients. In `LibSQLSession`, the `batch()` method iterates over incoming `queries`, invokes `_prepare()` on each item to generate a prepared query, extracts the underlying SQL string and parameter arguments via `getQuery()`, and pushes them into an `InStatement` array.
```typescript
async batch[] | readonly BatchItem<'sqlite'>[]>(queries: T) {
const preparedQueries: PreparedQuery[] = [];
const builtQueries: InStatement[] = [];
for (const query of queries) {
const preparedQuery = query._prepare();
const builtQuery = preparedQuery.getQuery();
preparedQueries.push(preparedQuery);
builtQueries.push({ sql: builtQuery.sql, args: builtQuery.params as InArgs });
}
```
Sources: [drizzle-orm/src/libsql/session.ts:77-86](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/session.ts#L77-L86)
Once the built statements are assembled, `LibSQLSession` invokes `this.client.batch(builtQueries)` and maps the resulting array of driver outputs back through each individual prepared query's `mapResult()` handler with array mode enabled.
```typescript
const batchResults = await this.client.batch(builtQueries);
return batchResults.map((result, i) => preparedQueries[i]!.mapResult(result, true));
}
```
Sources: [drizzle-orm/src/libsql/session.ts:88-90](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/session.ts#L88-L90)
Similarly, `LibSQLSession` provides a `migrate()` method that mirrors the exact structure of `batch()` but delegates to `this.client.migrate(builtQueries)` for migration-specific pipeline execution.
```typescript
async migrate[] | readonly BatchItem<'sqlite'>[]>(queries: T) {
const preparedQueries: PreparedQuery[] = [];
const builtQueries: InStatement[] = [];
for (const query of queries) {
const preparedQuery = query._prepare();
const builtQuery = preparedQuery.getQuery();
preparedQueries.push(preparedQuery);
builtQueries.push({ sql: builtQuery.sql, args: builtQuery.params as InArgs });
}
const batchResults = await this.client.migrate(builtQueries);
return batchResults.map((result, i) => preparedQueries[i]!.mapResult(result, true));
}
```
Sources: [drizzle-orm/src/libsql/session.ts:92-105](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/session.ts#L92-L105)
### Remote Proxy Transports
Proxy and HTTP-backed drivers implement batch pipelines by marshalling query descriptors across remote transport boundaries. In `NeonHttpSession`, the `batch()` method processes incoming queries by creating `NeonQueryPromise` instances with `fullResults: true` and array mode determined by each prepared query's `isResponseInArrayMode()` configuration.
```typescript
async batch, T extends Readonly<[U, ...U[]]>>(
queries: T,
) {
const preparedQueries: PreparedQuery[] = [];
const builtQueries: NeonQueryPromise[] = [];
for (const query of queries) {
const preparedQuery = query._prepare();
const builtQuery = preparedQuery.getQuery();
preparedQueries.push(preparedQuery);
builtQueries.push(
this.clientQuery(builtQuery.sql, builtQuery.params, {
fullResults: true,
arrayMode: preparedQuery.isResponseInArrayMode(),
}),
);
}
```
Sources: [drizzle-orm/src/neon-http/session.ts:199-214](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-http/session.ts#L199-L214)
The collected promises are then dispatched to Neon's HTTP client transaction endpoint using `this.client.transaction(builtQueries, queryConfig)` before mapping the batch results back to their respective prepared queries.
```typescript
const batchResults = await this.client.transaction(builtQueries, queryConfig);
return batchResults.map((result, i) => preparedQueries[i]!.mapResult(result, true)) as any;
```
Sources: [drizzle-orm/src/neon-http/session.ts:216-218](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-http/session.ts#L216-L218)
For SQLite proxy sessions (`SQLiteRemoteSession`), batch aggregation maps query parameters alongside explicit execution methods (`run`, `all`, `values`, or `get`) into remote transport payloads before invoking `this.batchCLient`.
```typescript
async batch[] | readonly BatchItem<'sqlite'>[]>(queries: T) {
const preparedQueries: PreparedQuery[] = [];
const builtQueries: { sql: string; params: any[]; method: 'run' | 'all' | 'values' | 'get' }[] = [];
for (const query of queries) {
const preparedQuery = query._prepare();
const builtQuery = (preparedQuery as RemotePreparedQuery).getQuery();
preparedQueries.push(preparedQuery);
builtQueries.push({ sql: builtQuery.sql, params: builtQuery.params, method: builtQuery.method });
}
const batchResults = await (this.batchCLient as AsyncBatchRemoteCallback)(builtQueries);
return batchResults.map((result, i) => preparedQueries[i]!.mapResult(result, true));
}
```
Sources: [drizzle-orm/src/sqlite-proxy/session.ts:76-89](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-proxy/session.ts#L76-L89)
> [!NOTE]
> `SQLiteRemoteSession` extracts raw batch result rows using session-specific helpers like `extractRawAllValueFromBatchResult`, `extractRawGetValueFromBatchResult`, and `extractRawValuesValueFromBatchResult` tailored to `SqliteRemoteResult` structures.
Sources: [drizzle-orm/src/sqlite-proxy/session.ts:107-117](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-proxy/session.ts#L107-L117)
## Related
- [Query Builder Foundation](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/query-builder-foundation)
- [Drivers And Runtimes](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/drivers-and-runtimes/drivers-and-runtimes)
---
## Technical docs: Query Caching
URL: https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/query-caching
Relevant source files
The following files were used as context for generating this wiki page:
- [drizzle-orm/src/cache/upstash/cache.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/cache/upstash/cache.ts)
- [drizzle-orm/src/cache/upstash/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/cache/upstash/index.ts)
- [drizzle-orm/src/singlestore-core/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/session.ts)
- [drizzle-orm/src/singlestore/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore/session.ts)
- [drizzle-orm/src/mysql-core/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/session.ts)
- [drizzle-orm/src/planetscale-serverless/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/planetscale-serverless/session.ts)
- [drizzle-orm/src/sqlite-core/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/session.ts)
- [drizzle-orm/src/sqlite-proxy/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-proxy/session.ts)
- [drizzle-orm/src/tidb-serverless/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tidb-serverless/session.ts)
- [drizzle-orm/src/gel-core/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/session.ts)
- [drizzle-orm/src/neon-serverless/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-serverless/session.ts)
- [drizzle-orm/src/mysql2/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql2/session.ts)
- [drizzle-orm/src/cache/core/cache.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/cache/core/cache.ts)
- [drizzle-orm/src/libsql/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/session.ts)
- [drizzle-orm/src/node-postgres/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/node-postgres/session.ts)
- [drizzle-orm/src/vercel-postgres/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/vercel-postgres/session.ts)
- [drizzle-orm/src/bun-sql/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/bun-sql/session.ts)
- [drizzle-orm/src/pg-proxy/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-proxy/session.ts)
- [drizzle-orm/src/xata-http/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/xata-http/session.ts)
- [drizzle-orm/src/pg-core/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/session.ts)
- [drizzle-orm/src/gel/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel/session.ts)
- [drizzle-orm/src/pglite/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pglite/session.ts)
- [drizzle-orm/src/mysql-proxy/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-proxy/session.ts)
- [drizzle-orm/src/op-sqlite/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/op-sqlite/session.ts)
- [drizzle-orm/src/neon-http/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-http/session.ts)
- [drizzle-orm/src/singlestore-core/db.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/db.ts)
- [drizzle-orm/src/cache/core/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/cache/core/index.ts)
- [drizzle-orm/src/aws-data-api/pg/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/aws-data-api/pg/session.ts)
- [drizzle-orm/src/cache/core/types.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/cache/core/types.ts)
- [drizzle-orm/src/durable-sqlite/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/durable-sqlite/session.ts)
## Overview
Query caching in Drizzle provides an extensible caching infrastructure designed to intercept database execution, minimize redundant round-trips, and maintain synchronization between cached query results and underlying table mutations. By integrating caching abstractions directly into database sessions and prepared statements across supported SQL dialects, queries can be conditionally cached, retrieved via read-through patterns, and automatically invalidated when related tables undergo changes.
Sources: [drizzle-orm/src/cache/core/cache.ts:5-42](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/cache/core/cache.ts#L5-L42), [drizzle-orm/src/singlestore-core/session.ts:68-152](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/session.ts#L68-L152), [drizzle-orm/src/mysql-core/session.ts:70-154](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/session.ts#L70-L154), [drizzle-orm/src/sqlite-core/session.ts:71-155](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/session.ts#L71-L155), [drizzle-orm/src/pg-core/session.ts:64-147](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/session.ts#L64-L147)
## Core Cache Abstractions and Contract
### Base Cache Class and Null Implementation
```typescript
export abstract class Cache {
static readonly [entityKind]: string = 'Cache';
abstract strategy(): 'explicit' | 'all';
/**
* Invoked if we should check cache for cached response
* @param sql
* @param tables
*/
abstract get(
key: string,
tables: string[],
isTag: boolean,
isAutoInvalidate?: boolean,
): Promise;
/**
* Invoked if new query should be inserted to cache
* @param sql
* @param tables
*/
abstract put(
hashedQuery: string,
response: any,
tables: string[],
isTag: boolean,
config?: CacheConfig,
): Promise;
/**
* Invoked if insert, update, delete was invoked
* @param tables
*/
abstract onMutate(
params: MutationOption,
): Promise;
}
export class NoopCache extends Cache {
override strategy() {
return 'all' as const;
}
static override readonly [entityKind]: string = 'NoopCache';
override async get(_key: string): Promise {
return undefined;
}
override async put(
_hashedQuery: string,
_response: any,
_tables: string[],
_config?: any,
): Promise {
// noop
}
override async onMutate(_params: MutationOption): Promise {
// noop
}
}
```
Sources: [drizzle-orm/src/cache/core/cache.ts:5-65](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/cache/core/cache.ts#L5-L65)
> [!NOTE]
> `NoopCache` inherits from the abstract `Cache` base class and resolves cache strategies as `'all'` while returning `undefined` for `get` operations, effectively bypassing caching when no active provider is configured.
### Mutation Options and Query Hashing
```typescript
export type MutationOption = { tags?: string | string[]; tables?: Table | Table[] | string | string[] };
export async function hashQuery(sql: string, params?: any[]) {
const dataToHash = `${sql}-${JSON.stringify(params)}`;
const encoder = new TextEncoder();
const data = encoder.encode(dataToHash);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hashArray = [...new Uint8Array(hashBuffer)];
const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}
```
Sources: [drizzle-orm/src/cache/core/cache.ts:67-78](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/cache/core/cache.ts#L67-L78)
> [!IMPORTANT]
> `hashQuery` serializes the SQL string and parameter array using `JSON.stringify`, encodes the combined payload via `TextEncoder`, and computes a SHA-256 digest using `crypto.subtle.digest`, converting the resulting buffer into a hexadecimal string representation.
### Configuration Interfaces
```typescript
export type CacheConfig = {
/**
* expire time, in seconds (a positive integer)
*/
ex?: number;
/**
* expire time, in milliseconds (a positive integer).
*/
px?: number;
/**
* Unix time at which the key will expire, in seconds (a positive integer).
*/
exat?: number;
/**
* Unix time at which the key will expire, in milliseconds (a positive integer)
*/
pxat?: number;
/**
* Retain the time to live associated with the key.
*/
keepTtl?: boolean;
/**
* Set an expiration (TTL or time to live) on one or more fields of a given hash key.
* Used for HEXPIRE command
*/
hexOptions?: 'NX' | 'nx' | 'XX' | 'xx' | 'GT' | 'gt' | 'LT' | 'lt';
};
export type WithCacheConfig = { enable: boolean; config?: CacheConfig; tag?: string; autoInvalidate?: boolean };
```
Sources: [drizzle-orm/src/cache/core/types.ts:1-29](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/cache/core/types.ts#L1-L29)
| Configuration Property | Type | Description |
| :--- | :--- | :--- |
| `ex` | `number` | Expire time in seconds (positive integer) |
| `px` | `number` | Expire time in milliseconds (positive integer) |
| `exat` | `number` | Unix time at which the key will expire, in seconds |
| `pxat` | `number` | Unix time at which the key will expire, in milliseconds |
| `keepTtl` | `boolean` | Retain the time to live associated with the key |
| `hexOptions` | `'NX' \| 'nx' \| 'XX' \| 'xx' \| 'GT' \| 'gt' \| 'LT' \| 'lt'` | Expiration options used for HEXPIRE commands |
| `enable` | `boolean` | Enables or disables query caching |
| `config` | `CacheConfig` | Underlying expiration and TTL configuration |
| `tag` | `string` | Custom cache tag for group invalidation |
| `autoInvalidate` | `boolean` | Automatically invalidate entries upon table mutation |
Sources: [drizzle-orm/src/cache/core/types.ts:1-29](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/cache/core/types.ts#L1-L29)
## Upstash Redis Storage Implementation
### UpstashCache Storage Architecture and Key Prefixes
The `UpstashCache` class extends the core `Cache` abstraction, utilizing the `@upstash/redis client package to implement distributed query caching with Lua scripting support. It relies on fixed naming prefixes and global key structures to manage cache entries, non-auto-invalidated queries, and relational table mappings.
| Constant Name | Value / Prefix | Description |
| :--- | :--- | :--- |
| `compositeTableSetPrefix` | `'__CTS__'` | Prefix for sets denoting composite table names for unique tables |
| `compositeTablePrefix` | `'__CT__'` | Prefix for Redis hashes mapping hash keys or tags to cache values |
| `tagsMapKey` | `'__tagsMap__'` | Redis key holding the mapping of tags to composite table names |
| `nonAutoInvalidateTablePrefix` | `'__nonAutoInvalidate__'` | Hash prefix storing queries whose auto-invalidation is disabled |
Sources: [drizzle-orm/src/cache/upstash/cache.ts:60-95](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/cache/upstash/cache.ts#L60-L95)
> [!NOTE]
> Queries configured with auto-invalidation disabled bypass composite table hashes entirely, preventing them from being swept away during table mutation triggers and instead residing inside the `__nonAutoInvalidate__` Redis hash.
Sources: [drizzle-orm/src/cache/upstash/cache.ts:87-94](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/cache/upstash/cache.ts#L87-L94)
### Lua Scripting for Retrieval and Mutation
```typescript
const getByTagScript = `
local tagsMapKey = KEYS[1] -- tags map key
local tag = ARGV[1] -- tag
local compositeTableName = redis.call('HGET', tagsMapKey, tag)
if not compositeTableName then
return nil
end
local value = redis.call('HGET', compositeTableName, tag)
return value
`;
const onMutateScript = `
local tagsMapKey = KEYS[1] -- tags map key
local tables = {} -- initialize tables array
local tags = ARGV -- tags array
for i = 2, #KEYS do
tables[#tables + 1] = KEYS[i] -- add all keys except the first one to tables
end
if #tags > 0 then
for _, tag in ipairs(tags) do
if tag ~= nil and tag ~= '' then
local compositeTableName = redis.call('HGET', tagsMapKey, tag)
if compositeTableName then
redis.call('HDEL', compositeTableName, tag)
end
end
end
redis.call('HDEL', tagsMapKey, unpack(tags))
end
local keysToDelete = {}
if #tables > 0 then
local compositeTableNames = redis.call('SUNION', unpack(tables))
for _, compositeTableName in ipairs(compositeTableNames) do
keysToDelete[#keysToDelete + 1] = compositeTableName
end
for _, table in ipairs(tables) do
keysToDelete[#keysToDelete + 1] = table
end
redis.call('DEL', unpack(keysToDelete))
end
`;
```
Sources: [drizzle-orm/src/cache/upstash/cache.ts:8-54](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/cache/upstash/cache.ts#L8-L54)
> [!IMPORTANT]
> `UpstashCache` registers two compiled Lua scripts during initialization: `getByTagScript` (marked readonly) which looks up tag mappings and fetches cached values in a single atomic round-trip, and `onMutateScript` which executes set unions (`SUNION`), table deletions (`DEL`), and hash field removals (`HDEL`) when database modifications occur.
Sources: [drizzle-orm/src/cache/upstash/cache.ts:8-54](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/cache/upstash/cache.ts#L8-L54), [drizzle-orm/src/cache/upstash/cache.ts:106-109](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/cache/upstash/cache.ts#L106-L109)
## Session Cache Lifecycle Coordination
### Execution Interception and Caching Mechanisms
Database sessions across SQLite, PostgreSQL, and MySQL proxy implementations coordinate caching through prepared query abstractions. When a query is executed via `SQLiteRemoteSession`, `PgRemoteSession`, or `MySqlRemoteSession`, parameters are filled, queries are logged via `Logger`, and execution flows through read-through wrapper methods like `queryWithCache`.
| Session Class | Driver Type | Cache Option Property | Default Cache Implementation |
| :--- | :--- | :--- | :--- |
| `SQLiteRemoteSession` | SQLite Proxy | `cache` | `NoopCache` |
| `PgRemoteSession` | PostgreSQL Proxy | `cache` | `NoopCache` |
| `MySqlRemoteSession` | MySQL Proxy | `cache` | `NoopCache` |
Sources: [drizzle-orm/src/sqlite-proxy/session.ts:22-41](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-proxy/session.ts#L22-L41), [drizzle-orm/src/pg-proxy/session.ts:18-41](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-proxy/session.ts#L18-L41), [drizzle-orm/src/mysql-proxy/session.ts:27-50](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-proxy/session.ts#L27-L50)
> [!NOTE]
> Sessions initialize their internal logger and cache instances during construction, falling back to `NoopLogger` and `NoopCache` when options are omitted from the session configuration object.
Sources: [drizzle-orm/src/sqlite-proxy/session.ts:38-41](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-proxy/session.ts#L38-L41), [drizzle-orm/src/pg-proxy/session.ts:32-41](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-proxy/session.ts#L32-L41), [drizzle-orm/src/mysql-proxy/session.ts:41-50](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-proxy/session.ts#L41-L50)
### Prepared Query Coordination
Prepared query classes wrap execution commands (`run`, `all`, `get`, `values`, `execute`) and interact directly with session-level caching hooks by passing query strings, parameters, and execution callbacks.
```typescript
async run(placeholderValues?: Record): Promise {
const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
this.logger.logQuery(this.query.sql, params);
return await this.queryWithCache(this.query.sql, params, async () => {
return await (this.client as AsyncRemoteCallback)(this.query.sql, params, 'run');
});
}
```
Sources: [drizzle-orm/src/sqlite-proxy/session.ts:177-183](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-proxy/session.ts#L177-L183)
> [!WARNING]
> In `PgRemoteSession`, query execution wrapped with OpenTelemetry spans (`drizzle.execute` and `drizzle.driver.execute`) records query text and parameter payloads as span attributes before delegating to `queryWithCache`.
Sources: [drizzle-orm/src/pg-proxy/session.ts:113-154](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-proxy/session.ts#L113-L154)
## Cache Invalidation and Mutation Handling
### Mutation Options and Invalidation Triggers
The core cache abstract contract defines the `onMutate` lifecycle hook to handle database modification operations such as inserts, updates, and deletes [[Cache Invalidation and Mutation Handling](#)], accepting a `MutationOption` parameter [[Cache Invalidation and Mutation Handling](#)]. This parameter structure supports optional tags and tables specified as single items or arrays of strings, table objects, or table instances [[Cache Invalidation and Mutation Handling](#)].
```typescript
export type MutationOption = { tags?: string | string[]; tables?: Table | Table[] | string | string[] };
```
Sources: [drizzle-orm/src/cache/core/cache.ts:67-67](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/cache/core/cache.ts#L67-L67)
> [!NOTE]
> The `NoopCache` implementation provides an empty implementation for `onMutate`, safely ignoring table mutation events when caching is disabled or unconfigured [[Cache Invalidation and Mutation Handling](#)].
Sources: [drizzle-orm/src/cache/core/cache.ts:62-64](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/cache/core/cache.ts#L62-L64)
### Upstash Mutation Execution via Lua
When database modifications trigger cache invalidation in `UpstashCache`, execution delegates to a specialized Lua script (`onMutateScript`) deployed to Redis [[Cache Invalidation and Mutation Handling](#)]. This script evaluates keys and arguments atomically to prune obsolete cache entries across composite table hashes and tag mapping structures [[Cache Invalidation and Mutation Handling](#)].
Sources: [drizzle-orm/src/cache/upstash/cache.ts:21-54](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/cache/upstash/cache.ts#L21-L54)
> [!CAUTION]
> The `onMutateScript` executes a set union (`SUNION`) across specified table keys to gather all composite table names linked to modified tables, subsequently issuing batch `DEL` commands to purge stale query results from Redis in a single atomic operation [[Cache Invalidation and Mutation Handling](#)].
Sources: [drizzle-orm/src/cache/upstash/cache.ts:42-53](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/cache/upstash/cache.ts#L42-L53)
## Driver and Serverless Runtime Adapters
### Session Options and NoopCache Wiring
Serverless and lightweight driver sessions initialize their options by defaulting unconfigured cache properties to `NoopCache`. Across driver implementations including `TiDBServerlessSession`, `NeonSession`, `XataHttpSession`, `GelDbSession`, `PgliteSession`, `OPSQLiteSession`, and `AwsDataApiSession`, the session constructor extracts the optional cache from the session options object or instantiates a fresh `NoopCache` instance.
```typescript
private options: TiDBServerlessSessionOptions = {},
) {
super(dialect);
this.client = tx ?? baseClient;
this.logger = options.logger ?? new NoopLogger();
this.cache = options.cache ?? new NoopCache();
}
```
Sources: [drizzle-orm/src/tidb-serverless/session.ts:124-130](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tidb-serverless/session.ts#L124-L130)
```typescript
constructor(
private client: XataHttpClient,
dialect: PgDialect,
private schema: RelationalSchemaConfig | undefined,
private options: XataHttpSessionOptions = {},
) {
super(dialect);
this.logger = options.logger ?? new NoopLogger();
this.cache = options.cache ?? new NoopCache();
}
```
Sources: [drizzle-orm/src/xata-http/session.ts:110-119](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/xata-http/session.ts#L110-L119)
```typescript
constructor(
private client: GelClient,
dialect: GelDialect,
private schema: RelationalSchemaConfig | undefined,
private options: GelSessionOptions = {},
) {
super(dialect);
this.logger = options.logger ?? new NoopLogger();
this.cache = options.cache ?? new NoopCache();
}
```
Sources: [drizzle-orm/src/gel/session.ts:117-126](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel/session.ts#L117-L126)
```typescript
constructor(
private client: PgliteClient | Transaction,
dialect: PgDialect,
private schema: RelationalSchemaConfig | undefined,
private options: PgliteSessionOptions = {},
) {
super(dialect);
this.logger = options.logger ?? new NoopLogger();
this.cache = options.cache ?? new NoopCache();
}
```
Sources: [drizzle-orm/src/pglite/session.ts:131-141](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pglite/session.ts#L131-L141)
```typescript
constructor(
private client: OPSQLiteConnection,
dialect: SQLiteAsyncDialect,
private schema: RelationalSchemaConfig | undefined,
options: OPSQLiteSessionOptions = {},
) {
super(dialect);
this.logger = options.logger ?? new NoopLogger();
this.cache = options.cache ?? new NoopCache();
}
```
Sources: [drizzle-orm/src/op-sqlite/session.ts:37-46](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/op-sqlite/session.ts#L37-L46)
```typescript
constructor(
/** @internal */
readonly client: AwsDataApiClient,
dialect: PgDialect,
private schema: RelationalSchemaConfig | undefined,
private options: AwsDataApiSessionOptions,
/** @internal */
readonly transactionId: string | undefined,
) {
super(dialect);
this.rawQuery = {
secretArn: options.secretArn,
resourceArn: options.resourceArn,
database: options.database,
};
this.cache = options.cache ?? new NoopCache();
}
```
Sources: [drizzle-orm/src/aws-data-api/pg/session.ts:175-191](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/aws-data-api/pg/session.ts#L175-L191)
```typescript
constructor(
public client: TSQL,
dialect: PgDialect,
private schema: RelationalSchemaConfig | undefined,
/** @internal */
readonly options: BunSQLSessionOptions = {},
) {
super(dialect);
this.logger = options.logger ?? new NoopLogger();
this.cache = options.cache ?? new NoopCache();
}
```
Sources: [drizzle-orm/src/bun-sql/session.ts:120-130](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/bun-sql/session.ts#L120-L130)
> [!NOTE]
> Synchronous storage environments such as `SQLiteDOSession` omit cache constructor arguments entirely within their prepared query initializers because synchronous runtime caching is unsupported.
Sources: [drizzle-orm/src/durable-sqlite/session.ts:100-111](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/durable-sqlite/session.ts#L100-L111)
### Prepared Query Cache Propagation
When sessions instantiate prepared queries, the session-level `cache` reference is passed directly into the query constructor. Prepared query classes such as `TiDBServerlessPreparedQuery`, `NeonPreparedQuery`, `LibSQLPreparedQuery`, `VercelPgPreparedQuery`, `XataHttpPreparedQuery`, `GelDbPreparedQuery`, `PglitePreparedQuery`, `OPSQLitePreparedQuery`, `NeonHttpPreparedQuery`, `AwsDataApiPreparedQuery`, and `BunSQLPreparedQuery` forward the cache instance, query metadata, and cache configuration objects up to base query classes.
| Driver Prepared Query | Client / Driver Type | Session Type | Cache Support |
| :--- | :--- | :--- | :--- |
| `TiDBServerlessPreparedQuery` | `Tx \| Connection` | `TiDBServerlessSession` | Yes |
| `NeonPreparedQuery` | `Pool \| PoolClient \| Client` | `NeonSession` | Yes |
| `LibSQLPreparedQuery` | `Client` | `LibSQLSession` | Yes |
| `VercelPgPreparedQuery` | `VercelPool \| VercelClient \| VercelPoolClient` | `VercelPgSession` | Yes |
| `XataHttpPreparedQuery` | `XataHttpClient` | `XataHttpSession` | Yes |
| `GelDbPreparedQuery` | `Client \| Transaction` | `GelDbSession` | Yes |
| `PglitePreparedQuery` | `PgliteClient \| Transaction` | `PgliteSession` | Yes |
| `OPSQLitePreparedQuery` | `OPSQLiteConnection` | `OPSQLiteSession` | Yes |
| `NeonHttpPreparedQuery` | `NeonHttpClient` | `NeonHttpSession` | Yes |
| `AwsDataApiPreparedQuery` | `AwsDataApiClient` | `AwsDataApiSession` | Yes |
| `BunSQLPreparedQuery` | `SQL` | `BunSQLSession` | Yes |
| `SQLiteDOPreparedQuery` | `DurableObjectStorage` | `SQLiteDOSession` | No (`undefined`) |
Sources: [drizzle-orm/src/tidb-serverless/session.ts:26-48](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tidb-serverless/session.ts#L26-L48), [drizzle-orm/src/neon-serverless/session.ts:27-49](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-serverless/session.ts#L27-L49), [drizzle-orm/src/libsql/session.ts:165-192](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/session.ts#L165-L192), [drizzle-orm/src/vercel-postgres/session.ts:26-48](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/vercel-postgres/session.ts#L26-L48), [drizzle-orm/src/xata-http/session.ts:27-45](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/xata-http/session.ts#L27-L45), [drizzle-orm/src/gel/session.ts:17-37](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel/session.ts#L17-L37), [drizzle-orm/src/pglite/session.ts:19-42](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pglite/session.ts#L19-L42), [drizzle-orm/src/op-sqlite/session.ts:112-133](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/op-sqlite/session.ts#L112-L133), [drizzle-orm/src/neon-http/session.ts:29-48](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-http/session.ts#L29-L48), [drizzle-orm/src/aws-data-api/pg/session.ts:30-55](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/aws-data-api/pg/session.ts#L30-L55), [drizzle-orm/src/bun-sql/session.ts:19-38](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/bun-sql/session.ts#L19-L38), [drizzle-orm/src/durable-sqlite/session.ts:90-111](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/durable-sqlite/session.ts#L90-L111)
> [!WARNING]
> When transaction boundaries are opened in serverless sessions—such as `TiDBServerlessSession.transaction`, `GelDbSession.transaction`, `PgliteSession.transaction`, and `AwsDataApiSession.transaction`—new session instances are created with native transaction handles while preserving reference to the parent session's configured `cache` instance.
Sources: [drizzle-orm/src/tidb-serverless/session.ts:173-191](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tidb-serverless/session.ts#L173-L191), [drizzle-orm/src/gel/session.ts:154-162](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel/session.ts#L154-L162), [drizzle-orm/src/pglite/session.ts:170-187](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pglite/session.ts#L170-L187), [drizzle-orm/src/aws-data-api/pg/session.ts:238-256](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/aws-data-api/pg/session.ts#L238-L256)
## Related
- [Sessions and Transactions](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/sessions-and-transactions)
- [Query Builder Foundation](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/query-builder-foundation)
---
## Technical docs: Logging and Tracing
URL: https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/logging-and-tracing
Relevant source files
The following files were used as context for generating this wiki page:
- [drizzle-orm/src/tracing.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tracing.ts)
- [drizzle-orm/src/sqlite-proxy/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-proxy/session.ts)
- [drizzle-orm/src/gel-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/dialect.ts)
- [drizzle-orm/src/libsql/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/session.ts)
- [drizzle-orm/src/neon-serverless/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-serverless/session.ts)
- [drizzle-orm/src/pg-core/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/session.ts)
- [drizzle-orm/src/gel-core/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/session.ts)
- [drizzle-orm/src/singlestore/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore/session.ts)
- [drizzle-orm/src/pg-proxy/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-proxy/session.ts)
- [drizzle-orm/src/bun-sql/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/bun-sql/session.ts)
- [drizzle-orm/src/node-postgres/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/node-postgres/session.ts)
- [drizzle-orm/src/pg-core/query-builders/insert.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/insert.ts)
- [drizzle-orm/src/pg-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/dialect.ts)
- [drizzle-orm/src/neon-http/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-http/session.ts)
- [drizzle-orm/src/planetscale-serverless/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/planetscale-serverless/session.ts)
- [drizzle-orm/src/tidb-serverless/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tidb-serverless/session.ts)
- [drizzle-orm/src/aws-data-api/pg/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/aws-data-api/pg/session.ts)
- [drizzle-orm/src/mysql2/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql2/session.ts)
- [drizzle-orm/src/singlestore-core/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/session.ts)
- [drizzle-orm/src/gel-core/query-builders/insert.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/insert.ts)
- [drizzle-orm/src/logger.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/logger.ts)
- [drizzle-orm/src/tracing-utils.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tracing-utils.ts)
- [drizzle-orm/src/op-sqlite/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/op-sqlite/session.ts)
- [drizzle-orm/src/singlestore-proxy/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-proxy/session.ts)
- [drizzle-orm/src/pg-core/query-builders/query.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query.ts)
- [drizzle-orm/src/sqlite-core/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/session.ts)
- [drizzle-orm/src/query-promise.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/query-promise.ts)
- [drizzle-orm/src/prisma/pg/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/prisma/pg/session.ts)
- [drizzle-orm/src/singlestore-core/query-builders/delete.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/query-builders/delete.ts)
- [drizzle-orm/src/mysql-core/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/session.ts)
## Overview
Drizzle ORM provides an integrated diagnostic infrastructure combining OpenTelemetry tracing and structured query logging to observe and monitor query execution lifecycle events. The tracing subsystem uses the `@opentelemetry/api` package to wrap operations in active spans like `drizzle.operation`, `drizzle.prepareQuery`, `drizzle.buildSQL`, `drizzle.execute`, `drizzle.driver.execute`, and `drizzle.mapResponse`, automatically capturing error statuses and ending spans when execution completes. Concurrently, session-level logging dispatches query strings and parameters through logger implementations such as `DefaultLogger` and `ConsoleLogWriter`, formatting parameters with JSON stringification. This dual architecture allows applications to track performance metrics, inspect parameterized query statements across various driver runtimes, and handle diagnostic errors during failed database interactions.
Sources: [drizzle-orm/src/tracing.ts:1-55](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tracing.ts#L1-L55), [drizzle-orm/src/logger.ts:1-39](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/logger.ts#L1-L39), [drizzle-orm/src/pg-core/session.ts:195-207](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/session.ts#L195-L207), [drizzle-orm/src/pg-proxy/session.ts:114-154](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-proxy/session.ts#L114-L154)
## OpenTelemetry tracing subsystem architecture
### Tracer Configuration and Module Integration
The OpenTelemetry tracing integration centers around the internal `tracer` object exported from `drizzle-orm/src/tracing.ts`. The module declares optional references to the `@opentelemetry/api` package and a raw tracer instance. When active spans are requested, the subsystem lazy-loads or references the tracer via `otel.trace.getTracer('drizzle-orm', npmVersion)`, utilizing the package version from `~/version.ts`. If `@opentelemetry/api` is not present in the runtime environment, span wrapping primitives bypass OpenTelemetry entirely and execute the provided callback directly.
```typescript
import type { Span, Tracer } from '@opentelemetry/api';
import { iife } from '~/tracing-utils.ts';
import { npmVersion } from '~/version.ts';
let otel: typeof import('@opentelemetry/api') | undefined;
let rawTracer: Tracer | undefined;
// try {
// otel = await import('@opentelemetry/api');
// } catch (err: any) {
// if (err.code !== 'MODULE_NOT_FOUND' && err.code !== 'ERR_MODULE_NOT_FOUND') {
// throw err;
// }
// }
type SpanName =
| 'drizzle.operation'
| 'drizzle.prepareQuery'
| 'drizzle.buildSQL'
| 'drizzle.execute'
| 'drizzle.driver.execute'
| 'drizzle.mapResponse';
/** @internal */
export const tracer = {
startActiveSpan unknown>(name: SpanName, fn: F): ReturnType {
if (!otel) {
return fn() as ReturnType;
}
if (!rawTracer) {
rawTracer = otel.trace.getTracer('drizzle-orm', npmVersion);
}
```
Sources: [drizzle-orm/src/tracing.ts:1-32](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tracing.ts#L1-L32)
> [!NOTE]
> If `@opentelemetry/api` is missing from the environment, `tracer.startActiveSpan` skips span creation and transparently executes the workload function without throwing module resolution errors.
### Span Names and Wrapping Primitives
The tracing subsystem defines a strict set of permitted operation names managed by the `SpanName` type. These identifiers cover the end-to-end query lifecycle from high-level operations down to driver-specific execution and response mapping.
| Span Name | Description |
| :--- | :--- |
| `drizzle.operation` | Top-level query builder or transactional operation wrapper |
| `drizzle.prepareQuery` | Statement preparation and parameter binding compilation |
| `drizzle.buildSQL` | SQL string generation and dialect operator construction |
| `drizzle.execute` | Query execution boundary across database sessions |
| `drizzle.driver.execute` | Low-level driver communication and transport layer invocation |
| `drizzle.mapResponse` | Raw database response parsing and entity mapping |
```typescript
type SpanName =
| 'drizzle.operation'
| 'drizzle.prepareQuery'
| 'drizzle.buildSQL'
| 'drizzle.execute'
| 'drizzle.driver.execute'
| 'drizzle.mapResponse';
```
Sources: [drizzle-orm/src/tracing.ts:15-21](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tracing.ts#L15-L21)
Span wrapping is executed via the `startActiveSpan` method, which delegates to an immediately invoked function expression helper (`iife`) defined in `drizzle-orm/src/tracing-utils.ts`.
```typescript
export function iife(fn: (...args: T) => U, ...args: T): U {
return fn(...args);
}
```
Sources: [drizzle-orm/src/tracing-utils.ts:1-3](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tracing-utils.ts#L1-L3-3)
The span wrapper wraps the callback execution inside a `try...catch...finally` block. If an exception occurs, the span status is explicitly set to `otel.SpanStatusCode.ERROR` with the error message extracted from the thrown instance, before rethrowing the error and ending the span.
```typescript
return iife(
(otel, rawTracer) =>
rawTracer.startActiveSpan(
name,
((span: Span) => {
try {
return fn(span);
} catch (e) {
span.setStatus({
code: otel.SpanStatusCode.ERROR,
message: e instanceof Error ? e.message : 'Unknown error', // eslint-disable-line no-instanceof/no-instanceof
});
throw e;
} finally {
span.end();
}
}) as F,
),
otel,
rawTracer,
);
},
```
Sources: [drizzle-orm/src/tracing.ts:34-55](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tracing.ts#L34-L55)
## Query builder span instrumentation
### Relational and Core Query Builder Spans
Query builder methods integrate directly with the tracing subsystem by wrapping statement preparation and query execution inside active spans. In PostgreSQL relational query builders (`PgRelationalQuery`), the `_prepare` method wraps statement construction and relational mapping within a `drizzle.prepareQuery` span.
```typescript
_prepare(name?: string): PgPreparedQuery {
return tracer.startActiveSpan('drizzle.prepareQuery', () => {
const { query, builtQuery } = this._toSQL();
return this.session.prepareQuery(
builtQuery,
undefined,
name,
true,
(rawRows, mapColumnValue) => {
const rows = rawRows.map((row) =>
mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue)
);
if (this.mode === 'first') {
return rows[0] as TResult;
}
return rows as TResult;
},
);
});
}
```
Sources: [drizzle-orm/src/pg-core/query-builders/query.ts:90-110](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query.ts#L90-L110)
When a relational query is executed via `execute()`, the operation is wrapped inside a `drizzle.operation` span before invoking the underlying prepared statement.
```typescript
override execute(): Promise {
return tracer.startActiveSpan('drizzle.operation', () => {
return this._prepare().execute(undefined, this.authToken);
});
}
```
Sources: [drizzle-orm/src/pg-core/query-builders/query.ts:152-156](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query.ts#L152-L156)
> [!NOTE]
> Relational execution relies on `_prepare()` internally, causing a nested trace structure where `drizzle.operation` invokes `drizzle.prepareQuery` during statement compilation.
### Dialect Compilation and Execution Flow
Query building across different dialects separates syntax compilation from session execution. For instance, SingleStore delete query builders (`SingleStoreDeleteBase`) invoke dialect builders like `buildDeleteQuery` and `sqlToQuery` during `getSQL` and `prepare` calls, passing table metadata and returning clauses directly to the session.
```typescript
getSQL(): SQL {
return this.dialect.buildDeleteQuery(this.config);
}
toSQL(): Query {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
prepare(): SingleStoreDeletePrepare {
return this.session.prepareQuery(
this.dialect.sqlToQuery(this.getSQL()),
this.config.returning,
undefined,
undefined,
undefined,
{
type: 'delete',
tables: extractUsedTable(this.config.table),
},
) as SingleStoreDeletePrepare;
}
```
Sources: [drizzle-orm/src/singlestore-core/query-builders/delete.ts:176-197](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/query-builders/delete.ts#L176-L197)
## Logger interface and default writers
### Logger Contracts and Writers
The logging subsystem defines two core abstraction contracts: `Logger`, which exposes a `logQuery` method accepting a SQL query string and an array of unknown parameters, and `LogWriter`, which defines a simple `write` method for delivering text messages.
```typescript
export interface Logger {
logQuery(query: string, params: unknown[]): void;
}
export interface LogWriter {
write(message: string): void;
}
```
Sources: [drizzle-orm/src/logger.ts:3-9](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/logger.ts#L3-L9)
The built-in output implementation is `ConsoleLogWriter`, which implements `LogWriter` by forwarding messages directly to `console.log`. Both `ConsoleLogWriter` and `DefaultLogger` define static `entityKind` metadata identifiers for runtime type inspection.
```typescript
export class ConsoleLogWriter implements LogWriter {
static readonly [entityKind]: string = 'ConsoleLogWriter';
write(message: string) {
console.log(message);
}
}
```
Sources: [drizzle-orm/src/logger.ts:11-17](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/logger.ts#L11-L17)
### DefaultLogger and Formatting Logic
`DefaultLogger` implements the `Logger` interface and accepts an optional configuration object containing a custom `LogWriter`. If no writer is supplied during instantiation, it defaults to a new instance of `ConsoleLogWriter`.
```typescript
export class DefaultLogger implements Logger {
static readonly [entityKind]: string = 'DefaultLogger';
readonly writer: LogWriter;
constructor(config?: { writer: LogWriter }) {
this.writer = config?.writer ?? new ConsoleLogWriter();
}
```
Sources: [drizzle-orm/src/logger.ts:19-26](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/logger.ts#L19-L26)
When `logQuery` is invoked, `DefaultLogger` serializes each query parameter into a JSON string using `JSON.stringify`. If serialization fails due to circular references or unsupported types, it falls back to standard `String(p)` coercion. The formatted parameter array is appended to the query string under the suffix `-- params: [...]` only when parameters are present, and the resulting payload is dispatched to the configured writer.
```typescript
logQuery(query: string, params: unknown[]): void {
const stringifiedParams = params.map((p) => {
try {
return JSON.stringify(p);
} catch {
return String(p);
}
});
const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(', ')}]` : '';
this.writer.write(`Query: ${query}${paramsStr}`);
}
}
```
Sources: [drizzle-orm/src/logger.ts:28-39](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/logger.ts#L28-L39)
> [!TIP]
> If `JSON.stringify` throws an error on complex parameter structures inside `DefaultLogger.logQuery`, the parameter falls back to `String(p)` rather than aborting query logging.
Additionally, `NoopLogger` provides a null-pattern implementation of `Logger` where `logQuery` performs no operations.
```typescript
export class NoopLogger implements Logger {
static readonly [entityKind]: string = 'NoopLogger';
logQuery(): void {
// noop
}
}
```
Sources: [drizzle-orm/src/logger.ts:41-47](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/logger.ts#L41-L47)
## Session level query logging integration
### Logger Dispatch Across Drivers
Database sessions and prepared query implementations across drivers coordinate with the logging subsystem by invoking `logQuery` on the configured `Logger` instance right before executing any statement. Each driver binds placeholders via `fillPlaceholders` and dispatches the interpolated query text and parameter array. For example, `RemotePreparedQuery` in the SQLite proxy driver invokes `this.logger.logQuery(this.query.sql, params)` across its `run`, `all`, `get`, and `values` execution methods prior to invoking the remote client callback.
```typescript
async run(placeholderValues?: Record): Promise {
const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
this.logger.logQuery(this.query.sql, params);
return await this.queryWithCache(this.query.sql, params, async () => {
return await (this.client as AsyncRemoteCallback)(this.query.sql, params, 'run');
});
}
```
Sources: [drizzle-orm/src/sqlite-proxy/session.ts:177-183](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-proxy/session.ts#L177-L183)
Similarly, `LibSQLPreparedQuery` dispatches `logger.logQuery(query.sql, params)` across execution branches before executing statements through the underlying LibSQL client or active transaction.
```typescript
async run(placeholderValues?: Record): Promise {
const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
this.logger.logQuery(this.query.sql, params);
return await this.queryWithCache(this.query.sql, params, async () => {
const stmt: InStatement = { sql: this.query.sql, args: params as InArgs };
return this.tx ? this.tx.execute(stmt) : this.client.execute(stmt);
});
}
```
Sources: [drizzle-orm/src/libsql/session.ts:194-201](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/session.ts#L194-L201)
PostgreSQL and MySQL drivers follow the same dispatch contract. In `NeonPreparedQuery`, `BunSQLPreparedQuery`, `NeonHttpPreparedQuery`, `TiDBServerlessPreparedQuery`, and `AwsDataApiPreparedQuery`, parameter binding precedes `logger.logQuery` invocation. `AwsDataApiPreparedQuery` extracts parameters from the raw query configuration input parameters before logging.
```typescript
async values(placeholderValues: Record = {}): Promise {
const params = fillPlaceholders(this.params, placeholderValues ?? {});
this.rawQuery.input.parameters = params.map((param, index) => ({
name: `${index + 1}`,
...toValueParam(param, this.typings[index]),
}));
this.options.logger?.logQuery(this.rawQuery.input.sql!, this.rawQuery.input.parameters);
```
Sources: [drizzle-orm/src/aws-data-api/pg/session.ts:110-119](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/aws-data-api/pg/session.ts#L110-L119)
Session-level fallback helpers also integrate logging directly. In `TiDBServerlessSession`, direct `all` queries compute the query structure via the dialect, invoke `this.logger.logQuery(querySql.sql, querySql.params)`, and dispatch to the client.
```typescript
override all(query: SQL): Promise {
const querySql = this.dialect.sqlToQuery(query);
this.logger.logQuery(querySql.sql, querySql.params);
return this.client.execute(querySql.sql, querySql.params) as Promise;
}
```
Sources: [drizzle-orm/src/tidb-serverless/session.ts:159-163](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tidb-serverless/session.ts#L159-L163)
### Driver Logging Integration Matrix
| Driver Module | Prepared Query Class | Session Class | Default Logger Fallback |
| :--- | :--- | :--- | :--- |
| `sqlite-proxy` | `RemotePreparedQuery` | `SQLiteProxySession` | `NoopLogger` |
| `libsql` | `LibSQLPreparedQuery` | `LibSQLSession` | `NoopLogger` |
| `neon-serverless` | `NeonPreparedQuery` | `NeonSession` | `NoopLogger` |
| `bun-sql` | `BunSQLPreparedQuery` | `BunSQLSession` | `NoopLogger` |
| `neon-http` | `NeonHttpPreparedQuery` | `NeonHttpSession` | `NoopLogger` |
| `tidb-serverless` | `TiDBServerlessPreparedQuery` | `TiDBServerlessSession` | `NoopLogger` |
| `aws-data-api/pg` | `AwsDataApiPreparedQuery` | `AwsDataApiSession` | `NoopLogger` |
| `op-sqlite` | `OPSQLitePreparedQuery` | `OPSQLiteSession` | `NoopLogger` |
| `singlestore-proxy` | `PreparedQuery` | `SingleStoreRemoteSession` | `NoopLogger` |
| `prisma/pg` | `PrismaPgPreparedQuery` | `PrismaPgSession` | `NoopLogger` |
Sources: [drizzle-orm/src/sqlite-proxy/session.ts:143-153](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-proxy/session.ts#L143-L153), [drizzle-orm/src/libsql/session.ts:165-174](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/session.ts#L165-L174), [drizzle-orm/src/neon-serverless/session.ts:27-38](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-serverless/session.ts#L27-L38), [drizzle-orm/src/bun-sql/session.ts:19-28](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/bun-sql/session.ts#L19-L28), [drizzle-orm/src/neon-http/session.ts:29-37](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-http/session.ts#L29-L37), [drizzle-orm/src/tidb-serverless/session.ts:26-34](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tidb-serverless/session.ts#L26-L34), [drizzle-orm/src/aws-data-api/pg/session.ts:30-42](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/aws-data-api/pg/session.ts#L30-L42), [drizzle-orm/src/op-sqlite/session.ts:28-46](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/op-sqlite/session.ts#L28-L46), [drizzle-orm/src/singlestore-proxy/session.ts:29-45](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-proxy/session.ts#L29-L45), [drizzle-orm/src/prisma/pg/session.ts:16-25](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/prisma/pg/session.ts#L16-L25)
> [!IMPORTANT]
> When options omit a logger during session initialization (such as in `BunSQLSession`, `TiDBServerlessSession`, and `OPSQLiteSession`), sessions instantiate a `NoopLogger` to ensure safe method invocation without requiring explicit null checks across prepared queries.
Sources: [drizzle-orm/src/bun-sql/session.ts:128-129](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/bun-sql/session.ts#L128-L129), [drizzle-orm/src/tidb-serverless/session.ts:128-129](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tidb-serverless/session.ts#L128-L129), [drizzle-orm/src/op-sqlite/session.ts:44-45](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/op-sqlite/session.ts#L44-L45)
## Diagnostics and tracing error handling
### Active Span Exception Capture
```typescript
startActiveSpan unknown>(name: SpanName, fn: F): ReturnType {
if (!otel) {
return fn() as ReturnType;
}
if (!rawTracer) {
rawTracer = otel.trace.getTracer('drizzle-orm', npmVersion);
}
return iife(
(otel, rawTracer) =>
rawTracer.startActiveSpan(
name,
((span: Span) => {
try {
return fn(span);
} catch (e) {
span.setStatus({
code: otel.SpanStatusCode.ERROR,
message: e instanceof Error ? e.message : 'Unknown error', // eslint-disable-line no-instanceof/no-instanceof
});
throw e;
} finally {
span.end();
}
}) as F,
),
otel,
rawTracer,
);
},
```
Sources: [drizzle-orm/src/tracing.ts:25-55](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tracing.ts#L25-L55)
The tracing subsystem intercepts exceptions during active span execution via the `startActiveSpan` wrapper. When an error is thrown within the callback function `fn(span)`, the execution catches the exception in a `try...catch` block, marks the OpenTelemetry span status as an error, and rethrows the original error.
> [!WARNING]
> If OpenTelemetry (`otel`) is not imported or available in the runtime environment, `startActiveSpan` bypasses span creation entirely and directly executes the callback function without error capture or status reporting.
Sources: [drizzle-orm/src/tracing.ts:26-28](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tracing.ts#L26-L28)
### Span Status and Error Properties
| Condition | Span Status Code | Error Message Extraction Strategy |
| :--- | :--- | :--- |
| Caught value is an `Error` instance | `otel.SpanStatusCode.ERROR` | `e.message` |
| Caught value is not an `Error` instance | `otel.SpanStatusCode.ERROR` | `'Unknown error'` |
Sources: [drizzle-orm/src/tracing.ts:42-45](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tracing.ts#L42-L45)
> [!IMPORTANT]
> The span lifecycle guarantees that `span.end()` is always invoked within a `finally` block, ensuring spans are closed even when query execution or response mapping throws an exception.
Sources: [drizzle-orm/src/tracing.ts:47-49](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tracing.ts#L47-L49)
## Related
- [Sessions and Transactions](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/sessions-and-transactions)
---
## Technical docs: Dialects And Schema Schema Definition
URL: https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/dialects-and-schema/dialects-and-schema-schema-definition
Relevant source files
The following files were used as context for generating this wiki page:
- [drizzle-kit/src/introspect-gel.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/introspect-gel.ts)
- [drizzle-orm/type-tests/pg/tables.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/pg/tables.ts)
- [drizzle-kit/src/serializer/pgSerializer.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/serializer/pgSerializer.ts)
- [drizzle-kit/src/introspect-pg.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/introspect-pg.ts)
- [drizzle-kit/src/sqlgenerator.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/sqlgenerator.ts)
- [drizzle-kit/src/serializer/pgSchema.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/serializer/pgSchema.ts)
- [drizzle-kit/src/serializer/gelSerializer.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/serializer/gelSerializer.ts)
- [drizzle-orm/type-tests/geldb/tables.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/geldb/tables.ts)
- [drizzle-kit/src/serializer/gelSchema.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/serializer/gelSchema.ts)
- [drizzle-kit/src/introspect-singlestore.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/introspect-singlestore.ts)
- [drizzle-orm/src/pg-core/indexes.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/indexes.ts)
- [drizzle-orm/src/pg-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/dialect.ts)
- [drizzle-orm/src/gel-core/indexes.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/indexes.ts)
- [drizzle-orm/src/pg-core/columns/common.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/columns/common.ts)
- [drizzle-orm/src/pg-core/table.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/table.ts)
- [drizzle-orm/src/pg-core/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/index.ts)
- [drizzle-orm/src/gel-core/columns/all.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/columns/all.ts)
- [drizzle-orm/src/gel-core/columns/common.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/columns/common.ts)
- [drizzle-orm/src/gel-core/schema.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/schema.ts)
- [drizzle-orm/src/gel-core/table.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/table.ts)
- [drizzle-orm/src/mysql-core/columns/all.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/columns/all.ts)
- [drizzle-orm/src/mysql-core/columns/common.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/columns/common.ts)
- [drizzle-orm/src/mysql-core/foreign-keys.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/foreign-keys.ts)
- [drizzle-orm/src/mysql-core/indexes.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/indexes.ts)
- [drizzle-orm/src/mysql-core/schema.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/schema.ts)
- [drizzle-orm/src/mysql-core/table.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/table.ts)
- [drizzle-orm/src/pg-core/columns/all.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/columns/all.ts)
- [drizzle-orm/src/pg-core/columns/postgis_extension/geometry.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/columns/postgis_extension/geometry.ts)
- [drizzle-orm/src/pg-core/columns/vector_extension/vector.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/columns/vector_extension/vector.ts)
- [drizzle-orm/src/pg-core/policies.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/policies.ts)
## Overview
The schema definition layer in Drizzle ORM provides a type-safe, declarative abstraction for structuring database tables, columns, constraints, indexes, sequences, and security primitives across different database engines (PostgreSQL, MySQL, SQLite, SingleStore, and Gel). By utilizing fluent method chaining and TypeScript type inference, Drizzle core modules allow developers to map database catalogs directly to strongly typed models without sacrificing native SQL control. This architecture bridges the gap between raw DDL statements and application code, powering migration generation via [Migration Toolkit Schema](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/migration-toolkit/migration-toolkit-schema) and database reverse engineering via [Database Introspection](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/migration-toolkit/database-introspection).
---
## Gel Schema Definition
Gel schema definitions are handled via the `gel-core` package, mimicking PostgreSQL-like semantics while supporting Gel-specific types and structures. Tables are declared using `gelTable` or via `GelSchema.table()` instances, tracking columns, foreign keys, and indexes in a unified metadata structure.
Sources: [drizzle-orm/src/gel-core/table.ts:73-141](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/table.ts#L73-L141)
The following call chain demonstrates how Gel tables and their columns are initialized and built during schema parsing:
`gelTable()` → `gelTableWithSchema()` → `getGelColumnBuilders()` → `columnBuilder.build()`
Sources: [drizzle-orm/src/gel-core/columns/all.ts:23-46](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/columns/all.ts#L23-L46)
```mermaid
sequenceDiagram
participant TableDef as gelTable
participant TableWithSchema as gelTableWithSchema
participant Builders as getGelColumnBuilders
participant ColumnBuilder as GelColumnBuilder
participant Column as GelColumn
TableDef->>TableWithSchema: gelTable(name, columns, extraConfig)
TableWithSchema->>Builders: getGelColumnBuilders()
Builders-->>TableWithSchema: Returns column builder map
TableWithSchema->>ColumnBuilder: setName(name)
ColumnBuilder->>Column: build(rawTable)
Column-->>TableWithSchema: Returns built column instance
```
Sources: [drizzle-orm/src/gel-core/table.ts:249-251](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/table.ts#L249-L251)
```typescript
import { gelTable, integer, text, index, check } from '~/gel-core/index.ts';
export const users = gelTable(
'users_table',
{
id: integer('id').primaryKey(),
age: integer('age1').notNull(),
className: text('class').notNull(),
},
(users) => [
index('usersAgeIdx').on(users.age.asc().nullsFirst()),
check('legalAge', sql`${users.age} > 18`),
]
);
```
Sources: [drizzle-orm/type-tests/geldb/tables.ts:65-98](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/geldb/tables.ts#L65-L98)
---
## MySQL Schema Definition
MySQL schema definitions reside in `mysql-core`, offering support for auto-incrementing columns, storage engines, table-level constraints, and character sets. Tables are initialized via `mysqlTable` or `mysqlDatabase().table()`.
Sources: [drizzle-orm/src/mysql-core/table.ts:61-116](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/table.ts#L61-L116)
Columns supporting auto-increment extend `MySqlColumnBuilderWithAutoIncrement`, enabling the `.autoincrement()` modifier which automatically flags the column as having a default value in the Drizzle type system.
Sources: [drizzle-orm/src/mysql-core/columns/common.ts:128-145](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/columns/common.ts#L128-L145)
Index configurations for MySQL utilize `IndexBuilderOn` to manage column lists and algorithms.
Sources: [drizzle-orm/src/mysql-core/indexes.ts:34-42](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/indexes.ts#L34-L42)
```typescript
import { mysqlTable, int, varchar, index } from '~/mysql-core/index.ts';
export const users = mysqlTable(
'users',
{
id: int('id').primaryKey().autoincrement(),
email: varchar('email', { length: 255 }).notNull().unique(),
},
(table) => [
index('email_idx').using('btree').on(table.email),
]
);
```
Sources: [drizzle-orm/src/mysql-core/table.ts:119-147](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/table.ts#L119-L147)
---
## PostgreSQL Schema Definition
### Column Builders and Extensions
PostgreSQL schema definitions utilize `pg-core` and provide extensive capabilities including standard types, PostGIS extensions, `pgvector` embeddings, sequences, check constraints, unique constraints, and row-level security (RLS) policies. PostgreSQL supports complex structural column builders such as `geometry` for spatial data and `vector` for machine learning embeddings. When defining vectors, specifying an operator class (such as `vector_cosine_ops` or `vector_l2_ops`) during index creation is required by `pgvector`.
Sources: [drizzle-orm/src/pg-core/columns/postgis_extension/geometry.ts:105-119](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/columns/postgis_extension/geometry.ts#L105-L119), [drizzle-orm/src/pg-core/columns/vector_extension/vector.ts:70-79](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/columns/vector_extension/vector.ts#L70-L79)
```typescript
import { pgTable, serial } from '~/pg-core/index.ts';
import { geometry } from '~/pg-core/columns/postgis_extension/geometry.ts';
import { vector } from '~/pg-core/columns/vector_extension/vector.ts';
export const items = pgTable('items', {
id: serial('id').primaryKey(),
location: geometry('location', { srid: 4326, mode: 'xy' }),
embedding: vector('embedding', { dimensions: 1536 }),
});
```
Sources: [drizzle-orm/type-tests/pg/tables.ts:1312-1335](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/pg/tables.ts#L1312-L1335)
### Indexes and Row-Level Security
Row-Level Security (RLS) can be enabled on tables using the `.enableRLS()` method chain, and security policies are attached using `pgPolicy`.
Sources: [drizzle-orm/src/pg-core/table.ts:126-136](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/table.ts#L126-L136), [drizzle-orm/src/pg-core/policies.ts:35-52](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/policies.ts#L35-L52)
```typescript
import { pgTable, text, integer, index, pgPolicy } from '~/pg-core/index.ts';
import { sql } from '~/sql/sql.ts';
export const documents = pgTable(
'documents',
{
id: integer('id').primaryKey(),
ownerId: text('owner_id').notNull(),
},
(table) => [
index('owner_idx').using('btree', table.ownerId.asc()),
pgPolicy('user_isolation_policy', {
for: 'all',
to: 'public',
using: sql`owner_id = current_user`,
}),
]
).enableRLS();
```
Sources: [drizzle-orm/src/pg-core/indexes.ts:159-178](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/indexes.ts#L159-L178)
---
## SingleStore Schema Definition
SingleStore schemas map distributed relational database capabilities using `singlestoreSchema` and `singlestoreTable`.
Sources: [drizzle-kit/src/introspect-singlestore.ts:10-13](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/introspect-singlestore.ts#L10-L13)
Introspection routines convert database column defaults, JSON types, and indexes into corresponding Drizzle schema declarations.
Sources: [drizzle-kit/src/introspect-singlestore.ts:139-156](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/introspect-singlestore.ts#L139-L156)
```typescript
import { singlestoreTable, int, varchar } from 'drizzle-orm/singlestore-core';
export const storeItems = singlestoreTable('store_items', {
id: int('id').primaryKey().autoincrement(),
title: varchar('title', { length: 128 }).notNull(),
});
```
Sources: [drizzle-kit/src/introspect-singlestore.ts:19-55](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/introspect-singlestore.ts#L19-L55)
---
## SQLite Schema Definition
SQLite schema definitions leverage lightweight type mappings suitable for embedded and edge runtimes (such as Cloudflare D1 or Expo SQLite).
Sources: [drizzle-kit/src/sqlgenerator.ts:117-124](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/sqlgenerator.ts#L117-L124)
They handle primary keys, unique constraints, and foreign key references through `sqlite-core`.
Sources: [drizzle-kit/src/sqlgenerator.ts:125-142](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/sqlgenerator.ts#L125-L142)
## Related
- [Dialects And Schema Query Builders](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/dialects-and-schema/dialects-and-schema-query-builders)
- [Table and Column Models](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/table-and-column-models)
- [Drivers And Runtimes](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/drivers-and-runtimes/drivers-and-runtimes)
- [Edge and Mobile SQLite](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/drivers-and-runtimes/edge-and-mobile-sqlite)
---
## Technical docs: Dialects And Schema Query Builders
URL: https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/dialects-and-schema/dialects-and-schema-query-builders
Relevant source files
The following files were used as context for generating this wiki page:
- [drizzle-orm/src/pg-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/dialect.ts)
- [drizzle-orm/src/gel-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/dialect.ts)
- [drizzle-orm/src/pg-core/query-builders/insert.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/insert.ts)
- [drizzle-orm/type-tests/pg/tables.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/pg/tables.ts)
- [drizzle-orm/src/pg-core/query-builders/refresh-materialized-view.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/refresh-materialized-view.ts)
- [drizzle-orm/src/sqlite-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/dialect.ts)
- [drizzle-orm/src/singlestore-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/dialect.ts)
- [drizzle-orm/src/gel-core/query-builders/refresh-materialized-view.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/refresh-materialized-view.ts)
- [drizzle-orm/src/mysql-core/dialect.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/dialect.ts)
- [drizzle-orm/src/pg-core/query-builders/update.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/update.ts)
- [drizzle-orm/src/pg-core/db.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/db.ts)
- [drizzle-orm/src/sqlite-core/query-builders/insert.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/insert.ts)
- [drizzle-orm/src/gel-core/query-builders/insert.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/insert.ts)
- [drizzle-orm/src/pg-core/query-builders/query.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/query.ts)
- [drizzle-orm/src/pg-core/query-builders/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/index.ts)
- [drizzle-orm/src/pg-core/query-builders/select.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/select.ts)
- [drizzle-orm/src/singlestore-core/query-builders/insert.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/query-builders/insert.ts)
- [drizzle-orm/src/pg-core/view.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/view.ts)
- [drizzle-orm/src/pg-core/query-builders/delete.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/delete.ts)
- [drizzle-orm/type-tests/sqlite/insert.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/sqlite/insert.ts)
- [drizzle-orm/type-tests/pg/insert.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/pg/insert.ts)
- [drizzle-orm/src/gel-core/query-builders/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/index.ts)
- [drizzle-orm/src/gel-core/db.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/db.ts)
- [drizzle-orm/src/gel-core/query-builders/select.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/select.ts)
- [drizzle-orm/src/gel-core/query-builders/update.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/update.ts)
## Overview
The Drizzle ORM query building architecture relies on dialect-specific compiler components coupled with fluent query builder classes to transform high-level method chains into parameterized SQL AST fragments. Each database dialect (PostgreSQL, Gel, SQLite, MySQL, and SingleStore) provides its own dialect driver class that manages identifier escaping, parameter formatting, casing cache transformations, and clause assembly for insert, update, delete, and select operations.
Sources: [drizzle-orm/src/pg-core/dialect.ts:609-618](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/dialect.ts#L609-L618)
```mermaid
flowchart TD
QB["Query Builder API
(.insert(), .select(), .update())"] --> Config["Query Configuration Object"]
Config --> Dialect["Dialect Compiler
(PgDialect, SQLiteDialect, etc.)"]
Dialect --> SQLAST["SQL AST & Chunks"]
SQLAST --> QueryWithTypings["sql.toQuery()"]
QueryWithTypings --> PreparedQuery["Prepared Statement / Session Execution"]
```
Sources: [drizzle-orm/src/sqlite-core/dialect.ts:596-604](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/dialect.ts#L596-L604)
---
## Gel Query Builders
The Gel query builder subsystem shares architectural lineages with PostgreSQL-core query builders, utilizing `GelDialect`, `GelInsertBase`, `GelSelectBase`, and `GelUpdateBase` to compile queries targeting Gel databases. Insert configurations handle column filtering via `col.shouldDisableInsert()`, fallback to column default functions (`col.defaultFn`) or `onUpdateFn`, and compile `returning` and `on conflict` clauses when present.
Sources: [drizzle-orm/src/gel-core/dialect.ts:508-575](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/dialect.ts#L508-L575)
```typescript
const inserted = await db.insert(users)
.values({ name: 'Gel User' })
.returning();
```
Sources: [drizzle-orm/src/gel-core/query-builders/insert.ts:220-279](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/insert.ts#L220-L279)
The Gel selection framework leverages `GelSelectBuilder` and `GelSelectQueryBuilderBase` to manage complex relation projections, join configurations, and set operators (`union`, `intersect`, `except`) with strict key validation checks.
Sources: [drizzle-orm/src/gel-core/query-builders/select.ts:60-145](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/select.ts#L60-L145)
> [!NOTE]
> Gel query builder methods validate set operator compatibility by inspecting whether left and right selection keys match identically and maintain the same order.
Sources: [drizzle-orm/src/gel-core/query-builders/select.ts:515-520](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/select.ts#L515-L520)
```typescript
if (!haveSameKeys((leftSelect as any).getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {
throw new Error(
'Set operator error (union / intersect / except): selected fields are not the same or are in a different order',
);
}
```
Sources: [drizzle-orm/src/gel-core/query-builders/select.ts:1119-1125](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/gel-core/query-builders/select.ts#L1119-L1125)
---
## MySQL Query Builders
MySQL-core query compilation is managed by `MySqlDialect` alongside `MySqlInsertConfig` and related query builders. When compiling insert queries via `buildInsertQuery`, the dialect filters out insert-disabled columns and iterates over input value records.
Sources: [drizzle-orm/src/mysql-core/dialect.ts:561-567](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/dialect.ts#L561-L567)
```typescript
buildInsertQuery({
table,
values: valuesOrSelect,
ignore,
onConflict,
select,
}: MySqlInsertConfig): { sql: SQL; generatedIds: Record[] } {
```
Sources: [drizzle-orm/src/mysql-core/dialect.ts:561-567](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/dialect.ts#L561-L567)
For each column entry during an insert operation, if a field value is `undefined` or an unassigned `Param`, the dialect checks column defaults (`col.defaultFn`) or update functions (`col.onUpdateFn`), populates generated ID tracking dictionaries, and constructs `ignore` and `on duplicate key` clauses.
Sources: [drizzle-orm/src/mysql-core/dialect.ts:586-645](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/mysql-core/dialect.ts#L586-L645)
> [!IMPORTANT]
> MySQL does not support a native `do nothing` conflict clause directly; developers achieve this behavior by setting a unique column to its own value (e.g., `{ id: sql`id` }`) within `.onDuplicateKeyUpdate()`.
Sources: [drizzle-orm/src/singlestore-core/query-builders/insert.ts:246-253](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/query-builders/insert.ts#L246-L253)
```typescript
onDuplicateKeyUpdate(
config: SingleStoreInsertOnDuplicateKeyUpdateConfig,
): SingleStoreInsertWithout {
const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
this.config.onConflict = sql`update ${setSql}`;
return this as any;
}
```
Sources: [drizzle-orm/src/singlestore-core/query-builders/insert.ts:246-253](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/query-builders/insert.ts#L246-L253)
---
## PostgreSQL Query Builders
PostgreSQL dialect compilation (`PgDialect`) drives advanced clause generation including CTEs (`withList`), column casing identifiers, system value overrides (`overriding system value`), and conflict resolution.
Sources: [drizzle-orm/src/pg-core/dialect.ts:513-515](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/dialect.ts#L513-L515)
```typescript
buildInsertQuery(
{ table, values: valuesOrSelect, onConflict, returning, withList, select, overridingSystemValue_ }: PgInsertConfig,
): SQL {
```
Sources: [drizzle-orm/src/pg-core/dialect.ts:513-515](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/dialect.ts#L513-L515)
The `PgInsertBase` class provides conflict handling methods `.onConflictDoNothing()` and `.onConflictDoUpdate()`.
Sources: [drizzle-orm/src/pg-core/query-builders/insert.ts:369-389](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/insert.ts#L369-L389)
```typescript
onConflictDoUpdate(
config: PgInsertOnConflictDoUpdateConfig,
): PgInsertWithout {
if (config.where && (config.targetWhere || config.setWhere)) {
throw new Error(
'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.',
);
}
const whereSql = config.where ? sql` where ${config.where}` : undefined;
const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : undefined;
const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : undefined;
const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
let targetColumn = '';
targetColumn = Array.isArray(config.target)
? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(',')
: this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target));
this.config.onConflict = sql`(${
sql.raw(targetColumn)
})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`;
return this as any;
}
```
Sources: [drizzle-orm/src/pg-core/query-builders/insert.ts:369-389](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/insert.ts#L369-L389)
PostgreSQL views and materialized views support execution refreshing via `PgRefreshMaterializedView`.
Sources: [drizzle-orm/src/pg-core/query-builders/refresh-materialized-view.ts:30-65](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/refresh-materialized-view.ts#L30-L65)
```typescript
export class PgRefreshMaterializedView
extends QueryPromise>
implements RunnableQuery, 'pg'>, SQLWrapper
{
static override readonly [entityKind]: string = 'PgRefreshMaterializedView';
private config: {
view: PgMaterializedView;
concurrently?: boolean;
withNoData?: boolean;
};
constructor(
view: PgMaterializedView,
private session: PgSession,
private dialect: PgDialect,
) {
super();
this.config = { view };
}
concurrently(): this {
if (this.config.withNoData !== undefined) {
throw new Error('Cannot use concurrently and withNoData together');
}
this.config.concurrently = true;
return this;
}
withNoData(): this {
if (this.config.concurrently !== undefined) {
throw new Error('Cannot use concurrently and withNoData together');
}
this.config.withNoData = true;
return this;
}
```
Sources: [drizzle-orm/src/pg-core/query-builders/refresh-materialized-view.ts:30-65](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/refresh-materialized-view.ts#L30-L65)
> [!CAUTION]
> Attempting to combine `.concurrently()` and `.withNoData()` on a materialized view refresh triggers an explicit error invariant check in both PostgreSQL and Gel implementations.
Sources: [drizzle-orm/src/pg-core/query-builders/refresh-materialized-view.ts:51-54](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/refresh-materialized-view.ts#L51-L54)
```typescript
if (this.config.withNoData !== undefined) {
throw new Error('Cannot use concurrently and withNoData together');
}
```
Sources: [drizzle-orm/src/pg-core/query-builders/refresh-materialized-view.ts:51-54](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/query-builders/refresh-materialized-view.ts#L51-L54)
---
## SingleStore Query Builders
SingleStore query building is directed by `SingleStoreDialect` and `SingleStoreInsertBase`. The dialect handles migration bootstrapping by verifying and creating the `__drizzle_migrations` table via `session.execute()`, and executes insert queries supporting `ignore` flags and duplicate key updates.
Sources: [drizzle-orm/src/singlestore-core/dialect.ts:53-66](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/dialect.ts#L53-L66)
```typescript
buildInsertQuery({
table,
values,
ignore,
onConflict,
}: SingleStoreInsertConfig): {
sql: SQL;
generatedIds: Record[];
} {
```
Sources: [drizzle-orm/src/singlestore-core/dialect.ts:519-527](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/dialect.ts#L519-L527)
When executing inserts, SingleStore tracks primary key auto-increment columns to generate response IDs, formatting clauses with `on duplicate key update`.
Sources: [drizzle-orm/src/singlestore-core/query-builders/insert.ts:246-253](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/query-builders/insert.ts#L246-L253)
```typescript
onDuplicateKeyUpdate(
config: SingleStoreInsertOnDuplicateKeyUpdateConfig,
): SingleStoreInsertWithout {
const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
this.config.onConflict = sql`update ${setSql}`;
return this as any;
}
```
Sources: [drizzle-orm/src/singlestore-core/query-builders/insert.ts:246-253](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-core/query-builders/insert.ts#L246-L253)
---
## SQLite Query Builders
SQLite query compilation (`SQLiteDialect`) manages parameter formatting (`?`), string escaping (`escapeString`), and identifier quoting (`escapeName`).
Sources: [drizzle-orm/src/sqlite-core/dialect.ts:57-67](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/dialect.ts#L57-L67)
```typescript
escapeName(name: string): string {
return `"${name.replace(/"/g, '""')}"`;
}
escapeParam(_num: number): string {
return '?';
}
escapeString(str: string): string {
return `'${str.replace(/'/g, "''")}'`;
}
```
Sources: [drizzle-orm/src/sqlite-core/dialect.ts:57-67](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/dialect.ts#L57-L67)
The `SQLiteInsertBase` builder handles table insertion records, falling back to column defaults or `null` values when parameters are omitted, and supports `.returning()` and `.onConflictDoNothing()` / `.onConflictDoUpdate()` clauses.
Sources: [drizzle-orm/src/sqlite-core/query-builders/insert.ts:306-317](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/insert.ts#L306-L317)
```typescript
onConflictDoNothing(config: { target?: IndexColumn | IndexColumn[]; where?: SQL } = {}): this {
if (!this.config.onConflict) this.config.onConflict = [];
if (config.target === undefined) {
this.config.onConflict.push(sql` on conflict do nothing`);
} else {
const targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;
const whereSql = config.where ? sql` where ${config.where}` : sql``;
this.config.onConflict.push(sql` on conflict ${targetSql} do nothing${whereSql}`);
}
return this;
}
```
Sources: [drizzle-orm/src/sqlite-core/query-builders/insert.ts:306-317](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/query-builders/insert.ts#L306-L317)
## Related
- [Dialects And Schema Schema Definition](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/dialects-and-schema/dialects-and-schema-schema-definition)
- [Drivers And Runtimes](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/drivers-and-runtimes/drivers-and-runtimes)
---
## Technical docs: Drivers And Runtimes
URL: https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/drivers-and-runtimes/drivers-and-runtimes
Relevant source files
The following files were used as context for generating this wiki page:
- [drizzle-orm/src/netlify-db/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/netlify-db/session.ts)
- [drizzle-orm/src/neon-http/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-http/session.ts)
- [drizzle-orm/src/xata-http/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/xata-http/session.ts)
- [drizzle-orm/src/neon-serverless/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-serverless/session.ts)
- [drizzle-kit/src/cli/connections.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/cli/connections.ts)
- [drizzle-orm/src/tidb-serverless/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tidb-serverless/session.ts)
- [drizzle-orm/src/neon-http/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-http/driver.ts)
- [drizzle-orm/src/vercel-postgres/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/vercel-postgres/session.ts)
- [drizzle-orm/src/xata-http/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/xata-http/driver.ts)
- [drizzle-orm/src/singlestore/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore/session.ts)
- [drizzle-orm/src/pg-proxy/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-proxy/session.ts)
- [drizzle-orm/src/planetscale-serverless/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/planetscale-serverless/session.ts)
- [drizzle-orm/src/aws-data-api/pg/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/aws-data-api/pg/session.ts)
- [drizzle-orm/src/netlify-db/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/netlify-db/driver.ts)
- [drizzle-orm/src/node-postgres/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/node-postgres/session.ts)
- [drizzle-orm/src/postgres-js/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/postgres-js/session.ts)
- [drizzle-orm/src/neon-serverless/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-serverless/driver.ts)
- [drizzle-orm/src/sqlite-proxy/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-proxy/session.ts)
- [drizzle-orm/src/pglite/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pglite/session.ts)
- [drizzle-orm/src/singlestore-proxy/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-proxy/session.ts)
- [drizzle-orm/src/aws-data-api/pg/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/aws-data-api/pg/driver.ts)
- [drizzle-orm/src/libsql/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/session.ts)
- [drizzle-orm/src/pg-core/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-core/session.ts)
- [drizzle-orm/src/durable-sqlite/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/durable-sqlite/session.ts)
- [drizzle-orm/src/neon-serverless/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-serverless/index.ts)
- [drizzle-orm/src/planetscale-serverless/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/planetscale-serverless/index.ts)
- [drizzle-orm/src/neon-http/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-http/index.ts)
- [drizzle-orm/src/aws-data-api/pg/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/aws-data-api/pg/index.ts)
- [drizzle-orm/src/xata-http/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/xata-http/index.ts)
- [drizzle-orm/src/tidb-serverless/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tidb-serverless/index.ts)
## Overview
The Drizzle ORM driver and runtime subsystem abstracts database communication across diverse connection models, ranging from traditional persistent TCP socket pools in Node.js to connectionless HTTP request-response APIs, WebSocket tunnels, cloud-managed SDK endpoints, and edge-native embedded runtimes. Drivers bridge database-specific client libraries with Drizzle's dialect query builders and session mechanics. Each driver exposes specialized initialization routines (`drizzle()`), session implementations (`PgSession`, `MySqlSession`, `SQLiteSession`), and prepared query objects that normalize parameter binding, row mapping, and caching strategies.
Different execution environments impose strict architectural constraints. Serverless functions and edge workers cannot maintain long-lived TCP connections without exhausting connection limits or failing due to idle timeouts. To accommodate this, Drizzle integrates with stateless HTTP drivers such as Neon HTTP, Xata HTTP, and AWS Data API, which submit individual queries over HTTP POST requests. Conversely, environments requiring transactional semantics or stateful protocols rely on WebSocket-tunneled pool clients (like Neon Serverless and Netlify DB) or native driver pools (`node-postgres`, `postgres-js`, `mysql2`). By decoupling query generation from driver execution through abstract session classes, Drizzle provides a unified API surface regardless of whether queries execute against local embedded files, remote serverless REST endpoints, or proxied worker channels.
Sources: [drizzle-orm/src/neon-http/session.ts:1-14](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-http/session.ts#L1-L14), [drizzle-orm/src/postgres-js/session.ts:1-15](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/postgres-js/session.ts#L1-L15), [drizzle-orm/src/aws-data-api/pg/driver.ts:1-20](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/aws-data-api/pg/driver.ts#L1-L20)
## Custom Proxy Drivers
Custom proxy drivers route database execution through user-supplied callback functions rather than managing direct network sockets. This architecture is heavily utilized in edge environments, testing frameworks, and migration tools where query execution must be intercepted, logged, or forwarded to a remote worker bridge. The proxy subsystem implements separate adapters for PostgreSQL (`PgRemoteSession`), MySQL/SingleStore (`SingleStoreRemoteSession`), and SQLite (`SQLiteRemoteSession`), translating Drizzle's prepared query executions into generic callback invocations.
Sources: [drizzle-orm/src/pg-proxy/session.ts:16-41](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-proxy/session.ts#L16-L41)
When a query executes under a proxy session, the framework bypasses native database drivers and invokes a remote callback function with the compiled SQL string, parameter values, execution method, and optional type hints. For instance, the PostgreSQL proxy prepared query evaluates placeholder values via `fillPlaceholders()`, logs the statement, and invokes the client callback with `'execute'` or `'all'` modes.
Sources: [drizzle-orm/src/pg-proxy/session.ts:91-129](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-proxy/session.ts#L91-L129)
```typescript
// Example usage of a PostgreSQL proxy driver initialization
import { drizzle } from 'drizzle-orm/pg-proxy';
const db = drizzle(async (sql, params, method, typings) => {
const res = await fetch('https://api.database.proxy/query', {
method: 'POST',
body: JSON.stringify({ sql, params, method, typings }),
});
return { rows: await res.json() };
});
```
Sources: [drizzle-orm/src/pg-proxy/session.ts:95-154](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-proxy/session.ts#L95-L154)
Because stateless proxies do not maintain persistent socket state, multi-statement transactions are fundamentally unsupported. Attempting to initiate a transaction on a proxy session immediately throws an explicit error indicating that transactions are unavailable for the proxy driver.
Sources: [drizzle-orm/src/pg-proxy/session.ts:70-76](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pg-proxy/session.ts#L70-L76), [drizzle-orm/src/singlestore-proxy/session.ts:72-78](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore-proxy/session.ts#L72-L78)
## MySQL and Serverless Drivers
MySQL and serverless MySQL runtimes are powered by drivers such as PlanetScale Serverless and TiDB Cloud Serverless. These drivers operate over HTTP or fetch-based APIs, delivering connectionless execution ideal for serverless and edge environments. The session implementations (`PlanetscaleSession` and `TiDBServerlessSession`) extend `MySqlSession` and coordinate query preparation via `PlanetScalePreparedQuery` and `TiDBServerlessPreparedQuery`.
Sources: [drizzle-orm/src/planetscale-serverless/session.ts:22-48](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/planetscale-serverless/session.ts#L22-L48), [drizzle-orm/src/tidb-serverless/session.ts:26-48](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tidb-serverless/session.ts#L26-L48)
Unlike traditional MySQL drivers that rely on persistent TCP connections, serverless MySQL clients accept an HTTP client or connection handle and execute queries via stateless request methods. For instance, `PlanetScalePreparedQuery` utilizes an execution configuration object (`{ as: 'object' }` or `{ as: 'array' }`) to dictate row formatting. When executing write queries without custom result mappers, the driver calculates affected rows and insert IDs, handling synthetic returning clauses for auto-incrementing primary keys or generated identifiers.
Sources: [drizzle-orm/src/planetscale-serverless/session.ts:49-96](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/planetscale-serverless/session.ts#L49-L96), [drizzle-orm/src/tidb-serverless/session.ts:50-86](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tidb-serverless/session.ts#L50-L86)
```mermaid
flowchart TD
A["Query Builder"] --> B["PlanetScalePreparedQuery.execute()"]
B --> C{"Fields or Custom Mapper?"}
C -- "No" --> D["client.execute(sql, params, { as: 'object' })"]
C -- "Yes" --> E["client.execute(sql, params, { as: 'array' })"]
E --> F["mapResultRow()"]
```
Sources: [drizzle-orm/src/planetscale-serverless/session.ts:49-106](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/planetscale-serverless/session.ts#L49-L106)
> [!NOTE]
> Streaming and database-level iterators are explicitly disabled in serverless MySQL drivers. Calling `.iterator()` on a `PlanetScalePreparedQuery` or `TiDBServerlessPreparedQuery` throws an error because HTTP request-response cycles cannot maintain open streams.
Sources: [drizzle-orm/src/planetscale-serverless/session.ts:108-111](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/planetscale-serverless/session.ts#L108-L111), [drizzle-orm/src/tidb-serverless/session.ts:99-102](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/tidb-serverless/session.ts#L99-L102)
## Node.js PostgreSQL Drivers
Node.js PostgreSQL runtimes rely on persistent TCP socket drivers, specifically `node-postgres` (`pg`) and `postgres-js` (`postgres`). These drivers manage connection pools (`Pool`), individual client connections (`Client`), and transaction blocks. Drizzle implements `NodePgSession` and `PostgresJsSession` to bridge these native clients with PostgreSQL query generation.
Sources: [drizzle-orm/src/node-postgres/session.ts:19-43](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/node-postgres/session.ts#L19-L43), [drizzle-orm/src/postgres-js/session.ts:17-36](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/postgres-js/session.ts#L17-L36)
Both sessions configure custom type parsers during initialization to prevent automatic transformation of date, timestamp, timestamptz, interval, and array types into JavaScript `Date` objects unless desired. This preserves raw string representations for high-precision decimal and timestamp handling. Transaction management in `PostgresJsSession` leverages the native `.begin()` callback wrapper provided by `postgres-js`, automatically provisioning a transaction-scoped client instance and applying transaction configuration parameters via `.setTransaction(config)`.
Sources: [drizzle-orm/src/node-postgres/session.ts:44-131](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/node-postgres/session.ts#L44-L131), [drizzle-orm/src/postgres-js/session.ts:167-184](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/postgres-js/session.ts#L167-L184)
```typescript
// Initializing Drizzle with postgres-js in Node.js
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
const queryClient = postgres('postgres://user:pass@localhost:5432/db');
const db = drizzle(queryClient);
```
Sources: [drizzle-kit/src/cli/connections.ts:274-297](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/cli/connections.ts#L274-L297)
Tracing is deeply integrated into Node.js PostgreSQL sessions via OpenTelemetry spans (`tracer.startActiveSpan`). Query execution is wrapped in nested spans (`drizzle.execute`, `drizzle.driver.execute`, and `drizzle.mapResponse`), capturing query text, parameters, and execution duration as span attributes.
Sources: [drizzle-orm/src/node-postgres/session.ts:133-171](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/node-postgres/session.ts#L133-L171), [drizzle-orm/src/postgres-js/session.ts:38-74](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/postgres-js/session.ts#L38-L74)
## Serverless PostgreSQL Drivers
Serverless PostgreSQL drivers provide connectionless execution models tailored for edge runtimes, serverless functions, and managed cloud platforms. This group includes Neon HTTP (`NeonHttpSession`), Xata HTTP (`XataHttpSession`), AWS Data API (`AwsDataApiSession`), Neon Serverless (`NeonSession`), Vercel Postgres (`VercelPgSession`), and Netlify DB (`NetlifyDbSession`).
Sources: [drizzle-orm/src/neon-http/session.ts:149-173](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-http/session.ts#L149-L173), [drizzle-orm/src/xata-http/session.ts:98-120](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/xata-http/session.ts#L98-L120), [drizzle-orm/src/aws-data-api/pg/session.ts:165-191](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/aws-data-api/pg/session.ts#L165-L191)
HTTP-based drivers (Neon HTTP, Xata HTTP) submit queries as REST payloads over HTTP POST requests rather than maintaining persistent socket connections. For instance, `XataHttpSession` delegates execution to the Xata client plugin (`client.sql`), specifying response types (`array` or `json`) to govern whether rows return as tuples or objects. Neon HTTP utilizes a fetch-based query function and supports batch execution via its transaction endpoint (`client.transaction(builtQueries, queryConfig)`), enabling multiple independent queries to execute in a single round trip.
Sources: [drizzle-orm/src/neon-http/session.ts:199-220](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-http/session.ts#L199-L220), [drizzle-orm/src/xata-http/session.ts:47-91](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/xata-http/session.ts#L47-L91)
```mermaid
sequenceDiagram
participant App as Drizzle ORM
participant Session as NeonHttpSession
participant Client as Neon HTTP Client
participant DB as Neon Cloud API
App->>Session: execute() / batch()
Session->>Client: clientQuery(sql, params, opts)
Client->>DB: HTTP POST /v2/query
DB-->>Client: FullQueryResults
Client-->>Session: Result rows
Session-->>App: Mapped result entities
```
Sources: [drizzle-orm/src/neon-http/session.ts:221-235](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-http/session.ts#L221-L235), [drizzle-orm/src/netlify-db/session.ts:130-142](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/netlify-db/session.ts#L130-L142)
AWS Data API (`AwsDataApiSession`) interacts with Amazon RDS databases through the AWS SDK (`RDSDataClient`). It translates Drizzle parameter bindings into named parameters (`:1`, `:2`) via `AwsPgDialect.escapeParam()` and converts column metadata into structured row objects when result headers are present.
Sources: [drizzle-orm/src/aws-data-api/pg/driver.ts:50-56](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/aws-data-api/pg/driver.ts#L50-L56), [drizzle-orm/src/aws-data-api/pg/session.ts:30-65](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/aws-data-api/pg/session.ts#L30-L65)
> [!WARNING]
> HTTP-based drivers such as Neon HTTP and Xata HTTP do not support traditional SQL transactions (`BEGIN`/`COMMIT`/`ROLLBACK`) across separate HTTP requests. Calling `.transaction()` on these sessions throws an explicit error, except where WebSocket fallback connections are explicitly provisioned (such as Netlify DB's hybrid pool).
Sources: [drizzle-orm/src/neon-http/session.ts:248-255](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-http/session.ts#L248-L255), [drizzle-orm/src/xata-http/session.ts:167-174](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/xata-http/session.ts#L167-L174), [drizzle-orm/src/netlify-db/session.ts:151-179](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/netlify-db/session.ts#L151-L179)
## SingleStore and Gel Drivers
SingleStore and Gel drivers manage relational connectivity for high-performance distributed analytics and advanced graph-relational runtimes. SingleStore driver sessions (`SingleStoreDriverSession`) integrate with the `mysql2` promise client, managing connection pools and standalone connections.
Sources: [drizzle-orm/src/singlestore/session.ts:202-220](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore/session.ts#L202-L220)
During query execution, `SingleStoreDriverSession` overrides the default `query()` method to configure custom type casting, ensuring `TIMESTAMP`, `DATETIME`, and `DATE` fields return as raw strings:
Sources: [drizzle-orm/src/singlestore/session.ts:251-270](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore/session.ts#L251-L270)
```typescript
const result = await this.client.query({
sql: query,
values: params,
rowsAsArray: true,
typeCast: function(field: any, next: any) {
if (field.type === 'TIMESTAMP' || field.type === 'DATETIME' || field.type === 'DATE') {
return field.string();
}
return next();
},
});
```
Sources: [drizzle-orm/src/singlestore/session.ts:255-269](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore/session.ts#L255-L269)
Transactions in SingleStore check whether the underlying client is a connection pool (`isPool()`). If so, a dedicated `PoolConnection` is acquired via `client.getConnection()`, configured with isolation levels or start transaction statements, and released in a `finally` block once execution completes or rolls back. Nested transactions utilize SQL savepoints (`savepoint sp1`, `rollback to savepoint sp1`).
Sources: [drizzle-orm/src/singlestore/session.ts:277-350](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore/session.ts#L277-L350), [drizzle-kit/src/cli/connections.ts:536-545](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/cli/connections.ts#L536-L545)
## SQLite File and LibSQL Drivers
SQLite file and edge runtimes are handled by specialized drivers including LibSQL (`libsql`), Cloudflare Durable Objects (`durable-sqlite`), and PGlite. These drivers support embedded storage engines, local WebAssembly runtimes, and distributed SQLite services like Turso.
`SQLiteDOSession` integrates with Cloudflare Durable Object storage (`DurableObjectStorage`), executing synchronous SQLite queries against `storage.sql`. Because Durable Object storage operates synchronously within isolate execution, queries are executed via `.exec()` and results are converted using `.toArray()` or iterator advancement (`.next().value`). Similarly, LibSQL sessions (`LibSQLSession`) manage asynchronous remote and embedded connections using `@libsql/client`, normalizing row data structures and handling `ArrayBuffer`-to-`Buffer` or `TextDecoder` conversions for binary blob fields.
Sources: [drizzle-orm/src/durable-sqlite/session.ts:23-72](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/durable-sqlite/session.ts#L23-L72), [drizzle-orm/src/libsql/session.ts:145-201](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/session.ts#L145-L201), [drizzle-orm/src/pglite/session.ts:123-195](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pglite/session.ts#L123-L195)
## Related
- [Dialects And Schema Query Builders](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/dialects-and-schema/dialects-and-schema-query-builders)
- [Edge and Mobile SQLite](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/drivers-and-runtimes/edge-and-mobile-sqlite)
- [Sessions and Transactions](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/core-architecture/sessions-and-transactions)
---
## Technical docs: Edge and Mobile SQLite
URL: https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/drivers-and-runtimes/edge-and-mobile-sqlite
Relevant source files
The following files were used as context for generating this wiki page:
- [drizzle-orm/src/durable-sqlite/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/durable-sqlite/driver.ts)
- [drizzle-orm/src/durable-sqlite/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/durable-sqlite/index.ts)
- [drizzle-orm/src/d1/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/d1/driver.ts)
- [drizzle-orm/src/sql-js/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql-js/driver.ts)
- [drizzle-orm/src/expo-sqlite/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/expo-sqlite/driver.ts)
- [drizzle-orm/src/libsql/wasm/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/wasm/index.ts)
- [drizzle-orm/src/prisma/sqlite/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/prisma/sqlite/driver.ts)
- [drizzle-orm/src/sqlite-proxy/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-proxy/driver.ts)
- [drizzle-orm/src/libsql/sqlite3/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/sqlite3/index.ts)
- [drizzle-orm/src/op-sqlite/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/op-sqlite/driver.ts)
- [drizzle-orm/src/pglite/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/pglite/driver.ts)
- [drizzle-kit/src/cli/connections.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/cli/connections.ts)
- [drizzle-orm/src/libsql/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/driver.ts)
- [drizzle-orm/src/libsql/node/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/node/index.ts)
- [drizzle-orm/src/bun-sqlite/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/bun-sqlite/driver.ts)
- [drizzle-orm/src/libsql/ws/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/ws/index.ts)
- [drizzle-orm/src/d1/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/d1/session.ts)
- [drizzle-orm/src/durable-sqlite/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/durable-sqlite/session.ts)
- [drizzle-orm/src/neon-serverless/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/neon-serverless/driver.ts)
- [drizzle-orm/src/vercel-postgres/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/vercel-postgres/driver.ts)
- [drizzle-orm/src/sql-js/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql-js/session.ts)
- [drizzle-orm/src/libsql/web/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/web/index.ts)
- [drizzle-orm/src/prisma/sqlite/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/prisma/sqlite/index.ts)
- [drizzle-orm/src/libsql/http/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/libsql/http/index.ts)
- [drizzle-orm/src/planetscale-serverless/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/planetscale-serverless/driver.ts)
- [drizzle-orm/type-tests/sqlite/db.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/type-tests/sqlite/db.ts)
- [drizzle-orm/src/expo-sqlite/index.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/expo-sqlite/index.ts)
- [drizzle-orm/src/better-sqlite3/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/better-sqlite3/driver.ts)
- [drizzle-orm/src/singlestore/driver.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/singlestore/driver.ts)
- [drizzle-orm/src/sqlite-core/session.ts](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-core/session.ts)
## Overview
Drizzle ORM provides dedicated driver integrations and session handlers for running SQLite databases across edge runtimes, serverless workers, WebAssembly environments, and native mobile applications. These drivers bridge Drizzle's synchronous and asynchronous query dialects with target environments such as Cloudflare D1, Cloudflare Durable Objects storage, Expo SQLite for React Native, OP-SQLite bindings, `sql.js` WebAssembly instances, and remote RPC sqlite-proxy endpoints. Each driver configures customized statement preparation, batch execution, and transaction lifecycle management tailored to the constraints and performance characteristics of its underlying runtime.
Sources: [drizzle-orm/src/durable-sqlite/driver.ts:1-60](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/durable-sqlite/driver.ts#L1-L60), [drizzle-orm/src/d1/driver.ts:1-78](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/d1/driver.ts#L1-L78), [drizzle-orm/src/sql-js/driver.ts:1-45](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql-js/driver.ts#L1-L45), [drizzle-orm/src/expo-sqlite/driver.ts:1-53](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/expo-sqlite/driver.ts#L1-L53), [drizzle-orm/src/sqlite-proxy/driver.ts:1-100](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sqlite-proxy/driver.ts#L1-L100), [drizzle-orm/src/op-sqlite/driver.ts:1-57](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/op-sqlite/driver.ts#L1-L57), [drizzle-orm/src/d1/session.ts:30-126](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/d1/session.ts#L30-L126), [drizzle-orm/src/durable-sqlite/session.ts:23-72](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/durable-sqlite/session.ts#L23-L72), [drizzle-orm/src/sql-js/session.ts:24-66](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/sql-js/session.ts#L24-L66)
## Cloudflare D1 Driver Architecture
### Driver Initialization and Client Configuration
The Cloudflare D1 integration initializes through the `drizzle()` entrypoint function which accepts a D1 database client (`AnyD1Database`, supporting both official `@cloudflare/workers-types` and Miniflare D1 bindings) and an optional `DrizzleConfig` parameter. It configures an asynchronous SQLite dialect (`SQLiteAsyncDialect`) utilizing the specified casing configuration, instantiates a logger (defaulting to `DefaultLogger` when `config.logger` is `true`), and extracts relational schema configurations if provided via `config.schema`.
```typescript
export function drizzle<
TSchema extends Record = Record,
TClient extends AnyD1Database = AnyD1Database,
>(
client: TClient,
config: DrizzleConfig = {},
): DrizzleD1Database & {
$client: TClient;
} {
const dialect = new SQLiteAsyncDialect({ casing: config.casing });
let logger;
if (config.logger === true) {
logger = new DefaultLogger();
} else if (config.logger !== false) {
logger = config.logger;
}
let schema: RelationalSchemaConfig | undefined;
if (config.schema) {
const tablesConfig = extractTablesRelationalConfig(
config.schema,
createTableRelationsHelpers,
);
schema = {
fullSchema: config.schema,
schema: tablesConfig.tables,
tableNamesMap: tablesConfig.tableNamesMap,
};
}
const session = new SQLiteD1Session(client as D1Database, dialect, schema, { logger, cache: config.cache });
const db = new DrizzleD1Database('async', dialect, session, schema) as DrizzleD1Database;
( db).$client = client;
( db).$cache = config.cache;
if (( db).$cache) {
( db).$cache['invalidate'] = config.cache?.onMutate;
}
return db as any;
}
```
Sources: [drizzle-orm/src/d1/driver.ts:39-78](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/d1/driver.ts#L39-L78)
The initialization function wires up `SQLiteD1Session` with the client, dialect, schema, and operational options including caching. It then constructs a `DrizzleD1Database` instance, attaches the raw client as `$client`, and exposes cache invalidation handlers on `$cache` when present.
```typescript
const session = new SQLiteD1Session(client as D1Database, dialect, schema, { logger, cache: config.cache });
const db = new DrizzleD1Database('async', dialect, session, schema) as DrizzleD1Database;
( db).$client = client;
( db).$cache = config.cache;
if (( db).$cache) {
( db).$cache['invalidate'] = config.cache?.onMutate;
}
```
Sources: [drizzle-orm/src/d1/driver.ts:69-76](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/d1/driver.ts#L69-L76)
### Async Dialect Integration and Session Management
`SQLiteD1Session` extends `SQLiteSession` with an `'async'` execution mode and handles query preparation by invoking `client.prepare(query.sql)` on the underlying D1 database handle. Prepared statements are wrapped in `D1PreparedQuery` instances that manage parameter binding, query logging, caching execution, and result mapping.
```typescript
prepareQuery(
query: Query,
fields: SelectedFieldsOrdered | undefined,
executeMethod: SQLiteExecuteMethod,
isResponseInArrayMode: boolean,
customResultMapper?: (rows: unknown[][]) => unknown,
queryMetadata?: {
type: 'select' | 'update' | 'delete' | 'insert';
tables: string[];
},
cacheConfig?: WithCacheConfig,
): D1PreparedQuery {
const stmt = this.client.prepare(query.sql);
return new D1PreparedQuery(
stmt,
query,
this.logger,
this.cache,
queryMetadata,
cacheConfig,
fields,
executeMethod,
isResponseInArrayMode,
customResultMapper,
);
}
```
Sources: [drizzle-orm/src/d1/session.ts:50-75](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/d1/session.ts#L50-L75)
Batch operations executed through `session.batch()` iterate over batch items, extract underlying prepared queries, bind parameters when present, or prepare fresh SQL statements if parameters are absent, before dispatching them concurrently via `client.batch()`.
```typescript
async batch[] | readonly BatchItem<'sqlite'>[]>(queries: T) {
const preparedQueries: PreparedQuery[] = [];
const builtQueries: D1PreparedStatement[] = [];
for (const query of queries) {
const preparedQuery = query._prepare();
const builtQuery = preparedQuery.getQuery();
preparedQueries.push(preparedQuery);
if (builtQuery.params.length > 0) {
builtQueries.push((preparedQuery as D1PreparedQuery).stmt.bind(...builtQuery.params));
} else {
const builtQuery = preparedQuery.getQuery();
builtQueries.push(
this.client.prepare(builtQuery.sql).bind(...builtQuery.params),
);
}
}
const batchResults = await this.client.batch(builtQueries);
return batchResults.map((result, i) => preparedQueries[i]!.mapResult(result, true));
}
```
Sources: [drizzle-orm/src/d1/session.ts:77-97](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/d1/session.ts#L77-L97)
### Transaction Lifecycle and Statement Execution
Transactions are managed explicitly via SQL commands issued against the session. The `transaction()` method initiates a block by executing `begin` with optional behavior configuration, runs the transaction callback with a `D1Transaction` instance, commits on success, or rolls back upon catching any error.
```typescript
override async transaction(
transaction: (tx: D1Transaction) => T | Promise,
config?: SQLiteTransactionConfig,
): Promise {
const tx = new D1Transaction('async', this.dialect, this, this.schema);
await this.run(sql.raw(`begin${config?.behavior ? ' ' + config.behavior : ''}`));
try {
const result = await transaction(tx);
await this.run(sql`commit`);
return result;
} catch (err) {
await this.run(sql`rollback`);
throw err;
}
}
```
Sources: [drizzle-orm/src/d1/session.ts:111-125](https://github.com/blade47/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-orm/src/d1/session.ts#L111-L125)
Nested transactions within `D1Transaction` rely on SQLite savepoints. Each nested level generates a unique savepoint name using its `nestedIndex`, executing `savepoint spN`, releasing it upon completion, or rolling back to the savepoint on failure.
```typescript
override async transaction