Database.ts overview

The DrizzleDatabase seam: the application hands over a drizzle handle of any dialect and driver, Promise- or Effect-shaped. AuthDatabase describes only the query-builder fragment the stores use. A handle given as an Effect is resolved per query, as request-scoped pools on Workers need.

Example

import { Layer } from "effect"
import { drizzle } from "drizzle-orm/node-postgres"
import { Pool } from "pg"
import * as Drizzle from "@thomasfosterau/effect-auth-drizzle"

const db = drizzle({ client: new Pool({ connectionString: process.env["DATABASE_URL"] }) })
const stores = Drizzle.Layers.layer().pipe(Layer.provide(Drizzle.Database.databaseLayer(db)))

Example

// A handle resolved per query, from the calling request's scope.
import { Context, Effect, Layer } from "effect"
import * as Drizzle from "@thomasfosterau/effect-auth-drizzle"

const RequestDatabase = Context.Reference<PgAsyncDatabase<PgQueryResultHKT>>("app/RequestDatabase", {
  defaultValue: () => fallbackHandle
})

// Built once, for the whole isolate — it holds no connection.
const stores = Drizzle.Layers.layer().pipe(Layer.provide(Drizzle.Database.databaseLayer(RequestDatabase)))

// Per request, in that request's scope:
const handler = program.pipe(Effect.provide(Context.make(RequestDatabase, thisRequestsDb)))

Exports Grouped by Category


utils

AuthDatabase (interface)

Every drizzle database operation this package performs, in the smallest shape that describes them.

A PgAsyncDatabase, a SQLiteAsyncDatabase (sync or async), a MySqlAsyncDatabase and drizzle’s Effect databases all implement this fragment at runtime; databaseLayer and effectDatabaseLayer are what turn a concrete handle into one.

Signature

export interface AuthDatabase {
  select(): DrizzleSelectBuilder
  select<TFields extends DrizzleSelectFields>(fields: TFields): DrizzleFieldsSelectBuilder<TFields>
  insert<TTable extends Table>(table: TTable): DrizzleInsertBuilder<TTable>
  update<TTable extends Table>(table: TTable): DrizzleUpdateBuilder<TTable>
  delete(table: Table): DrizzleWhereStep
}

Source

DrizzleConflictUpdate (interface)

An INSERT ... ON CONFLICT DO UPDATE that can still name what it returns.

Signature

export interface DrizzleConflictUpdate extends DrizzleExecutable<unknown> {
  returning<TFields extends DrizzleSelectFields>(fields: TFields): DrizzleExecutable<Array<DrizzleSelected<TFields>>>
}

Source

DrizzleDatabase (class)

Tag for the drizzle database handle the stores read out of context.

Provide it with databaseLayer (Promise-shaped drivers) or effectDatabaseLayer (Effect-shaped drivers). Both accept either a handle or an Effect yielding one.

Signature

declare class DrizzleDatabase

Source

DrizzleExecutable (interface)

A drizzle query that has been fully built and can be run.

Signature

export interface DrizzleExecutable<out A> {
  execute(): DrizzleResult<A>
}

Source

DrizzleFieldsSelectBuilder (interface)

The value db.select(fields) returns.

Projecting by column rather than by table is what lets one store serve tables whose column names it does not know: the result is keyed by the store’s own field names whatever the columns are called, and typed from the columns themselves. See Columns.ts.

Signature

export interface DrizzleFieldsSelectBuilder<TFields extends DrizzleSelectFields> {
  from(table: Table): DrizzleRowSelectFrom<DrizzleSelected<TFields>>
}

Source

DrizzleHandle (interface)

How the stores get hold of a database handle.

database is run once per query rather than once per layer, so a handle that is itself request-scoped can be resolved from the calling fiber’s context. For a fixed handle it is Effect.succeed(handle) and costs nothing.

Signature

export interface DrizzleHandle {
  readonly database: Effect.Effect<AuthDatabase>
}

Source

DrizzleInsertBuilder (interface)

The value db.insert(table) returns.

Signature

export interface DrizzleInsertBuilder<TTable extends Table> {
  values(values: InferInsertModel<TTable>): DrizzleInsertValues
}

Source

DrizzleInsertValues (interface)

