Skip to content

@unthrown/drizzle


@unthrown/drizzle / node-postgres

node-postgres

Database

NodePgUnthrownDatabase

Defined in: packages/drizzle/src/node-postgres/driver.ts:66

A node-postgres database whose every query resolves to an AsyncResult.

Remarks

The unthrown sibling of drizzle's NodePgDatabase. Build one with drizzle rather than by hand — the factory is what pairs a dialect, a session and a client.

Extends

Type Parameters

Type ParameterDefault typeDescription
TRelations extends AnyRelationsEmptyRelationsthe relational schema backing db.query.

Constructors

Constructor
ts
new NodePgUnthrownDatabase<TRelations>(
   dialect, 
   session, 
   relations): NodePgUnthrownDatabase<TRelations>;

Defined in: packages/drizzle/src/node-postgres/driver.ts:83

Parameters
ParameterType
dialectPgDialect
sessionNodePgUnthrownSession<TRelations>
relationsTRelations
Returns

NodePgUnthrownDatabase<TRelations>

Overrides

PgUnthrownDatabase.constructor

Properties

PropertyModifierTypeDefault valueDescriptionOverridesInherited fromDefined in
_readonlyobjectundefined--PgUnthrownDatabase._packages/drizzle/src/pg-core/db.ts:61
_.relationsreadonlyTRelationsundefined---packages/drizzle/src/pg-core/db.ts:62
_.sessionreadonlyPgUnthrownSession<unknown>undefined---packages/drizzle/src/pg-core/db.ts:63
$withreadonlyWithBuilderundefinedCreates a subquery that defines a temporary named result set as a CTE. It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query. See docs: https://orm.drizzle.team/docs/select#with-clause Param alias The alias for the subquery. Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries. Example // Create a subquery with alias 'sq' and use it in the select query const sq = db.$with("sq").as(db.select().from(users).where(eq(users.id, 42))); const rows = (await db.with(sq).select().from(sq)).get(); To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them: // Select an arbitrary SQL value as a field in a CTE and reference it in the main query const sq = db.$with("sq").as( db .select({ name: sql<string>upper(${users.name}).as("name"), }) .from(users), ); const rows = (await db.with(sq).select({ name: sq.name }).from(sq)).get();-PgUnthrownDatabase.$withpackages/drizzle/src/pg-core/db.ts:173
queryreadonly{ [K in string | number | symbol]: RelationalQueryBuilder<TRelations, TRelations[K], PgUnthrownRelationalQueryHKT> }undefinedThe relational query API — db.query.users.findMany(…), one entry per table in the relational schema.-PgUnthrownDatabase.querypackages/drizzle/src/pg-core/db.ts:70
sessionreadonlyNodePgUnthrownSession<TRelations>undefinedThe node-postgres session this database runs on. Remarks Narrows the base's PgUnthrownSession<unknown> — whose transaction handle is deliberately unresolved, because the base facade is built underneath the transaction class that extends it — to the one this driver actually holds. declare because the base already assigns it; this only restates its type, which is what gives transaction a typed handle.PgUnthrownDatabase.session-packages/drizzle/src/node-postgres/driver.ts:81
taggedreadonlybooleanfalse--PgUnthrownDatabase.taggedpackages/drizzle/src/pg-core/db.ts:85
[entityKind]readonlystring"NodePgUnthrownDatabase"-PgUnthrownDatabase.[entityKind]-packages/drizzle/src/node-postgres/driver.ts:69

Methods

$count()
ts
$count(source, filters?): PgUnthrownCountBuilder;

Defined in: packages/drizzle/src/pg-core/db.ts:218

Count the rows a table, view or subquery yields, optionally filtered.

Parameters
ParameterType
source| PgTable<TableConfig> | PgViewBase<string, boolean, ColumnsSelection> | SQL<unknown> | SQLWrapper<unknown>
filters?SQL<unknown>
Returns

PgUnthrownCountBuilder

Example
ts
const total = (await db.$count(users, eq(users.active, true))).get();
//    ^? number — a count is a read, so its error channel is `never`.
Inherited from

PgUnthrownDatabase.$count

delete()
ts
delete<TTable>(table): PgUnthrownDeleteBase<TTable, NodePgQueryResultHKT>;

Defined in: packages/drizzle/src/pg-core/db.ts:613

Creates a delete query.

Calling this method without .where() clause will delete all rows in a table. The .where() clause specifies which rows should be deleted.

See docs: https://orm.drizzle.team/docs/delete

A write carries the full PgQueryError union — a delete can still raise 23505 through an ON DELETE SET DEFAULT — so awaiting the builder resolves to a Result you fold with mapErrCases or match.

Type Parameters
Type Parameter
TTable extends PgTable<TableConfig>
Parameters
ParameterTypeDescription
tableTTableThe table to delete from.
Returns

PgUnthrownDeleteBase<TTable, NodePgQueryResultHKT>

Example
ts
// Delete all rows in the 'cars' table
const all = await db.delete(cars);
//    ^? Result<DeleteResult<…>, PgQueryError>

// Delete rows with filters and conditions
await db.delete(cars).where(eq(cars.color, "green"));

// Delete with returning clause
const deleted = await db.delete(cars).where(eq(cars.id, 1)).returning();
Inherited from

PgUnthrownDatabase.delete

execute()
ts
execute<TRow>(query): PgUnthrownRaw<QueryResult<Assume<TRow, QueryResultRow>>>;

Defined in: packages/drizzle/src/pg-core/db.ts:650

Run a statement drizzle does not model — a raw SQL fragment or a string.

Type Parameters
Type ParameterDefault type
TRow extends Record<string, unknown>Record<string, unknown>
Parameters
ParameterType
querystring | SQLWrapper<unknown>
Returns

PgUnthrownRaw<QueryResult<Assume<TRow, QueryResultRow>>>

Remarks

Unlike every other entry point, this one compiles its argument eagerly, because PgUnthrownRaw is defined as holding an already-prepared query (that is what makes its getSQL, getQuery and _prepare synchronous accessors, exactly as in drizzle). Compilation therefore happens here rather than at await, and a SQLWrapper that cannot compile throws at this call site instead of yielding a defect.

That is a deliberate line, not an oversight: the contract this package makes is about running a query — awaiting a builder, or calling its execute() — and db.execute(…) is the factory that produces one, not the run itself. The builder it returns is fully guarded. Reaching the throw takes handing in a query builder that is already broken (db.execute(db.select({ t: other.col }).from(users))); a string or a sql template — the documented use — cannot. Closing the gap would mean deferring compilation, which would cost PgRaw's shape and its synchronous accessors for a case where the argument, not the statement, is the bug.

