Drizzle ORM — Agentuity Documentation

Drizzle ORM

Type-safe database access with Drizzle ORM

The @agentuity/drizzle package provides type-safe database access with Drizzle ORM, built on the resilient @agentuity/postgres client.

Installation

bun add @agentuity/drizzle

Basic Usage

import { createPostgresDrizzle, eq } from '@agentuity/drizzle';
import * as schema from './schema';
 
const { db, close } = createPostgresDrizzle({ schema });
 
// Type-safe queries
const activeUsers = await db
  .select()
  .from(schema.users)
  .where(eq(schema.users.active, true));
 
// Insert with returning
const [newUser] = await db
  .insert(schema.users)
  .values({ name: 'Alice', email: 'alice@example.com' })
  .returning();

Defining Your Schema

// schema.ts
import { pgTable, serial, text, boolean, timestamp } from '@agentuity/drizzle/schema';
 
export const users = pgTable('users', {
  id: serial('id').primaryKey(),
  name: text('name').notNull(),
  email: text('email').notNull().unique(),
  active: boolean('active').default(true),
  createdAt: timestamp('created_at').defaultNow(),
});

Transactions

Use Drizzle's transaction API for atomic operations:

import { eq, sql } from '@agentuity/drizzle';
 
await db.transaction(async (tx) => {
  await tx.update(schema.accounts)
    .set({ balance: sql`balance - ${100}` })
    .where(eq(schema.accounts.name, 'Alice'));
 
  await tx.update(schema.accounts)
    .set({ balance: sql`balance + ${100}` })
    .where(eq(schema.accounts.name, 'Bob'));
});

Configuration

const { db, client, close } = createPostgresDrizzle({
  schema,
  url: 'postgres://user:pass@localhost:5432/mydb',
  logger: true,
  reconnect: { maxAttempts: 5 },
  onReconnected: () => console.log('Reconnected'),
});

By default, client is a resilient PostgresPool backed by the pg driver. Set driver: 'bun-sql' only when you specifically need Bun's SQL driver.

OptionTypeDefaultDescription
schemaobject-Your Drizzle schema definition
urlstringDATABASE_URLPostgreSQL connection string
connectionStringstringDATABASE_URLPostgreSQL connection string, kept for compatibility with pg-style configuration
connectionPostgresConfig-Full @agentuity/postgres connection configuration
driver'pg' | 'bun-sql''pg'Database driver. The default uses PostgresPool
loggerbooleanfalseEnable query logging
reconnectobject-Reconnection settings (see postgres client)
onConnect() => void-Callback after the initial connection is established
onReconnected() => void-Callback when reconnection succeeds

Re-exported Utilities

Common Drizzle utilities are re-exported for convenience:

import {
  // Query operators
  eq, ne, gt, gte, lt, lte,
  and, or, not,
  isNull, isNotNull,
  inArray, notInArray,
  between, like, ilike,
 
  // Ordering
  asc, desc,
 
  // SQL helpers
  sql,
} from '@agentuity/drizzle';

Migrations

Use drizzle-kit to manage schema migrations:

bun add -D drizzle-kit
// drizzle.config.ts
import { defineConfig } from 'drizzle-kit';
 
const databaseUrl = process.env.DATABASE_URL;
if (!databaseUrl) {
  throw new Error('DATABASE_URL is required for Drizzle migrations');
}
 
export default defineConfig({
  schema: './schema.ts',
  out: './drizzle',
  dialect: 'postgresql',
  dbCredentials: {
    url: databaseUrl,
  },
});
# Generate migrations from schema changes
bunx drizzle-kit generate
 
# Apply migrations to database
bunx drizzle-kit migrate

See the Drizzle documentation for more migration options.

Auth Integration

Use with @agentuity/auth for user management:

import { createPostgresDrizzle, drizzleAdapter } from '@agentuity/drizzle';
import { createAuth } from '@agentuity/auth';
import * as schema from './schema';
 
const { db } = createPostgresDrizzle({ schema });
 
const auth = createAuth({
  database: drizzleAdapter(db, {
    provider: 'pg',
  }),
});

See Authentication for full setup.

Next Steps