An INSERT ... VALUES, runnable as-is or turned into an upsert.

The upsert is the one place the dialects spell differently: PostgreSQL and SQLite have onConflictDoUpdate (with RETURNING), MySQL has onDuplicateKeyUpdate (without). Each handle carries exactly one of the two, so both are optional here and the rate-limit store picks whichever it finds.

Signature

export interface DrizzleInsertValues extends DrizzleExecutable<unknown> {
  onConflictDoUpdate?(config: { readonly target: Column; readonly set: DrizzleUpsertSet }): DrizzleConflictUpdate
  onDuplicateKeyUpdate?(config: { readonly set: DrizzleUpsertSet }): DrizzleExecutable<unknown>
}

Source

DrizzleResult (type alias)

What running a built drizzle query yields.

The classic drivers resolve a Promise; drizzle’s Effect drivers return an Effect whose error channel carries the driver’s own query error. The store layer accepts either, so a driver change never reaches the store code.

Signature

type DrizzleResult<A> = Promise<A> | Effect.Effect<A, unknown>

Source

DrizzleRowSelectFiltered (interface)

A SELECT yielding TRows, with its WHERE already applied: it can still be narrowed by limit/orderBy, or run as-is.

Signature

export interface DrizzleRowSelectFiltered<out TRow> extends DrizzleExecutable<Array<TRow>> {
  limit(limit: number): DrizzleExecutable<Array<TRow>>
  orderBy(...columns: Array<SQLWrapper>): DrizzleExecutable<Array<TRow>>
}

Source

DrizzleRowSelectFrom (interface)

A SELECT yielding TRows, before any WHERE.

Signature

export interface DrizzleRowSelectFrom<out TRow> extends DrizzleRowSelectFiltered<TRow> {
  where(where: SQL | undefined): DrizzleRowSelectFiltered<TRow>
}

Source

DrizzleRows (type alias)

The rows a SELECT * over TTable yields.

Signature

type DrizzleRows<TTable extends Table> = Array<InferSelectModel<TTable>>

Source

DrizzleSelectBuilder (interface)

The value db.select() returns.

Signature

export interface DrizzleSelectBuilder {
  from<TTable extends Table>(table: TTable): DrizzleSelectFrom<TTable>
}

Source

DrizzleSelectFields (type alias)

The columns a projected SELECT names, keyed by what the caller wants them called in the result.

Signature

type DrizzleSelectFields = Readonly<Record<string, Column>>

Source

DrizzleSelectFiltered (interface)

A SELECT * over TTable with its WHERE already applied.

Signature

export interface DrizzleSelectFiltered<TTable extends Table> extends DrizzleRowSelectFiltered<
  InferSelectModel<TTable>
> {}

Source

DrizzleSelectFrom (interface)

A SELECT * ... FROM table, before any WHERE.

Signature

export interface DrizzleSelectFrom<TTable extends Table> extends DrizzleRowSelectFrom<InferSelectModel<TTable>> {}

Source

DrizzleSelected (type alias)

The row a projected SELECT over TFields yields — drizzle’s own InferColumnsDataTypes, which reads each column’s data and nullability straight off the column object.

Signature

type DrizzleSelected<TFields extends DrizzleSelectFields> = InferColumnsDataTypes<TFields>

Source

DrizzleUpdateBuilder (interface)

The value db.update(table) returns. A column is set to a value, or to a SQL expression over the row (remaining - 1), as every dialect’s set accepts.

Signature

export interface DrizzleUpdateBuilder<TTable extends Table> {
  set(values: {
    readonly [K in keyof InferInsertModel<TTable>]?: InferInsertModel<TTable>[K] | SQL
  }): DrizzleWhereStep
}

Source

DrizzleUpsertSet (type alias)

What an upsert sets on the row it found, by column key.

Signature

type DrizzleUpsertSet = Readonly<Record<string, DrizzleUpsertValue>>

Source

DrizzleUpsertValue (type alias)

A value an upsert sets a column to: a plain value, or a SQL expression.

Signature

type DrizzleUpsertValue = SQLWrapper | string | number | boolean | Date | null

Source

DrizzleWhereStep (interface)

A statement whose only remaining step is its WHERE.

Signature

export interface DrizzleWhereStep {
  where(where: SQL | undefined): DrizzleExecutable<unknown>
}