Example
ts
const result = await db.execute(sql`select now()`);
Inherited from

PgUnthrownDatabase.execute

insert()
ts
insert<TTable>(table): PgInsertBuilder<TTable, NodePgQueryResultHKT, false, PgUnthrownInsertHKT>;

Defined in: packages/drizzle/src/pg-core/db.ts:572

Creates an insert query.

Calling this method will create new rows in a table. Use .values() method to specify which values to insert.

See docs: https://orm.drizzle.team/docs/insert

A write carries the full PgQueryError union, so awaiting the builder resolves to a Result you fold with mapErrCases or match — never a rejection.

Type Parameters
Type Parameter
TTable extends PgTable<TableConfig>
Parameters
ParameterTypeDescription
tableTTableThe table to insert into.
Returns

PgInsertBuilder<TTable, NodePgQueryResultHKT, false, PgUnthrownInsertHKT>

Example
ts
// Insert one row
const one = await db.insert(cars).values({ brand: "BMW" });
//    ^? Result<InsertResult<…>, PgQueryError>

// Insert multiple rows
await db.insert(cars).values([{ brand: "BMW" }, { brand: "Porsche" }]);

// Insert with returning clause
const inserted = await db.insert(cars).values({ brand: "BMW" }).returning();
Inherited from

PgUnthrownDatabase.insert

refreshMaterializedView()
ts
refreshMaterializedView<TView>(view): PgUnthrownRefreshMaterializedView<NodePgQueryResultHKT>;

Defined in: packages/drizzle/src/pg-core/db.ts:618

Rebuild a materialized view's stored rows.

Type Parameters
Type Parameter
TView extends PgMaterializedView<string, boolean, ColumnsSelection>
Parameters
ParameterType
viewTView
Returns

PgUnthrownRefreshMaterializedView<NodePgQueryResultHKT>

Inherited from

PgUnthrownDatabase.refreshMaterializedView

select()
Call Signature
ts
select(): PgUnthrownSelectBuilder<undefined>;

Defined in: packages/drizzle/src/pg-core/db.ts:396

Creates a select query.

Calling this method with no arguments will select all columns from the table. Pass a selection object to specify the columns you want to select.

Use .from() method to specify which table to select from.

See docs: https://orm.drizzle.team/docs/select

Awaiting the builder resolves to a Result, never rows directly — a read has no modeled failure, so the error channel is never and .get() compiles.

Returns

PgUnthrownSelectBuilder<undefined>

Example
ts
// Select all columns and all rows from the 'cars' table
const allCars = (await db.select().from(cars)).get();

// Select specific columns and all rows from the 'cars' table
const carsIdsAndBrands = (
  await db
    .select({
      id: cars.id,
      brand: cars.brand,
    })
    .from(cars)
).get();
Inherited from

PgUnthrownDatabase.select

Call Signature
ts
select<TSelection>(fields): PgUnthrownSelectBuilder<TSelection>;

Defined in: packages/drizzle/src/pg-core/db.ts:397

Creates a select query.

Calling this method with no arguments will select all columns from the table. Pass a selection object to specify the columns you want to select.

Use .from() method to specify which table to select from.

See docs: https://orm.drizzle.team/docs/select

Awaiting the builder resolves to a Result, never rows directly — a read has no modeled failure, so the error channel is never and .get() compiles.

Type Parameters
Type Parameter
TSelection extends SelectedFields
Parameters
ParameterType
fieldsTSelection
Returns

PgUnthrownSelectBuilder<TSelection>

Example
ts
// Select all columns and all rows from the 'cars' table
const allCars = (await db.select().from(cars)).get();

// Select specific columns and all rows from the 'cars' table
const carsIdsAndBrands = (
  await db
    .select({
      id: cars.id,
      brand: cars.brand,
    })
    .from(cars)
).get();
Inherited from

PgUnthrownDatabase.select

selectDistinct()
Call Signature
ts
selectDistinct(): PgUnthrownSelectBuilder<undefined>;

Defined in: packages/drizzle/src/pg-core/db.ts:437

Adds distinct expression to the select query.

Calling this method will return only unique values. When multiple columns are selected, it returns rows with unique combinations of values in these columns.

Use .from() method to specify which table to select from. Pass a selection object to specify the columns you want to select.

See docs: https://orm.drizzle.team/docs/select#distinct

Returns

PgUnthrownSelectBuilder<undefined>

Example
ts
// Select all unique rows from the 'cars' table
const unique = (
  await db.selectDistinct().from(cars).orderBy(cars.id, cars.brand, cars.color)
).get();

// Select all unique brands from the 'cars' table
const brands = (
  await db.selectDistinct({ brand: cars.brand }).from(cars).orderBy(cars.brand)
).get();
Inherited from

PgUnthrownDatabase.selectDistinct

Call Signature
ts
selectDistinct<TSelection>(fields): PgUnthrownSelectBuilder<TSelection>;

Defined in: packages/drizzle/src/pg-core/db.ts:438

Adds distinct expression to the select query.

Calling this method will return only unique values. When multiple columns are selected, it returns rows with unique combinations of values in these columns.

Use .from() method to specify which table to select from. Pass a selection object to specify the columns you want to select.

See docs: https://orm.drizzle.team/docs/select#distinct

Type Parameters
Type Parameter
TSelection extends SelectedFields
Parameters
ParameterType
fieldsTSelection
Returns

PgUnthrownSelectBuilder<TSelection>

Example
ts
// Select all unique rows from the 'cars' table
const unique = (
  await db.selectDistinct().from(cars).orderBy(cars.id, cars.brand, cars.color)
).get();

// Select all unique brands from the 'cars' table
const brands = (
  await db.selectDistinct({ brand: cars.brand }).from(cars).orderBy(cars.brand)
).get();
Inherited from

PgUnthrownDatabase.selectDistinct

selectDistinctOn()
Call Signature
ts
selectDistinctOn(on): PgUnthrownSelectBuilder<undefined>;

Defined in: packages/drizzle/src/pg-core/db.ts:483

Adds distinct on expression to the select query.

Calling this method will specify how the unique rows are determined.

Use .from() method to specify which table to select from. Pass a selection object as the second argument to specify the columns you want to select.

See docs: https://orm.drizzle.team/docs/select#distinct

Parameters
ParameterTypeDescription
on( | SQLWrapper<unknown> | PgColumn<any, PgColumnBaseConfig<any>, { }>)[]The expression defining uniqueness.
Returns

PgUnthrownSelectBuilder<undefined>

