@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
PgUnthrownDatabase<NodePgQueryResultHKT,TRelations>
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
TRelations extends AnyRelations | EmptyRelations | the relational schema backing db.query. |
Constructors
Constructor
new NodePgUnthrownDatabase<TRelations>(
dialect,
session,
relations): NodePgUnthrownDatabase<TRelations>;Defined in: packages/drizzle/src/node-postgres/driver.ts:83
Parameters
| Parameter | Type |
|---|---|
dialect | PgDialect |
session | NodePgUnthrownSession<TRelations> |
relations | TRelations |
Returns
NodePgUnthrownDatabase<TRelations>
Overrides
PgUnthrownDatabase.constructor
Properties
| Property | Modifier | Type | Default value | Description | Overrides | Inherited from | Defined in |
|---|---|---|---|---|---|---|---|
_ | readonly | object | undefined | - | - | PgUnthrownDatabase._ | packages/drizzle/src/pg-core/db.ts:61 |
_.relations | readonly | TRelations | undefined | - | - | - | packages/drizzle/src/pg-core/db.ts:62 |
_.session | readonly | PgUnthrownSession<unknown> | undefined | - | - | - | packages/drizzle/src/pg-core/db.ts:63 |
$with | readonly | WithBuilder | undefined | Creates 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.$with | packages/drizzle/src/pg-core/db.ts:173 |
query | readonly | { [K in string | number | symbol]: RelationalQueryBuilder<TRelations, TRelations[K], PgUnthrownRelationalQueryHKT> } | undefined | The relational query API — db.query.users.findMany(…), one entry per table in the relational schema. | - | PgUnthrownDatabase.query | packages/drizzle/src/pg-core/db.ts:70 |
session | readonly | NodePgUnthrownSession<TRelations> | undefined | The 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 |
tagged | readonly | boolean | false | - | - | PgUnthrownDatabase.tagged | packages/drizzle/src/pg-core/db.ts:85 |
[entityKind] | readonly | string | "NodePgUnthrownDatabase" | - | PgUnthrownDatabase.[entityKind] | - | packages/drizzle/src/node-postgres/driver.ts:69 |
Methods
$count()
$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
| Parameter | Type |
|---|---|
source | | PgTable<TableConfig> | PgViewBase<string, boolean, ColumnsSelection> | SQL<unknown> | SQLWrapper<unknown> |
filters? | SQL<unknown> |
Returns
Example
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
delete()
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
| Parameter | Type | Description |
|---|---|---|
table | TTable | The table to delete from. |
Returns
PgUnthrownDeleteBase<TTable, NodePgQueryResultHKT>
Example
// 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
execute()
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 Parameter | Default type |
|---|---|
TRow extends Record<string, unknown> | Record<string, unknown> |
Parameters
| Parameter | Type |
|---|---|
query | string | 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
const result = await db.execute(sql`select now()`);Inherited from
insert()
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
| Parameter | Type | Description |
|---|---|---|
table | TTable | The table to insert into. |
Returns
PgInsertBuilder<TTable, NodePgQueryResultHKT, false, PgUnthrownInsertHKT>
Example
// 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
refreshMaterializedView()
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
| Parameter | Type |
|---|---|
view | TView |
Returns
PgUnthrownRefreshMaterializedView<NodePgQueryResultHKT>
Inherited from
PgUnthrownDatabase.refreshMaterializedView
select()
Call Signature
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
// 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
Call Signature
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
| Parameter | Type |
|---|---|
fields | TSelection |
Returns
PgUnthrownSelectBuilder<TSelection>
Example
// 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
selectDistinct()
Call Signature
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
// 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
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
| Parameter | Type |
|---|---|
fields | TSelection |
Returns
PgUnthrownSelectBuilder<TSelection>
Example
// 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
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
| Parameter | Type | Description |
|---|---|---|
on | ( | SQLWrapper<unknown> | PgColumn<any, PgColumnBaseConfig<any>, { }>)[] | The expression defining uniqueness. |
Returns
PgUnthrownSelectBuilder<undefined>
Example
// 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
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
| Parameter | Type | Description |
|---|---|---|
on | ( | SQLWrapper<unknown> | PgColumn<any, PgColumnBaseConfig<any>, { }>)[] | The expression defining uniqueness. |
fields | TSelection | - |
Returns
PgUnthrownSelectBuilder<TSelection>
Example
// 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()
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
| Parameter | Type | Description |
|---|---|---|
fn | (tx) => AsyncResult<A, E> | the work to run inside the transaction. |
config? | PgTransactionConfig | isolation 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
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()
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
| Parameter | Type | Description |
|---|---|---|
table | TTable | The table to update. |
Returns
PgUpdateBuilder<TTable, NodePgQueryResultHKT, PgUnthrownUpdateHKT>
Example
// 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
with()
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
| Parameter | Type | Description |
|---|---|---|
...queries | WithSubquery<string, Record<string, unknown>>[] | The CTEs to incorporate into the main query. |
Returns
object
| Name | Type | Defined 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
// 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
UnthrownDrizzleConfig
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;relationsis the successor.cache— the query cache hangs offdb.$cacheand invalidates on mutation, neither of which this database facade models yet.jit— drizzle's JIT row mappers are gated behind an@internalcompatibility 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 Parameter | Default type | Description |
|---|---|---|
TRelations extends AnyRelations | EmptyRelations | the relational schema backing db.query. |
Properties
| Property | Modifier | Type | Description | Defined in |
|---|---|---|---|---|
codecs? | readonly | PgCodecs | Column codecs, overriding node-postgres' own. | packages/drizzle/src/node-postgres/driver.ts:45 |
logger? | readonly | boolean | Logger | true 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? | readonly | TRelations | The relational schema, as built by drizzle's defineRelations. | packages/drizzle/src/node-postgres/driver.ts:38 |
drizzle()
Call Signature
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 Parameter | Default type |
|---|---|
TRelations extends TablesRelationalConfig | EmptyRelations |
Parameters
| Parameter | Type |
|---|---|
connectionString | string |
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
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
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 Parameter | Default type |
|---|---|
TClient extends NodePgClient | - |
TRelations extends TablesRelationalConfig | EmptyRelations |
Parameters
| Parameter | Type |
|---|---|
config | UnthrownDrizzleConfig<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
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
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 Parameter | Default type |
|---|---|
TRelations extends TablesRelationalConfig | EmptyRelations |
Parameters
| Parameter | Type |
|---|---|
config | UnthrownDrizzleConfig<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
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
PgUnthrownSession<NodePgUnthrownTransaction<TRelations>>
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
TRelations extends AnyRelations | EmptyRelations | the relational schema backing db.query. |
Constructors
Constructor
new NodePgUnthrownSession<TRelations>(
client,
dialect,
relations,
logger?): NodePgUnthrownSession<TRelations>;Defined in: packages/drizzle/src/node-postgres/session.ts:256
Parameters
| Parameter | Type | Description |
|---|---|---|
client | NodePgClient | the 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. |
dialect | PgDialect | drizzle's Postgres dialect, which compiles the SQL. |
relations | TRelations | the relational schema, forwarded to every transaction. |
logger | Logger | drizzle's query logger. |
Returns
NodePgUnthrownSession<TRelations>
Overrides
Properties
| Property | Modifier | Type | Default value | Overrides | Defined in |
|---|---|---|---|---|---|
[entityKind] | readonly | string | "NodePgUnthrownSession" | PgUnthrownSession.[entityKind] | packages/drizzle/src/node-postgres/session.ts:246 |
Methods
arrays()
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
| Parameter | Type |
|---|---|
query | SQL |
Returns
AsyncResult<unknown, PgQueryError>
Inherited from
execute()
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
| Parameter | Type |
|---|---|
query | SQL |
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
objects()
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
| Parameter | Type |
|---|---|
query | SQL |
Returns
AsyncResult<unknown, PgQueryError>
Inherited from
prepareQuery()
prepareQuery<T>(
query,
mode,
name,
mapper?): PgUnthrownPreparedQuery<T>;Defined in: packages/drizzle/src/node-postgres/session.ts:265
Type Parameters
| Type Parameter | Default type |
|---|---|
T extends PreparedQueryConfig | PreparedQueryConfig |
Parameters
| Parameter | Type |
|---|---|
query | Query |
mode | PgQueryMode |
name | string | boolean |
mapper? | PgRowMapper |
Returns
Overrides
PgUnthrownSession.prepareQuery
transaction()
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
| Parameter | Type |
|---|---|
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
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
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
PgUnthrownDatabase<NodePgQueryResultHKT,TRelations>
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
TRelations extends AnyRelations | EmptyRelations | the relational schema backing tx.query. |
Constructors
Constructor
new NodePgUnthrownTransaction<TRelations>(
dialect,
session,
relations,
savepoints?,
parseRqbJson?): NodePgUnthrownTransaction<TRelations>;Defined in: packages/drizzle/src/node-postgres/session.ts:417
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
dialect | PgDialect | undefined | - |
session | PgUnthrownSession<unknown> | undefined | - |
relations | TRelations | undefined | - |
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.count | number | undefined | - |
parseRqbJson | boolean | false | - |
Returns
NodePgUnthrownTransaction<TRelations>
Overrides
PgUnthrownDatabase.constructor
Properties
| Property | Modifier | Type | Default value | Description | Overrides | Inherited from | Defined in |
|---|---|---|---|---|---|---|---|
_ | readonly | object | undefined | - | - | PgUnthrownDatabase._ | packages/drizzle/src/pg-core/db.ts:61 |
_.relations | readonly | TRelations | undefined | - | - | - | packages/drizzle/src/pg-core/db.ts:62 |
_.session | readonly | PgUnthrownSession<unknown> | undefined | - | - | - | packages/drizzle/src/pg-core/db.ts:63 |
$with | readonly | WithBuilder | undefined | Creates 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.$with | packages/drizzle/src/pg-core/db.ts:173 |
query | readonly | { [K in string | number | symbol]: RelationalQueryBuilder<TRelations, TRelations[K], PgUnthrownRelationalQueryHKT> } | undefined | The relational query API — db.query.users.findMany(…), one entry per table in the relational schema. | - | PgUnthrownDatabase.query | packages/drizzle/src/pg-core/db.ts:70 |
tagged | readonly | boolean | false | - | - | PgUnthrownDatabase.tagged | packages/drizzle/src/pg-core/db.ts:85 |
[entityKind] | readonly | string | "NodePgUnthrownTransaction" | - | PgUnthrownDatabase.[entityKind] | - | packages/drizzle/src/node-postgres/session.ts:410 |
Methods
$count()
$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
| Parameter | Type |
|---|---|
source | | PgTable<TableConfig> | PgViewBase<string, boolean, ColumnsSelection> | SQL<unknown> | SQLWrapper<unknown> |
filters? | SQL<unknown> |
Returns
Example
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
delete()
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
| Parameter | Type | Description |
|---|---|---|
table | TTable | The table to delete from. |
Returns
PgUnthrownDeleteBase<TTable, NodePgQueryResultHKT>
Example
// 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
execute()
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 Parameter | Default type |
|---|---|
TRow extends Record<string, unknown> | Record<string, unknown> |
Parameters
| Parameter | Type |
|---|---|
query | string | 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
const result = await db.execute(sql`select now()`);Inherited from
insert()
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
| Parameter | Type | Description |
|---|---|---|
table | TTable | The table to insert into. |
Returns
PgInsertBuilder<TTable, NodePgQueryResultHKT, false, PgUnthrownInsertHKT>
Example
// 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
refreshMaterializedView()
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
| Parameter | Type |
|---|---|
view | TView |
Returns
PgUnthrownRefreshMaterializedView<NodePgQueryResultHKT>
Inherited from
PgUnthrownDatabase.refreshMaterializedView
select()
Call Signature
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
// 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
Call Signature
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
| Parameter | Type |
|---|---|
fields | TSelection |
Returns
PgUnthrownSelectBuilder<TSelection>
Example
// 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
selectDistinct()
Call Signature
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
// 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
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
| Parameter | Type |
|---|---|
fields | TSelection |
Returns
PgUnthrownSelectBuilder<TSelection>
Example
// 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
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
| Parameter | Type | Description |
|---|---|---|
on | ( | SQLWrapper<unknown> | PgColumn<any, PgColumnBaseConfig<any>, { }>)[] | The expression defining uniqueness. |
Returns
PgUnthrownSelectBuilder<undefined>
Example
// 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
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
| Parameter | Type | Description |
|---|---|---|
on | ( | SQLWrapper<unknown> | PgColumn<any, PgColumnBaseConfig<any>, { }>)[] | The expression defining uniqueness. |
fields | TSelection | - |
Returns
PgUnthrownSelectBuilder<TSelection>
Example
// 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()
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
| Parameter | Type |
|---|---|
config | PgTransactionConfig |
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
await tx.setTransaction({ isolationLevel: "serializable" });transaction()
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
| Parameter | Type |
|---|---|
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
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()
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
| Parameter | Type | Description |
|---|---|---|
table | TTable | The table to update. |
Returns
PgUpdateBuilder<TTable, NodePgQueryResultHKT, PgUnthrownUpdateHKT>
Example
// 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
with()
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
| Parameter | Type | Description |
|---|---|---|
...queries | WithSubquery<string, Record<string, unknown>>[] | The CTEs to incorporate into the main query. |
Returns
object
| Name | Type | Defined 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
// 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
NodePgClient
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.