Source

EffectDrizzleDatabase (interface)

A drizzle handle whose built queries are Effects rather than Promises — drizzle-orm/effect-postgres, effect-pglite, effect-mysql2, effect-sqlite-* and the rest of drizzle’s Effect drivers.

Why this is shaped differently from the other doors

databaseLayer names its argument’s type exactly (PgAsyncDatabase and friends). This door checks the shape of the builder chain instead, so one signature covers every Effect driver, whatever dialect and Effect HKT it carries: it checks that select() yields a from(), that insert() yields a values(), and so on, down to the execute() the store layer calls. The table types cannot be checked at this boundary (no real drizzle handle is assignable to a signature generic over drizzle’s shared Table, which is why databaseLayer ends in a cast too), but the rows and inserts the stores see are still derived from the tables they were given.

Signature

export interface EffectDrizzleDatabase {
  select: ChainStep<{
    from: ChainStep<{
      where: ChainStep<unknown>
      limit: ChainStep<unknown>
      orderBy: ChainStep<unknown>
      execute: ChainStep<unknown>
    }>
  }>
  insert: ChainStep<{ values: ChainStep<{ execute: ChainStep<unknown> }> }>
  update: ChainStep<{ set: ChainStep<{ where: ChainStep<unknown> }> }>
  delete: ChainStep<{ where: ChainStep<{ execute: ChainStep<unknown> }> }>
}

Source

databaseLayer

Provide a Promise-shaped drizzle handle as DrizzleDatabase.

Accepts any PostgreSQL, SQLite or MySQL handle — drizzle(...) from any driver, and the transaction handle passed to db.transaction(...), since each dialect’s transaction type extends its database type — either directly or as an Effect that yields one.

Passing an Effect defers the handle to query time: it is run once per query, in the calling fiber, so a handle held in a Context.Reference follows the request that set it, as a request-scoped pool on Workers needs.

Pair it with the tables for the same dialect (Pg.tables, Sqlite.tables or MySql.tables); the store layers take those separately, so the pairing is the caller’s to get right.

Signature

declare const databaseLayer: {
  <TQueryResult extends PgQueryResultHKT, TRelations extends AnyRelations>(
    db: PgAsyncDatabase<TQueryResult, TRelations> | Effect.Effect<PgAsyncDatabase<TQueryResult, TRelations>>
  ): Layer.Layer<DrizzleDatabase>
  <TResultKind extends "sync" | "async", TRunResult, TRelations extends AnyRelations>(
    db:
      | SQLiteAsyncDatabase<TResultKind, TRunResult, TRelations>
      | Effect.Effect<SQLiteAsyncDatabase<TResultKind, TRunResult, TRelations>>
  ): Layer.Layer<DrizzleDatabase>
  <TQueryResult extends MySqlQueryResultHKT, TRelations extends AnyRelations>(
    db: MySqlAsyncDatabase<TQueryResult, TRelations> | Effect.Effect<MySqlAsyncDatabase<TQueryResult, TRelations>>
  ): Layer.Layer<DrizzleDatabase>
}

Source

effectDatabaseLayer

Provide an Effect-shaped drizzle handle as DrizzleDatabase.

This is the door for drizzle-orm/effect-postgres and its siblings, whose queries are Effects: the stores run them directly, so nothing in the path from Auth.SessionStore to the database crosses a Promise boundary. See EffectDrizzleDatabase for what this door can and cannot check.

As with databaseLayer, passing an Effect instead of a handle defers the handle to query time. With an Effect-shaped driver that is the whole request-scoped-pool story: the handle lives in the request’s Effect context and needs no AsyncLocalStorage to find its way to the query.

Example

import * as PgDrizzle from "drizzle-orm/effect-postgres"

const stores = Drizzle.Layers.layer(Drizzle.Pg.tables).pipe(
  Layer.provide(Drizzle.Database.effectDatabaseLayer(PgDrizzle.makeWithDefaults()))
)

Signature

declare const effectDatabaseLayer: (
  db: EffectDrizzleDatabase | Effect.Effect<EffectDrizzleDatabase>
) => Layer.Layer<DrizzleDatabase>

Source


This site uses Just the Docs, a documentation theme for Jekyll.