Example
ts
// Select the first row for each unique brand from the 'cars' table
const firstPerBrand = (
  await db.selectDistinctOn([cars.brand]).from(cars).orderBy(cars.brand)
).get();

// The first occurrence of each unique brand, with its color
const brandColors = (
  await db
    .selectDistinctOn([cars.brand], { brand: cars.brand, color: cars.color })
    .from(cars)
    .orderBy(cars.brand, cars.color)
).get();
Inherited from

PgUnthrownDatabase.selectDistinctOn

Call Signature
ts
selectDistinctOn<TSelection>(on, fields): PgUnthrownSelectBuilder<TSelection>;

Defined in: packages/drizzle/src/pg-core/db.ts:484

Adds distinct on expression to the select query.

Calling this method will specify how the unique rows are determined.

Use .from() method to specify which table to select from. Pass a selection object as the second argument to specify the columns you want to select.

See docs: https://orm.drizzle.team/docs/select#distinct

Type Parameters
Type Parameter
TSelection extends SelectedFields
Parameters
ParameterTypeDescription
on( | SQLWrapper<unknown> | PgColumn<any, PgColumnBaseConfig<any>, { }>)[]The expression defining uniqueness.
fieldsTSelection-
Returns

PgUnthrownSelectBuilder<TSelection>

Example
ts
// Select the first row for each unique brand from the 'cars' table
const firstPerBrand = (
  await db.selectDistinctOn([cars.brand]).from(cars).orderBy(cars.brand)
).get();

// The first occurrence of each unique brand, with its color
const brandColors = (
  await db
    .selectDistinctOn([cars.brand], { brand: cars.brand, color: cars.color })
    .from(cars)
    .orderBy(cars.brand, cars.color)
).get();
Inherited from

PgUnthrownDatabase.selectDistinctOn

transaction()
ts
transaction<A, E>(fn, config?): AsyncResult<A, PgQueryError | E>;

Defined in: packages/drizzle/src/node-postgres/driver.ts:134

Run fn inside a database transaction.

Type Parameters
Type Parameter
A
E
Parameters
ParameterTypeDescription
fn(tx) => AsyncResult<A, E>the work to run inside the transaction.
config?PgTransactionConfigisolation level, access mode and deferrability, rendered into the BEGIN.
Returns

AsyncResult<A, PgQueryError | E>

Remarks

Ok commits; Err and Defect both roll back. An Err re-surfaces typed in the error channel, so rolling back costs no information — and because rollback is returning an Err, there is no tx.rollback().

PgQueryError joins the callback's own error channel because the transaction's control statements can fail on their own account: a DEFERRABLE constraint is checked at COMMIT, so a unique violation can be raised by the commit rather than by any statement the callback ran.

The callback owes an AsyncResult, so each step ends in .execute() — a builder is a thenable that resolves to a Result, not an AsyncResult itself — and the steps compose with flatMap or DoAsync().bind(…).

A one-line delegate to NodePgUnthrownSession.transaction, exactly as drizzle's own database delegates to its session: the session owns the connection, and a transaction is a property of one connection.

Example
ts
const moved = await db.transaction((tx) =>
  tx
    .update(accounts)
    .set({ balance: sql`${accounts.balance} - 100` })
    .where(eq(accounts.id, from))
    .execute()
    .flatMap(() =>
      tx
        .update(accounts)
        .set({ balance: sql`${accounts.balance} + 100` })
        .where(eq(accounts.id, to))
        .execute(),
    ),
);
update()
ts
update<TTable>(table): PgUpdateBuilder<TTable, NodePgQueryResultHKT, PgUnthrownUpdateHKT>;

Defined in: packages/drizzle/src/pg-core/db.ts:538

Creates an update query.

Calling this method without .where() clause will update all rows in a table. The .where() clause specifies which rows should be updated.

Use .set() method to specify which values to update.

See docs: https://orm.drizzle.team/docs/update

A write carries the full PgQueryError union, so awaiting the builder resolves to a Result you fold with mapErrCases or match — never a rejection.

Type Parameters
Type Parameter
TTable extends PgTable<TableConfig>
Parameters
ParameterTypeDescription
tableTTableThe table to update.
Returns

PgUpdateBuilder<TTable, NodePgQueryResultHKT, PgUnthrownUpdateHKT>

Example
ts
// Update all rows in the 'cars' table
const all = await db.update(cars).set({ color: "red" });
//    ^? Result<UpdateResult<…>, PgQueryError>

// Update rows with filters and conditions
await db.update(cars).set({ color: "red" }).where(eq(cars.brand, "BMW"));

// Update with returning clause
const updated = await db
  .update(cars)
  .set({ color: "red" })
  .where(eq(cars.id, 1))
  .returning();
Inherited from

PgUnthrownDatabase.update

with()
ts
with(...queries): object;

Defined in: packages/drizzle/src/pg-core/db.ts:251

Incorporates a previously defined CTE (using $with) into the main query.

This method allows the main query to reference a temporary named result set.

See docs: https://orm.drizzle.team/docs/select#with-clause

Parameters
ParameterTypeDescription
...queriesWithSubquery<string, Record<string, unknown>>[]The CTEs to incorporate into the main query.
Returns

object

NameTypeDefined in
delete()<TTable>(table) => PgUnthrownDeleteBase<TTable, NodePgQueryResultHKT>packages/drizzle/src/pg-core/db.ts:273
insert()<TTable>(table) => PgInsertBuilder<TTable, NodePgQueryResultHKT, false, PgUnthrownInsertHKT>packages/drizzle/src/pg-core/db.ts:270
select(){ (): PgUnthrownSelectBuilder<undefined>; <TSelection> (fields): PgUnthrownSelectBuilder<TSelection>; }packages/drizzle/src/pg-core/db.ts:252
selectDistinct(){ (): PgUnthrownSelectBuilder<undefined>; <TSelection> (fields): PgUnthrownSelectBuilder<TSelection>; }packages/drizzle/src/pg-core/db.ts:256
selectDistinctOn(){ (on): PgUnthrownSelectBuilder<undefined>; <TSelection> (on, fields): PgUnthrownSelectBuilder<TSelection>; }packages/drizzle/src/pg-core/db.ts:260
update()<TTable>(table) => PgUpdateBuilder<TTable, NodePgQueryResultHKT, PgUnthrownUpdateHKT>packages/drizzle/src/pg-core/db.ts:267
Example
ts
// Define a subquery 'sq' as a CTE using $with
const sq = db.$with("sq").as(db.select().from(users).where(eq(users.id, 42)));

// Incorporate the CTE 'sq' into the main query and select from it
const rows = (await db.with(sq).select().from(sq)).get();
Inherited from

