npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@db4/drizzle

v0.1.2

Published

Drizzle ORM adapter for db4 document database

Readme

@db4/drizzle

npm version license TypeScript

(GitHub, npm)

Description

Drizzle ORM adapter for db4 document database. This package provides a Drizzle ORM-compatible interface that lets you use familiar Drizzle syntax for schema definition, queries, and migrations while leveraging db4's distributed Durable Object architecture under the hood.

Define your tables with type-safe column builders, query with the fluent Drizzle API, and run migrations seamlessly against your db4 database.

Installation

npm install @db4/drizzle drizzle-orm

Or with pnpm:

pnpm add @db4/drizzle drizzle-orm

Usage

import { sqliteTable, integer, text, boolean, timestamp } from '@db4/drizzle';
import { relations } from '@db4/drizzle';

// Define tables
export const users = sqliteTable('users', {
  id: integer('id').primaryKey(),
  name: text('name').notNull(),
  email: text('email').notNull().unique(),
  isActive: boolean('is_active').default(true),
  createdAt: timestamp('created_at').defaultNow(),
});

export const posts = sqliteTable('posts', {
  id: integer('id').primaryKey(),
  title: text('title').notNull(),
  content: text('content'),
  authorId: integer('author_id').references(() => users.id),
  publishedAt: timestamp('published_at'),
});

// Define relations
export const usersRelations = relations(users, ({ many }) => ({
  posts: many(posts),
}));

export const postsRelations = relations(posts, ({ one }) => ({
  author: one(users, {
    fields: [posts.authorId],
    references: [users.id],
  }),
}));

Database Connection

import { drizzle } from '@db4/drizzle';
import { createClient } from '@db4/client';

// Create db4 client
const client = createClient({
  baseUrl: 'https://my-app.db4.io',
  apiKey: 'db4_live_key_12345',
});

// Create Drizzle database instance
const db = drizzle(client);

Queries

import { eq, gt, and, or, like, desc } from '@db4/drizzle';

// Select all users
const allUsers = await db.select().from(users);

// Select with conditions
const activeUsers = await db
  .select()
  .from(users)
  .where(eq(users.isActive, true));

// Complex queries
const recentPosts = await db
  .select({
    id: posts.id,
    title: posts.title,
    authorName: users.name,
  })
  .from(posts)
  .leftJoin(users, eq(posts.authorId, users.id))
  .where(
    and(
      gt(posts.publishedAt, new Date('2024-01-01')),
      like(posts.title, '%TypeScript%')
    )
  )
  .orderBy(desc(posts.publishedAt))
  .limit(10);

// Aggregations
const postCounts = await db
  .select({
    authorId: posts.authorId,
    count: count(posts.id),
  })
  .from(posts)
  .groupBy(posts.authorId);

Inserts

import { insert } from '@db4/drizzle';

// Single insert
const newUser = await db
  .insert(users)
  .values({
    name: 'Alice',
    email: '[email protected]/api',
  })
  .returning();

// Bulk insert
await db.insert(posts).values([
  { title: 'First Post', authorId: 1 },
  { title: 'Second Post', authorId: 1 },
  { title: 'Third Post', authorId: 2 },
]);

// Insert with conflict handling
await db
  .insert(users)
  .values({ id: 1, name: 'Alice', email: '[email protected]/api' })
  .onConflictDoUpdate({
    target: users.id,
    set: { name: 'Alice Updated' },
  });

Updates and Deletes

import { update, eq, lt } from '@db4/drizzle';

// Update records
await db
  .update(users)
  .set({ isActive: false })
  .where(lt(users.lastLoginAt, new Date('2023-01-01')));

// Delete records
await db.delete(posts).where(eq(posts.authorId, 123));

Transactions

const result = await db.transaction(async (tx) => {
  const user = await tx
    .insert(users)
    .values({ name: 'Bob', email: '[email protected]/api' })
    .returning();

  await tx
    .insert(posts)
    .values({ title: 'Welcome Post', authorId: user[0].id });

  return user[0];
});

Migrations

import { MigrationRunner, generateMigrationSQL, diffSchemas } from '@db4/drizzle';

// Generate migration from schema diff
const changes = diffSchemas(oldSchema, newSchema);
const sql = generateMigrationSQL(changes);

// Run migrations
const runner = new MigrationRunner(db);
await runner.up();

// Check migration status
const status = await runner.status();
console.log('Applied:', status.applied);
console.log('Pending:', status.pending);

API

Drizzle ORM integration for db4:

function sqliteTable(name: string, columns: SchemaColumns): SQLiteTable;
function drizzle(db: DB4Database, schema: Schema): DrizzleDatabase;

Schema Functions

function sqliteTable(name: string, columns: SchemaColumns): SQLiteTable;
function integer(name: string): IntegerColumn;
function text(name: string): TextColumn;
function boolean(name: string): BooleanColumn;
function timestamp(name: string): TimestampColumn;
function blob(name: string): BlobColumn;
function real(name: string): RealColumn;
function relations(table: SQLiteTable, fn: RelationsFn): Relations;

Query Operators

| Operator | Description | |----------|-------------| | eq(col, value) | Equal | | ne(col, value) | Not equal | | gt(col, value) | Greater than | | gte(col, value) | Greater than or equal | | lt(col, value) | Less than | | lte(col, value) | Less than or equal | | like(col, pattern) | LIKE pattern match | | ilike(col, pattern) | Case-insensitive LIKE | | inArray(col, values) | IN array | | between(col, min, max) | BETWEEN range | | isNull(col) | IS NULL | | isNotNull(col) | IS NOT NULL | | and(...conditions) | AND conditions | | or(...conditions) | OR conditions | | not(condition) | NOT condition |

Aggregate Functions

function count(column?: AnyColumn): AggregateFunction;
function sum(column: AnyColumn): AggregateFunction;
function avg(column: AnyColumn): AggregateFunction;
function min(column: AnyColumn): AggregateFunction;
function max(column: AnyColumn): AggregateFunction;

Related Packages

See Also

License

MIT