by Opal W.

Drizzle is a lightweight, serverless-ready TypeScript ORM supporting PostgreSQL, MySQL, and SQLite with type-safe query building, automatic migrations, schema validation plugins, and a rich tooling ecosystem.
This block provides the full Drizzle ORM TypeScript source, a lightweight (~7.4kb minified+gzipped) headless ORM that targets PostgreSQL, MySQL, and SQLite including serverless runtimes. It exposes a SQL-like query builder and relational query API with strict TypeScript types. The typical buyer is a Node.js or edge-runtime backend developer who wants type-safe database access without a heavy runtime dependency.
index.ts - Main barrel export; re-exports all core symbolsalias.ts - Table and column aliasing utilitiescolumn-builder.ts - Base ColumnBuilder class for schema definitioncolumn.ts - Base Column class and column metadata typesentity.ts - Internal entity tagging helpers used across the ORMerrors.ts - Typed error classes thrown by the ORMlogger.ts - Logger interface and DefaultLogger implementationoperations.ts - DML operation helpers (insert, update, delete primitives)query-promise.ts - QueryPromise base class wrapping async query executionrelations.ts - relations(), one(), many() for relational query buildersql/ - Core sql template tag, SQL type, type hints, and operatorssubquery.ts - Subquery class for composing nested selectstable.ts - Base Table class and getTableName / getTableColumns utilsutils.ts - General-purpose internal utility functionsview-common.ts - Shared view definition helperspg-core/ - PostgreSQL schema builder and query layermysql-core/ - MySQL schema builder and query layersqlite-core/ - SQLite schema builder and query layeraws-data-api/ - AWS RDS Data API adapter (PostgreSQL)better-sqlite3/ - better-sqlite3 driver adapterbun-sql/ - Bun SQL driver adapterbun-sqlite/ - Bun SQLite driver adapterSpin up an isolated sandbox and run it server-side — no local setup.
Tetrees AI Review of this version
This Express backend / api completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Pipeline avcp-2026-08-04.1 · SHA-256 27c39d97b33c17db…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Reviewed Aug 4, 2026
Push this product straight into your AI IDE, web builder or cloud IDE.
Connect Tetrees to a compatible AI IDE, list products you own, and request the verified ZIP without exposing seller upload controls.
No reviews yet.
Sign in to join the discussion
Loading discussion…
neon-http/ - Neon serverless HTTP driver adapternode-postgres/ - node-postgres (pg) driver adapterpostgres-js/ - postgres.js driver adapterlibsql/ - LibSQL / Turso driver adapterd1/ - Cloudflare D1 driver adapterrelations.ts - Relational query builder relation declarationscasing.ts - Column casing strategy helpers (camelCase / snake_case)migrator.ts - Base migration runner interfacesession.ts - Abstract Session and Transaction base classestracing.ts / tracing-utils.ts - OpenTelemetry tracing integrationcache/ - Query result caching layerbatch.ts - Batch query execution support# Core (always required)
npm install drizzle-orm
# Choose ONE driver adapter based on your database:
# PostgreSQL – node-postgres
npm install pg
npm install --save-dev @types/pg
# PostgreSQL – postgres.js
npm install postgres
# PostgreSQL – Neon serverless
npm install @neondatabase/serverless
# MySQL – mysql2
npm install mysql2
# SQLite – better-sqlite3
npm install better-sqlite3
npm install --save-dev @types/better-sqlite3
# SQLite – Bun built-in (no extra install)
# AWS RDS Data API
npm install @aws-sdk/client-rds-data
# Migrations (CLI companion, dev only)
npm install --save-dev drizzle-kit
No native build steps, pod installs, or Android linking are required for server-side Node.js use. Expo SQLite (expo-sqlite/) requires npx expo prebuild and a managed/bare Expo project.
Drop the source. Copy the source/ directory into your project, e.g. src/drizzle-orm/.
Configure tsconfig.json paths so imports resolve cleanly:
{
"compilerOptions": {
"strict": true,
"moduleResolution": "bundler",
"paths": {
"~/sql/sql.ts": ["./src/drizzle-orm/sql/sql.ts"],
"~/*": ["./src/drizzle-orm/*"]
}
}
}
Choose a driver and import from its subdirectory (e.g. src/drizzle-orm/node-postgres).
Environment variables (driver-specific, not ORM-specific):
DATABASE_URL – standard connection string consumed by your driver of choice.AWS_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY – required for aws-data-api/pg.Optional: enable logging by passing a logger option to drizzle():
import { DefaultLogger } from './src/drizzle-orm/logger';
// pass { logger: new DefaultLogger() } to drizzle(driver, { logger })
sql (template tag)import { sql } from 'drizzle-orm'; // or from './source/sql/index.ts'
const fragment: SQL = sql`SELECT * FROM ${usersTable} WHERE id = ${userId}`;
The sql tagged template literal builds a parameterized SQL object. Use it wherever you need raw SQL fragments inside query builders, default column values, or where conditions that exceed the query builder's helpers.
relationsimport { relations } from 'drizzle-orm';
const userRelations = relations(users, ({ one, many }) => ({
profile: one(profiles, { fields: [users.id], references: [profiles.userId] }),
posts: many(posts),
}));
Declares relational metadata consumed by Drizzle's Relational Query Builder (db.query.*). Call it once per table, alongside the table definition. Required when using findFirst / findMany with with: includes.
getValueFromDataApiimport { getValueFromDataApi } from './source/aws-data-api/common/index.ts';
import type { Field } from '@aws-sdk/client-rds-data';
const jsValue = getValueFromDataApi(field as Field);
Converts a single AWS RDS Data API Field union type into a plain JavaScript value. Used internally by the aws-data-api/pg session, but exposed for custom result-set processors that work directly with the AWS SDK response.
typingsToAwsTypeHintimport { typingsToAwsTypeHint } from './source/aws-data-api/common/index.ts';
import type { QueryTypingsValue } from './source/sql/sql.ts';
const hint = typingsToAwsTypeHint('uuid'); // TypeHint.UUID
Maps Drizzle's internal QueryTypingsValue strings ('date', 'uuid', 'json', etc.) to the AWS TypeHint enum required when sending parameters to the RDS Data API. Use it when building a custom RDS Data API adapter or middleware layer.
Declare a typed table, run a select, and use sql for a raw fragment.
import { drizzle } from 'drizzle-orm/node-postgres';
import { pgTable, serial, text, varchar } from 'drizzle-orm/pg-core';
import { sql, eq } from 'drizzle-orm';
import { Pool } from 'pg';
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const db = drizzle(pool);
const users = pgTable('users', {
id: serial('id').primaryKey(),
name: varchar('name', { length: 100 }).notNull(),
email: text('email').notNull(),
});
// Typed select
const allUsers = await db.select().from(users);
// Raw SQL fragment
const count = await db.execute(sql`SELECT COUNT(*) FROM ${users}`);
// Filtered select
const user = await db.select().from(users).where(eq(users.id, 1));
Use relations to declare associations and db.query to fetch nested data.
import { drizzle } from 'drizzle-orm/node-postgres';
import { pgTable, serial, text, integer } from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
import { Pool } from 'pg';
const users = pgTable('users', {
id: serial('id').primaryKey(),
name: text('name').notNull(),
});
const posts = pgTable('posts', {
id: serial('id').primaryKey(),
title: text('title').notNull(),
authorId: integer('author_id').notNull(),
});
const userRelations = relations(users, ({ many }) => ({
posts: many(posts),
}));
const postRelations = relations(posts, ({ one }) => ({
author: one(users, { fields: [posts.authorId], references: [users.id] }),
}));
const db = drizzle(new Pool({ connectionString: process.env.DATABASE_URL }), {
schema: { users, posts, userRelations, postRelations },
});
const result = await db.query.users.findMany({
with: { posts: true },
});
Process a raw AWS RDS Data API response using the exposed helpers.
import { getValueFromDataApi, typingsToAwsTypeHint, toValueParam } from './source/aws-data-api/common/index.ts';
import { RDSDataClient, ExecuteStatementCommand } from '@aws-sdk/client-rds-data';
const client = new RDSDataClient({ region: 'us-east-1' });
const response = await client.send(new ExecuteStatementCommand({
resourceArn: process.env.DB_ARN!,
secretArn: process.env.DB_SECRET!,
database: 'mydb',
sql: 'SELECT id, created_at FROM events WHERE id = :id',
parameters: [
toValueParam('550e8400-e29b-41d4-a716-446655440000', 'uuid').value
? { name: 'id', ...toValueParam('550e8400-e29b-41d4-a716-446655440000', 'uuid') }
: { name: 'id', value: { stringValue: '550e8400-e29b-41d4-a716-446655440000' } },
],
}));
const rows = response.records?.map(row => row.map(getValueFromDataApi));
console.log(rows);
index.ts - Barrel that re-exports every public symbol from the core modules.alias.ts - Implements aliasedTable() for giving tables query-scoped aliases.column-builder.ts - Abstract ColumnBuilder wired into the schema DSL chain.column.ts - Runtime Column class carrying type metadata and constraints.entity.ts - Lightweight brand-tagging so the ORM can identify its own objects at runtime.errors.ts - DrizzleError and related typed exceptions.logger.ts - Logger interface plus DefaultLogger that writes to console.operations.ts - Internal helpers for constructing INSERT / UPDATE / DELETE AST nodes.query-promise.ts - QueryPromise<T> base class making queries thenable and composable.relations.ts - relations(), one(), many() for Relational Query Builder declarations.sql/ - The sql tag, SQL AST node, Placeholder, operators, and type-hint constants.subquery.ts - Subquery wrapper enabling nested selects in from/join clauses.table.ts - Table base class, getTableName, getTableColumns inspection helpers.utils.ts - Internal helpers: mapValues, chunk, iife, etc.view-common.ts - Shared types for materialized and non-materialized view definitions.casing.ts - CasingCache and strategy objects for camelCase / snake_case mapping.session.ts - Abstract Session and Transaction that all drivers implement.migrator.ts - MigrationMeta type and base migration runner contract.tracing.ts / tracing-utils.ts - Optional OpenTelemetry span wrapping for queries.batch.ts - BatchItem type and batch execution helpers for supported drivers.cache/ - Pluggable query-result cache layer with TTL support.pg-core/ - Full PostgreSQL DDL types: pgTable, column builders, indexes, enums.mysql-core/ - MySQL DDL types: mysqlTable, column builders, indexes.sqlite-core/ - SQLite DDL types: sqliteTable, column builders.aws-data-api/ - RDS Data API field conversion utilities and PostgreSQL session adapter.better-sqlite3/ - Synchronous better-sqlite3 driver integration.bun-sql/ - Bun native SQL driver integration.neon-http/ - Neon serverless HTTP transport adapter.node-postgres/ - pg Pool/Client driver integration.libsql/ - LibSQL (Turso) driver integration.d1/ - Cloudflare D1 binding adapter.moduleResolution must be bundler or node16 - path aliases with .ts extensions in imports fail under classic node resolution; set "moduleResolution": "bundler" in tsconfig.json.~/* path alias not resolved - The source uses ~/ as an alias for the source root; configure paths in tsconfig.json and mirror them in your bundler (Vite: resolve.alias, webpack: alias).drizzle-orm package ships dual ESM/CJS; if you copy source directly, ensure your build tool handles .ts re-exports and does not mix module formats.@aws-sdk/client-rds-data version pin - getValueFromDataApi depends on the Field union shape; pin to ^3.0.0 to avoid breaking field-type changes.relations not passed to drizzle() - Relational queries (db.query.*) silently return nothing if schema (including relation objects) is not passed as the second argument to drizzle().async functions works, but do not await an already-resolved value expecting lazy execution.I have the Drizzle ORM TypeScript source at `source/` in my project root,
and a usage guide at `USAGE.md`. The upstream package is `drizzle-orm`.
My project is a Node.js TypeScript Express API using [DESCRIBE YOUR DATABASE: e.g. PostgreSQL via node-postgres].
Please help me integrate Drizzle ORM step by step:
1. Read `USAGE.md` and `source/index.ts` to understand the public API.
2. Create a `src/db/schema.ts` file defining my tables: [LIST YOUR TABLES AND COLUMNS].
3. Create a `src/db/index.ts` that initializes the drizzle client using the appropriate driver from `source/`.
4. Add a `DATABASE_URL` environment variable and show how to load it.
5. Write typed query helpers for: select all, find by id, insert, update, delete.
6. If I have relations, use `relations()` from `source/relations.ts` and wire up `db.query`.
7. Show the required `tsconfig.json` changes for path aliases.
8. Do not invent any API; use only symbols visible in `source/index.ts` and the driver subdirectories shown in `USAGE.md`.
Drizzle ORM is released under the Apache 2.0 License (see source/LICENSE if present, or the repository at https://github.com/drizzle-team/drizzle-orm). Upstream npm package: drizzle-orm. Maintained by the Drizzle Team.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
The full install guide and integration prompts unlock after purchase.
Automation, Utilities & Developer Tools
Free