PgUnthrownDatabase.with


UnthrownDrizzleConfig

ts
type UnthrownDrizzleConfig<TRelations> = object;

Defined in: packages/drizzle/src/node-postgres/driver.ts:36

The options drizzle accepts.

Remarks

Drizzle's DrizzlePgConfig minus the members this package does not carry:

  • schema — drizzle removed it from the Postgres config in v1; relations is the successor.
  • cache — the query cache hangs off db.$cache and invalidates on mutation, neither of which this database facade models yet.
  • jit — drizzle's JIT row mappers are gated behind an @internal compatibility probe that is stripped from its published .d.ts, so it cannot be forwarded without reimplementing the probe. Leaving it out gives drizzle's own default (the premade mappers), so nothing silently changes.

Type Parameters

Type ParameterDefault typeDescription
TRelations extends AnyRelationsEmptyRelationsthe relational schema backing db.query.

Properties

PropertyModifierTypeDescriptionDefined in
codecs?readonlyPgCodecsColumn codecs, overriding node-postgres' own.packages/drizzle/src/node-postgres/driver.ts:45
logger?readonlyboolean | Loggertrue for drizzle's DefaultLogger (every statement to the console), a Logger of your own, or false/absent for none.packages/drizzle/src/node-postgres/driver.ts:43
relations?readonlyTRelationsThe relational schema, as built by drizzle's defineRelations.packages/drizzle/src/node-postgres/driver.ts:38

drizzle()

Call Signature

ts
function drizzle<TRelations>(connectionString, config?): NodePgUnthrownDatabase<TRelations> & object;

Defined in: packages/drizzle/src/node-postgres/driver.ts:218

Build a Postgres database whose every query resolves to an AsyncResult.

Type Parameters
Type ParameterDefault type
TRelations extends TablesRelationalConfigEmptyRelations
Parameters
ParameterType
connectionStringstring
config?UnthrownDrizzleConfig<TRelations>
Returns

NodePgUnthrownDatabase<TRelations> & object

Remarks

This replaces drizzle-orm/node-postgres's own drizzle() rather than wrapping its result: migrating a call site is an import change. Every method on the database already speaks AsyncResult, so there is no try* naming scheme to learn — a query's modeled failures are the PgQueryError union, and every infrastructure failure (a dropped connection, a deadlock, a statement that will not compile) is a defect rather than a value you branch on.

The escape hatch is db.$client: it is the very client you passed (or the pool the factory built), so a stock drizzle-orm/node-postgres database over the same pool — for a migration runner, or a batch API this package does not model — is one line away.

The call forms are exactly drizzle's own — a connection string (with an optional UnthrownDrizzleConfig second argument), or a configuration object carrying a client under client or connection details under connection. There is deliberately no positional-client form: drizzle has none, and a second spelling of { client: pool } would mean a call site no longer ports back by changing the import. (@param is left unspelled deliberately: one doc comment fronts three overloads whose parameters are named differently.)

Example
ts
const db = drizzle({ client: pool, relations });

const created = await db
  .insert(users)
  .values({ id: 1, email: "ada@example.com" })
  .returning()
  .execute()
  .mapErrCases((m) =>
    m.with(P.tag("UniqueConstraintViolation"), () => "email already taken" as const)
     .with(
       P.tag("ForeignKeyViolation"),
       P.tag("CheckViolation"),
       P.tag("ExclusionViolation"),
       P.tag("NotNullViolation"),
       (e) => e._tag,
     ),
  );

Call Signature

ts
function drizzle<TClient, TRelations>(config): NodePgUnthrownDatabase<TRelations> & object;

Defined in: packages/drizzle/src/node-postgres/driver.ts:222

Build a Postgres database whose every query resolves to an AsyncResult.

Type Parameters
Type ParameterDefault type
TClient extends NodePgClient-
TRelations extends TablesRelationalConfigEmptyRelations
Parameters
ParameterType
configUnthrownDrizzleConfig<TRelations> & object
Returns

NodePgUnthrownDatabase<TRelations> & object

Remarks

This replaces drizzle-orm/node-postgres's own drizzle() rather than wrapping its result: migrating a call site is an import change. Every method on the database already speaks AsyncResult, so there is no try* naming scheme to learn — a query's modeled failures are the PgQueryError union, and every infrastructure failure (a dropped connection, a deadlock, a statement that will not compile) is a defect rather than a value you branch on.

The escape hatch is db.$client: it is the very client you passed (or the pool the factory built), so a stock drizzle-orm/node-postgres database over the same pool — for a migration runner, or a batch API this package does not model — is one line away.

The call forms are exactly drizzle's own — a connection string (with an optional UnthrownDrizzleConfig second argument), or a configuration object carrying a client under client or connection details under connection. There is deliberately no positional-client form: drizzle has none, and a second spelling of { client: pool } would mean a call site no longer ports back by changing the import. (@param is left unspelled deliberately: one doc comment fronts three overloads whose parameters are named differently.)

Example
ts
const db = drizzle({ client: pool, relations });

const created = await db
  .insert(users)
  .values({ id: 1, email: "ada@example.com" })
  .returning()
  .execute()
  .mapErrCases((m) =>
    m.with(P.tag("UniqueConstraintViolation"), () => "email already taken" as const)
     .with(
       P.tag("ForeignKeyViolation"),
       P.tag("CheckViolation"),
       P.tag("ExclusionViolation"),
       P.tag("NotNullViolation"),
       (e) => e._tag,
     ),
  );

Call Signature

ts
function drizzle<TRelations>(config): NodePgUnthrownDatabase<TRelations> & object;

Defined in: packages/drizzle/src/node-postgres/driver.ts:228

Build a Postgres database whose every query resolves to an AsyncResult.

Type Parameters
Type ParameterDefault type
TRelations extends TablesRelationalConfigEmptyRelations
Parameters
ParameterType
configUnthrownDrizzleConfig<TRelations> & object
Returns

NodePgUnthrownDatabase<TRelations> & object

Remarks

This replaces drizzle-orm/node-postgres's own drizzle() rather than wrapping its result: migrating a call site is an import change. Every method on the database already speaks AsyncResult, so there is no try* naming scheme to learn — a query's modeled failures are the PgQueryError union, and every infrastructure failure (a dropped connection, a deadlock, a statement that will not compile) is a defect rather than a value you branch on.

The escape hatch is db.$client: it is the very client you passed (or the pool the factory built), so a stock drizzle-orm/node-postgres database over the same pool — for a migration runner, or a batch API this package does not model — is one line away.

The call forms are exactly drizzle's own — a connection string (with an optional UnthrownDrizzleConfig second argument), or a configuration object carrying a client under client or connection details under connection. There is deliberately no positional-client form: drizzle has none, and a second spelling of { client: pool } would mean a call site no longer ports back by changing the import. (@param is left unspelled deliberately: one doc comment fronts three overloads whose parameters are named differently.)

Example
ts
const db = drizzle({ client: pool, relations });

const created = await db
  .insert(users)
  .values({ id: 1, email: "ada@example.com" })
  .returning()
  .execute()
  .mapErrCases((m) =>
    m.with(P.tag("UniqueConstraintViolation"), () => "email already taken" as const)
     .with(
       P.tag("ForeignKeyViolation"),
       P.tag("CheckViolation"),
       P.tag("ExclusionViolation"),
       P.tag("NotNullViolation"),
       (e) => e._tag,
     ),
  );

Session

NodePgUnthrownSession

Defined in: packages/drizzle/src/node-postgres/session.ts:243

A node-postgres session whose every query resolves to an AsyncResult.

Remarks

The unthrown sibling of drizzle's NodePgSession. Everything above it is type plumbing; this is where a real driver is spoken to.

Extends

Type Parameters

Type ParameterDefault typeDescription
TRelations extends AnyRelationsEmptyRelationsthe relational schema backing db.query.

Constructors

Constructor
ts
new NodePgUnthrownSession<TRelations>(
   client, 
   dialect, 
   relations, 
   logger?): NodePgUnthrownSession<TRelations>;

Defined in: packages/drizzle/src/node-postgres/session.ts:256

Parameters
ParameterTypeDescription
clientNodePgClientthe pool or client to run statements against. A pool has a connection checked out for the duration of a transaction and released afterwards; a plain client is used as-is.
dialectPgDialectdrizzle's Postgres dialect, which compiles the SQL.
relationsTRelationsthe relational schema, forwarded to every transaction.
loggerLoggerdrizzle's query logger.
Returns

NodePgUnthrownSession<TRelations>

Overrides

PgUnthrownSession.constructor

Properties

PropertyModifierTypeDefault valueOverridesDefined in
[entityKind]readonlystring"NodePgUnthrownSession"PgUnthrownSession.[entityKind]packages/drizzle/src/node-postgres/session.ts:246

Methods

arrays()
ts
arrays(query): AsyncResult<unknown, PgQueryError>;

Defined in: packages/drizzle/src/pg-core/session.ts:276

Run a raw SQL fragment, returning each row as an array of column values.

Parameters
ParameterType
querySQL
Returns

AsyncResult<unknown, PgQueryError>

Inherited from

PgUnthrownSession.arrays

execute()
ts
execute(query): AsyncResult<unknown, PgQueryError>;

Defined in: packages/drizzle/src/pg-core/session.ts:271

Run a raw SQL fragment, returning the driver's own result object.

Parameters
ParameterType
querySQL
Returns

AsyncResult<unknown, PgQueryError>

Remarks

Compilation runs inside the failure boundary — see runQuery. dialect.sqlToQuery throws for mistakes that are type-legal and reachable, and a throw escaping here would land on a caller who has no try/catch, because this method's contract is a Result.

Inherited from

PgUnthrownSession.execute

objects()
ts
objects(query): AsyncResult<unknown, PgQueryError>;

Defined in: packages/drizzle/src/pg-core/session.ts:281

Run a raw SQL fragment, returning each row as a column-keyed object.

Parameters
ParameterType
querySQL
Returns

AsyncResult<unknown, PgQueryError>

Inherited from

PgUnthrownSession.objects

prepareQuery()
ts
prepareQuery<T>(
   query, 
   mode, 
   name, 
   mapper?): PgUnthrownPreparedQuery<T>;

Defined in: packages/drizzle/src/node-postgres/session.ts:265

Type Parameters
Type ParameterDefault type
T extends PreparedQueryConfigPreparedQueryConfig
Parameters
ParameterType
queryQuery
modePgQueryMode
namestring | boolean
mapper?PgRowMapper
Returns

PgUnthrownPreparedQuery<T>

Overrides

PgUnthrownSession.prepareQuery

transaction()
ts
transaction<A, E>(fn, config?): AsyncResult<A, PgQueryError | E>;

Defined in: packages/drizzle/src/node-postgres/session.ts:339

Run fn inside a database transaction.

Type Parameters
Type Parameter
A
E
Parameters
ParameterType
fn(tx) => AsyncResult<A, E>
config?PgTransactionConfig
Returns

AsyncResult<A, PgQueryError | E>

Remarks

Ok commits; Err and Defect both roll back. An Err re-surfaces typed in the error channel, so rolling back costs no information — and because rollback is returning an Err, there is no tx.rollback().

PgQueryError joins the callback's own error channel because the transaction's control statements can fail on their own account: a DEFERRABLE constraint is checked at COMMIT, so a unique violation can be raised by the commit rather than by any statement the callback ran.

The whole sequence is qualified once, here, and nothing inside it is left to a channel that could swallow it: the control statements run on the raw rejecting path (see PgUnthrownPreparedQuery.runUnqualified), so a failed COMMIT can never be mistaken for a successful one.

The callback owes an AsyncResult, so each step ends in .execute() — a builder is a thenable that resolves to a Result, not an AsyncResult itself — and the steps compose with flatMap.

Example
ts
const moved = await db.transaction((tx) =>
  tx
    .update(accounts)
    .set({ balance: sql`${accounts.balance} - 100` })
    .where(eq(accounts.id, from))
    .execute()
    .flatMap(() =>
      tx
        .update(accounts)
        .set({ balance: sql`${accounts.balance} + 100` })
        .where(eq(accounts.id, to))
        .execute(),
    ),
);
Overrides

PgUnthrownSession.transaction


NodePgUnthrownTransaction

Defined in: packages/drizzle/src/node-postgres/session.ts:407

The handle a NodePgUnthrownSession.transaction callback receives: a database whose statements all run inside the open transaction.

Remarks

There is deliberately no rollback(). Drizzle needs one because its rollback signal is a throw; here the signal is an Err, and a second spelling of one concept is exactly what this library does not do. Return an Err — from a failed query or one of your own — and the transaction rolls back with that error still in hand.

Extends

Type Parameters

Type ParameterDefault typeDescription
TRelations extends AnyRelationsEmptyRelationsthe relational schema backing tx.query.

Constructors

Constructor
ts
new NodePgUnthrownTransaction<TRelations>(
   dialect, 
   session, 
   relations, 
   savepoints?, 
   parseRqbJson?): NodePgUnthrownTransaction<TRelations>;

Defined in: packages/drizzle/src/node-postgres/session.ts:417

Parameters
ParameterTypeDefault valueDescription
dialectPgDialectundefined-
sessionPgUnthrownSession<unknown>undefined-
relationsTRelationsundefined-
savepoints{ count: number; }...the savepoint-name counter, shared by every handle descended from one transaction (see transaction). Defaults to a fresh one, which is what a root transaction wants.
savepoints.countnumberundefined-
parseRqbJsonbooleanfalse-
Returns

NodePgUnthrownTransaction<TRelations>

Overrides

PgUnthrownDatabase.constructor

Properties

PropertyModifierTypeDefault valueDescriptionOverridesInherited fromDefined in
_readonlyobjectundefined--PgUnthrownDatabase._packages/drizzle/src/pg-core/db.ts:61
_.relationsreadonlyTRelationsundefined---packages/drizzle/src/pg-core/db.ts:62
_.sessionreadonlyPgUnthrownSession<unknown>undefined---packages/drizzle/src/pg-core/db.ts:63
$withreadonlyWithBuilderundefinedCreates a subquery that defines a temporary named result set as a CTE. It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query. See docs: https://orm.drizzle.team/docs/select#with-clause Param alias The alias for the subquery. Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries. Example // Create a subquery with alias 'sq' and use it in the select query const sq = db.$with("sq").as(db.select().from(users).where(eq(users.id, 42))); const rows = (await db.with(sq).select().from(sq)).get(); To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them: // Select an arbitrary SQL value as a field in a CTE and reference it in the main query const sq = db.$with("sq").as( db .select({ name: sql<string>upper(${users.name}).as("name"), }) .from(users), ); const rows = (await db.with(sq).select({ name: sq.name }).from(sq)).get();-PgUnthrownDatabase.$withpackages/drizzle/src/pg-core/db.ts:173
queryreadonly{ [K in string | number | symbol]: RelationalQueryBuilder<TRelations, TRelations[K], PgUnthrownRelationalQueryHKT> }undefinedThe relational query API — db.query.users.findMany(…), one entry per table in the relational schema.-PgUnthrownDatabase.querypackages/drizzle/src/pg-core/db.ts:70
taggedreadonlybooleanfalse--PgUnthrownDatabase.taggedpackages/drizzle/src/pg-core/db.ts:85
[entityKind]readonlystring"NodePgUnthrownTransaction"-PgUnthrownDatabase.[entityKind]-packages/drizzle/src/node-postgres/session.ts:410

Methods

$count()
ts
$count(source, filters?): PgUnthrownCountBuilder;

Defined in: packages/drizzle/src/pg-core/db.ts:218

Count the rows a table, view or subquery yields, optionally filtered.

Parameters
ParameterType
source| PgTable<TableConfig> | PgViewBase<string, boolean, ColumnsSelection> | SQL<unknown> | SQLWrapper<unknown>
filters?SQL<unknown>
Returns

PgUnthrownCountBuilder

Example
ts
const total = (await db.$count(users, eq(users.active, true))).get();
//    ^? number — a count is a read, so its error channel is `never`.
Inherited from

PgUnthrownDatabase.$count

delete()
ts
delete<TTable>(table): PgUnthrownDeleteBase<TTable, NodePgQueryResultHKT>;

Defined in: packages/drizzle/src/pg-core/db.ts:613

Creates a delete query.

Calling this method without .where() clause will delete all rows in a table. The .where() clause specifies which rows should be deleted.

See docs: https://orm.drizzle.team/docs/delete

A write carries the full PgQueryError union — a delete can still raise 23505 through an ON DELETE SET DEFAULT — so awaiting the builder resolves to a Result you fold with mapErrCases or match.

Type Parameters
Type Parameter
TTable extends PgTable<TableConfig>
Parameters
ParameterTypeDescription
tableTTableThe table to delete from.
Returns

PgUnthrownDeleteBase<TTable, NodePgQueryResultHKT>

Example
ts
// Delete all rows in the 'cars' table
const all = await db.delete(cars);
//    ^? Result<DeleteResult<…>, PgQueryError>

// Delete rows with filters and conditions
await db.delete(cars).where(eq(cars.color, "green"));

// Delete with returning clause
const deleted = await db.delete(cars).where(eq(cars.id, 1)).returning();
Inherited from

PgUnthrownDatabase.delete

execute()
ts
execute<TRow>(query): PgUnthrownRaw<QueryResult<Assume<TRow, QueryResultRow>>>;

Defined in: packages/drizzle/src/pg-core/db.ts:650

Run a statement drizzle does not model — a raw SQL fragment or a string.

Type Parameters
Type ParameterDefault type
TRow extends Record<string, unknown>Record<string, unknown>
Parameters
ParameterType
querystring | SQLWrapper<unknown>
Returns

PgUnthrownRaw<QueryResult<Assume<TRow, QueryResultRow>>>

Remarks

Unlike every other entry point, this one compiles its argument eagerly, because PgUnthrownRaw is defined as holding an already-prepared query (that is what makes its getSQL, getQuery and _prepare synchronous accessors, exactly as in drizzle). Compilation therefore happens here rather than at await, and a SQLWrapper that cannot compile throws at this call site instead of yielding a defect.

That is a deliberate line, not an oversight: the contract this package makes is about running a query — awaiting a builder, or calling its execute() — and db.execute(…) is the factory that produces one, not the run itself. The builder it returns is fully guarded. Reaching the throw takes handing in a query builder that is already broken (db.execute(db.select({ t: other.col }).from(users))); a string or a sql template — the documented use — cannot. Closing the gap would mean deferring compilation, which would cost PgRaw's shape and its synchronous accessors for a case where the argument, not the statement, is the bug.

Example
ts
const result = await db.execute(sql`select now()`);
Inherited from

PgUnthrownDatabase.execute

insert()
ts
insert<TTable>(table): PgInsertBuilder<TTable, NodePgQueryResultHKT, false, PgUnthrownInsertHKT>;

Defined in: packages/drizzle/src/pg-core/db.ts:572

Creates an insert query.

Calling this method will create new rows in a table. Use .values() method to specify which values to insert.

See docs: https://orm.drizzle.team/docs/insert

A write carries the full PgQueryError union, so awaiting the builder resolves to a Result you fold with mapErrCases or match — never a rejection.

Type Parameters
Type Parameter
TTable extends PgTable<TableConfig>
Parameters
ParameterTypeDescription
tableTTableThe table to insert into.
Returns

PgInsertBuilder<TTable, NodePgQueryResultHKT, false, PgUnthrownInsertHKT>

Example
ts
// Insert one row
const one = await db.insert(cars).values({ brand: "BMW" });
//    ^? Result<InsertResult<…>, PgQueryError>

// Insert multiple rows
await db.insert(cars).values([{ brand: "BMW" }, { brand: "Porsche" }]);

// Insert with returning clause
const inserted = await db.insert(cars).values({ brand: "BMW" }).returning();
Inherited from

PgUnthrownDatabase.insert

refreshMaterializedView()
ts
refreshMaterializedView<TView>(view): PgUnthrownRefreshMaterializedView<NodePgQueryResultHKT>;

Defined in: packages/drizzle/src/pg-core/db.ts:618

Rebuild a materialized view's stored rows.

Type Parameters
Type Parameter
TView extends PgMaterializedView<string, boolean, ColumnsSelection>
Parameters
ParameterType
viewTView
Returns

PgUnthrownRefreshMaterializedView<NodePgQueryResultHKT>

Inherited from

PgUnthrownDatabase.refreshMaterializedView

select()
Call Signature
ts
select(): PgUnthrownSelectBuilder<undefined>;

Defined in: packages/drizzle/src/pg-core/db.ts:396

Creates a select query.

Calling this method with no arguments will select all columns from the table. Pass a selection object to specify the columns you want to select.

Use .from() method to specify which table to select from.

See docs: https://orm.drizzle.team/docs/select

Awaiting the builder resolves to a Result, never rows directly — a read has no modeled failure, so the error channel is never and .get() compiles.

Returns

PgUnthrownSelectBuilder<undefined>

Example
ts
// Select all columns and all rows from the 'cars' table
const allCars = (await db.select().from(cars)).get();

// Select specific columns and all rows from the 'cars' table
const carsIdsAndBrands = (
  await db
    .select({
      id: cars.id,
      brand: cars.brand,
    })
    .from(cars)
).get();
Inherited from

PgUnthrownDatabase.select

Call Signature
ts
select<TSelection>(fields): PgUnthrownSelectBuilder<TSelection>;

Defined in: packages/drizzle/src/pg-core/db.ts:397

Creates a select query.

Calling this method with no arguments will select all columns from the table. Pass a selection object to specify the columns you want to select.

Use .from() method to specify which table to select from.

See docs: https://orm.drizzle.team/docs/select

Awaiting the builder resolves to a Result, never rows directly — a read has no modeled failure, so the error channel is never and .get() compiles.

Type Parameters
Type Parameter
TSelection extends SelectedFields
Parameters
ParameterType
fieldsTSelection
Returns

PgUnthrownSelectBuilder<TSelection>

Example
ts
// Select all columns and all rows from the 'cars' table
const allCars = (await db.select().from(cars)).get();

// Select specific columns and all rows from the 'cars' table
const carsIdsAndBrands = (
  await db
    .select({
      id: cars.id,
      brand: cars.brand,
    })
    .from(cars)
).get();
Inherited from

PgUnthrownDatabase.select

selectDistinct()
Call Signature
ts
selectDistinct(): PgUnthrownSelectBuilder<undefined>;

Defined in: packages/drizzle/src/pg-core/db.ts:437

Adds distinct expression to the select query.

Calling this method will return only unique values. When multiple columns are selected, it returns rows with unique combinations of values in these columns.

Use .from() method to specify which table to select from. Pass a selection object to specify the columns you want to select.

See docs: https://orm.drizzle.team/docs/select#distinct

Returns

PgUnthrownSelectBuilder<undefined>

Example
ts
// Select all unique rows from the 'cars' table
const unique = (
  await db.selectDistinct().from(cars).orderBy(cars.id, cars.brand, cars.color)
).get();

// Select all unique brands from the 'cars' table
const brands = (
  await db.selectDistinct({ brand: cars.brand }).from(cars).orderBy(cars.brand)
).get();
Inherited from

PgUnthrownDatabase.selectDistinct

Call Signature
ts
selectDistinct<TSelection>(fields): PgUnthrownSelectBuilder<TSelection>;

Defined in: packages/drizzle/src/pg-core/db.ts:438

Adds distinct expression to the select query.

Calling this method will return only unique values. When multiple columns are selected, it returns rows with unique combinations of values in these columns.

Use .from() method to specify which table to select from. Pass a selection object to specify the columns you want to select.

See docs: https://orm.drizzle.team/docs/select#distinct

Type Parameters
Type Parameter
TSelection extends SelectedFields
Parameters
ParameterType
fieldsTSelection
Returns

PgUnthrownSelectBuilder<TSelection>

Example
ts
// Select all unique rows from the 'cars' table
const unique = (
  await db.selectDistinct().from(cars).orderBy(cars.id, cars.brand, cars.color)
).get();

// Select all unique brands from the 'cars' table
const brands = (
  await db.selectDistinct({ brand: cars.brand }).from(cars).orderBy(cars.brand)
).get();
Inherited from

PgUnthrownDatabase.selectDistinct

selectDistinctOn()
Call Signature
ts
selectDistinctOn(on): PgUnthrownSelectBuilder<undefined>;

Defined in: packages/drizzle/src/pg-core/db.ts:483

Adds distinct on expression to the select query.

Calling this method will specify how the unique rows are determined.

Use .from() method to specify which table to select from. Pass a selection object as the second argument to specify the columns you want to select.

See docs: https://orm.drizzle.team/docs/select#distinct

Parameters
ParameterTypeDescription
on( | SQLWrapper<unknown> | PgColumn<any, PgColumnBaseConfig<any>, { }>)[]The expression defining uniqueness.
Returns

PgUnthrownSelectBuilder<undefined>

Example
ts
// Select the first row for each unique brand from the 'cars' table
const firstPerBrand = (
  await db.selectDistinctOn([cars.brand]).from(cars).orderBy(cars.brand)
).get();

// The first occurrence of each unique brand, with its color
const brandColors = (
  await db
    .selectDistinctOn([cars.brand], { brand: cars.brand, color: cars.color })
    .from(cars)
    .orderBy(cars.brand, cars.color)
).get();
Inherited from

PgUnthrownDatabase.selectDistinctOn

Call Signature
ts
selectDistinctOn<TSelection>(on, fields): PgUnthrownSelectBuilder<TSelection>;

Defined in: packages/drizzle/src/pg-core/db.ts:484

Adds distinct on expression to the select query.

Calling this method will specify how the unique rows are determined.

Use .from() method to specify which table to select from. Pass a selection object as the second argument to specify the columns you want to select.

See docs: https://orm.drizzle.team/docs/select#distinct

Type Parameters
Type Parameter
TSelection extends SelectedFields
Parameters
ParameterTypeDescription
on( | SQLWrapper<unknown> | PgColumn<any, PgColumnBaseConfig<any>, { }>)[]The expression defining uniqueness.
fieldsTSelection-
Returns

PgUnthrownSelectBuilder<TSelection>

Example
ts
// Select the first row for each unique brand from the 'cars' table
const firstPerBrand = (
  await db.selectDistinctOn([cars.brand]).from(cars).orderBy(cars.brand)
).get();

// The first occurrence of each unique brand, with its color
const brandColors = (
  await db
    .selectDistinctOn([cars.brand], { brand: cars.brand, color: cars.color })
    .from(cars)
    .orderBy(cars.brand, cars.color)
).get();
Inherited from

PgUnthrownDatabase.selectDistinctOn

setTransaction()
ts
setTransaction(config): AsyncResult<unknown, PgQueryError>;

Defined in: packages/drizzle/src/node-postgres/session.ts:440

Set the characteristics of the transaction already in progress.

Parameters
ParameterType
configPgTransactionConfig
Returns

AsyncResult<unknown, PgQueryError>

Remarks

A config that asks for nothing ({}) issues no statement: Postgres requires at least one mode after set transaction, so the alternative is a syntax error reported as a defect for a call that requested no change.

Example
ts
await tx.setTransaction({ isolationLevel: "serializable" });
transaction()
ts
transaction<A, E>(fn): AsyncResult<A, PgQueryError | E>;

Defined in: packages/drizzle/src/node-postgres/session.ts:484

Run fn inside a nested transaction — a savepoint of the enclosing one.

Type Parameters
Type Parameter
A
E
Parameters
ParameterType
fn(tx) => AsyncResult<A, E>
Returns

AsyncResult<A, PgQueryError | E>

Remarks

The same rule one level down: Ok releases the savepoint, Err and Defect roll back to it. Only the nested scope is undone, so the enclosing transaction stays open and decides for itself — recover the inner Err and the outer scope still commits.

Savepoint names come from a counter shared by every handle descended from one transaction, so no two live savepoints on that connection can share a name. Naming them by nesting depth (drizzle's scheme) is safe only while nested transactions are started one after another; two started concurrently — which allAsync makes an easy thing to write — would both be sp1 on the one connection, and the first rollback to savepoint sp1 would unwind the other's work.

Example
ts
const result = await db.transaction((tx) =>
  tx
    .transaction((nested) => nested.insert(logs).values({ message: "optional" }).execute())
    // The savepoint rolled back; the outer transaction carries on. Every
    // case is named, so the grouped arm lists the whole PgQueryError union.
    .recoverErrCases((m) =>
      m.with(
        P.tag("UniqueConstraintViolation"),
        P.tag("ForeignKeyViolation"),
        P.tag("CheckViolation"),
        P.tag("ExclusionViolation"),
        P.tag("NotNullViolation"),
        () => undefined,
      ),
    )
    .flatMap(() => tx.insert(users).values({ id: 1, name: "ada" }).execute()),
);
update()
ts
update<TTable>(table): PgUpdateBuilder<TTable, NodePgQueryResultHKT, PgUnthrownUpdateHKT>;

Defined in: packages/drizzle/src/pg-core/db.ts:538

Creates an update query.

Calling this method without .where() clause will update all rows in a table. The .where() clause specifies which rows should be updated.

Use .set() method to specify which values to update.

See docs: https://orm.drizzle.team/docs/update

A write carries the full PgQueryError union, so awaiting the builder resolves to a Result you fold with mapErrCases or match — never a rejection.

Type Parameters
Type Parameter
TTable extends PgTable<TableConfig>
Parameters
ParameterTypeDescription
tableTTableThe table to update.
Returns

PgUpdateBuilder<TTable, NodePgQueryResultHKT, PgUnthrownUpdateHKT>

Example
ts
// Update all rows in the 'cars' table
const all = await db.update(cars).set({ color: "red" });
//    ^? Result<UpdateResult<…>, PgQueryError>

// Update rows with filters and conditions
await db.update(cars).set({ color: "red" }).where(eq(cars.brand, "BMW"));

// Update with returning clause
const updated = await db
  .update(cars)
  .set({ color: "red" })
  .where(eq(cars.id, 1))
  .returning();
Inherited from

PgUnthrownDatabase.update

with()
ts
with(...queries): object;

Defined in: packages/drizzle/src/pg-core/db.ts:251

Incorporates a previously defined CTE (using $with) into the main query.

This method allows the main query to reference a temporary named result set.

See docs: https://orm.drizzle.team/docs/select#with-clause

Parameters
ParameterTypeDescription
...queriesWithSubquery<string, Record<string, unknown>>[]The CTEs to incorporate into the main query.
Returns

object

NameTypeDefined in
delete()<TTable>(table) => PgUnthrownDeleteBase<TTable, NodePgQueryResultHKT>packages/drizzle/src/pg-core/db.ts:273
insert()<TTable>(table) => PgInsertBuilder<TTable, NodePgQueryResultHKT, false, PgUnthrownInsertHKT>packages/drizzle/src/pg-core/db.ts:270
select(){ (): PgUnthrownSelectBuilder<undefined>; <TSelection> (fields): PgUnthrownSelectBuilder<TSelection>; }packages/drizzle/src/pg-core/db.ts:252
selectDistinct(){ (): PgUnthrownSelectBuilder<undefined>; <TSelection> (fields): PgUnthrownSelectBuilder<TSelection>; }packages/drizzle/src/pg-core/db.ts:256
selectDistinctOn(){ (on): PgUnthrownSelectBuilder<undefined>; <TSelection> (on, fields): PgUnthrownSelectBuilder<TSelection>; }packages/drizzle/src/pg-core/db.ts:260
update()<TTable>(table) => PgUpdateBuilder<TTable, NodePgQueryResultHKT, PgUnthrownUpdateHKT>packages/drizzle/src/pg-core/db.ts:267
Example
ts
// Define a subquery 'sq' as a CTE using $with
const sq = db.$with("sq").as(db.select().from(users).where(eq(users.id, 42)));

// Incorporate the CTE 'sq' into the main query and select from it
const rows = (await db.with(sq).select().from(sq)).get();
Inherited from

PgUnthrownDatabase.with


NodePgClient

ts
type NodePgClient = pg.Pool | pg.PoolClient | pg.Client;

Defined in: packages/drizzle/src/node-postgres/session.ts:33

A node-postgres client this package can drive: a pool, a client checked out of one, or a standalone client.

Released under the MIT License.