Initial commit

This commit is contained in:
Ammaar Reshi
2025-01-04 14:06:53 +00:00
parent 7082408604
commit d6025af146
23760 changed files with 3299690 additions and 0 deletions

View File

@ -0,0 +1,79 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var count_exports = {};
__export(count_exports, {
PgCountBuilder: () => PgCountBuilder
});
module.exports = __toCommonJS(count_exports);
var import_entity = require("../../entity.cjs");
var import_sql = require("../../sql/sql.cjs");
class PgCountBuilder extends import_sql.SQL {
constructor(params) {
super(PgCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
this.params = params;
this.mapWith(Number);
this.session = params.session;
this.sql = PgCountBuilder.buildCount(
params.source,
params.filters
);
}
sql;
token;
static [import_entity.entityKind] = "PgCountBuilder";
[Symbol.toStringTag] = "PgCountBuilder";
session;
static buildEmbeddedCount(source, filters) {
return import_sql.sql`(select count(*) from ${source}${import_sql.sql.raw(" where ").if(filters)}${filters})`;
}
static buildCount(source, filters) {
return import_sql.sql`select count(*) as count from ${source}${import_sql.sql.raw(" where ").if(filters)}${filters};`;
}
/** @intrnal */
setToken(token) {
this.token = token;
return this;
}
then(onfulfilled, onrejected) {
return Promise.resolve(this.session.count(this.sql, this.token)).then(
onfulfilled,
onrejected
);
}
catch(onRejected) {
return this.then(void 0, onRejected);
}
finally(onFinally) {
return this.then(
(value) => {
onFinally?.();
return value;
},
(reason) => {
onFinally?.();
throw reason;
}
);
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
PgCountBuilder
});
//# sourceMappingURL=count.cjs.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/pg-core/query-builders/count.ts"],"sourcesContent":["import { entityKind } from '~/entity.ts';\nimport { SQL, sql, type SQLWrapper } from '~/sql/sql.ts';\nimport type { NeonAuthToken } from '~/utils.ts';\nimport type { PgSession } from '../session.ts';\nimport type { PgTable } from '../table.ts';\n\nexport class PgCountBuilder<\n\tTSession extends PgSession<any, any, any>,\n> extends SQL<number> implements Promise<number>, SQLWrapper {\n\tprivate sql: SQL<number>;\n\tprivate token?: NeonAuthToken;\n\n\tstatic override readonly [entityKind] = 'PgCountBuilder';\n\t[Symbol.toStringTag] = 'PgCountBuilder';\n\n\tprivate session: TSession;\n\n\tprivate static buildEmbeddedCount(\n\t\tsource: PgTable | SQL | SQLWrapper,\n\t\tfilters?: SQL<unknown>,\n\t): SQL<number> {\n\t\treturn sql<number>`(select count(*) from ${source}${sql.raw(' where ').if(filters)}${filters})`;\n\t}\n\n\tprivate static buildCount(\n\t\tsource: PgTable | SQL | SQLWrapper,\n\t\tfilters?: SQL<unknown>,\n\t): SQL<number> {\n\t\treturn sql<number>`select count(*) as count from ${source}${sql.raw(' where ').if(filters)}${filters};`;\n\t}\n\n\tconstructor(\n\t\treadonly params: {\n\t\t\tsource: PgTable | SQL | SQLWrapper;\n\t\t\tfilters?: SQL<unknown>;\n\t\t\tsession: TSession;\n\t\t},\n\t) {\n\t\tsuper(PgCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);\n\n\t\tthis.mapWith(Number);\n\n\t\tthis.session = params.session;\n\n\t\tthis.sql = PgCountBuilder.buildCount(\n\t\t\tparams.source,\n\t\t\tparams.filters,\n\t\t);\n\t}\n\n\t/** @intrnal */\n\tsetToken(token?: NeonAuthToken) {\n\t\tthis.token = token;\n\t\treturn this;\n\t}\n\n\tthen<TResult1 = number, TResult2 = never>(\n\t\tonfulfilled?: ((value: number) => TResult1 | PromiseLike<TResult1>) | null | undefined,\n\t\tonrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined,\n\t): Promise<TResult1 | TResult2> {\n\t\treturn Promise.resolve(this.session.count(this.sql, this.token))\n\t\t\t.then(\n\t\t\t\tonfulfilled,\n\t\t\t\tonrejected,\n\t\t\t);\n\t}\n\n\tcatch(\n\t\tonRejected?: ((reason: any) => any) | null | undefined,\n\t): Promise<number> {\n\t\treturn this.then(undefined, onRejected);\n\t}\n\n\tfinally(onFinally?: (() => void) | null | undefined): Promise<number> {\n\t\treturn this.then(\n\t\t\t(value) => {\n\t\t\t\tonFinally?.();\n\t\t\t\treturn value;\n\t\t\t},\n\t\t\t(reason) => {\n\t\t\t\tonFinally?.();\n\t\t\t\tthrow reason;\n\t\t\t},\n\t\t);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA2B;AAC3B,iBAA0C;AAKnC,MAAM,uBAEH,eAAmD;AAAA,EAuB5D,YACU,QAKR;AACD,UAAM,eAAe,mBAAmB,OAAO,QAAQ,OAAO,OAAO,EAAE,WAAW;AANzE;AAQT,SAAK,QAAQ,MAAM;AAEnB,SAAK,UAAU,OAAO;AAEtB,SAAK,MAAM,eAAe;AAAA,MACzB,OAAO;AAAA,MACP,OAAO;AAAA,IACR;AAAA,EACD;AAAA,EAvCQ;AAAA,EACA;AAAA,EAER,QAA0B,wBAAU,IAAI;AAAA,EACxC,CAAC,OAAO,WAAW,IAAI;AAAA,EAEf;AAAA,EAER,OAAe,mBACd,QACA,SACc;AACd,WAAO,uCAAoC,MAAM,GAAG,eAAI,IAAI,SAAS,EAAE,GAAG,OAAO,CAAC,GAAG,OAAO;AAAA,EAC7F;AAAA,EAEA,OAAe,WACd,QACA,SACc;AACd,WAAO,+CAA4C,MAAM,GAAG,eAAI,IAAI,SAAS,EAAE,GAAG,OAAO,CAAC,GAAG,OAAO;AAAA,EACrG;AAAA;AAAA,EAsBA,SAAS,OAAuB;AAC/B,SAAK,QAAQ;AACb,WAAO;AAAA,EACR;AAAA,EAEA,KACC,aACA,YAC+B;AAC/B,WAAO,QAAQ,QAAQ,KAAK,QAAQ,MAAM,KAAK,KAAK,KAAK,KAAK,CAAC,EAC7D;AAAA,MACA;AAAA,MACA;AAAA,IACD;AAAA,EACF;AAAA,EAEA,MACC,YACkB;AAClB,WAAO,KAAK,KAAK,QAAW,UAAU;AAAA,EACvC;AAAA,EAEA,QAAQ,WAA8D;AACrE,WAAO,KAAK;AAAA,MACX,CAAC,UAAU;AACV,oBAAY;AACZ,eAAO;AAAA,MACR;AAAA,MACA,CAAC,WAAW;AACX,oBAAY;AACZ,cAAM;AAAA,MACP;AAAA,IACD;AAAA,EACD;AACD;","names":[]}

View File

@ -0,0 +1,29 @@
import { entityKind } from "../../entity.cjs";
import { SQL, type SQLWrapper } from "../../sql/sql.cjs";
import type { NeonAuthToken } from "../../utils.cjs";
import type { PgSession } from "../session.cjs";
import type { PgTable } from "../table.cjs";
export declare class PgCountBuilder<TSession extends PgSession<any, any, any>> extends SQL<number> implements Promise<number>, SQLWrapper {
readonly params: {
source: PgTable | SQL | SQLWrapper;
filters?: SQL<unknown>;
session: TSession;
};
private sql;
private token?;
static readonly [entityKind] = "PgCountBuilder";
[Symbol.toStringTag]: string;
private session;
private static buildEmbeddedCount;
private static buildCount;
constructor(params: {
source: PgTable | SQL | SQLWrapper;
filters?: SQL<unknown>;
session: TSession;
});
/** @intrnal */
setToken(token?: NeonAuthToken): this;
then<TResult1 = number, TResult2 = never>(onfulfilled?: ((value: number) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined): Promise<TResult1 | TResult2>;
catch(onRejected?: ((reason: any) => any) | null | undefined): Promise<number>;
finally(onFinally?: (() => void) | null | undefined): Promise<number>;
}

View File

@ -0,0 +1,29 @@
import { entityKind } from "../../entity.js";
import { SQL, type SQLWrapper } from "../../sql/sql.js";
import type { NeonAuthToken } from "../../utils.js";
import type { PgSession } from "../session.js";
import type { PgTable } from "../table.js";
export declare class PgCountBuilder<TSession extends PgSession<any, any, any>> extends SQL<number> implements Promise<number>, SQLWrapper {
readonly params: {
source: PgTable | SQL | SQLWrapper;
filters?: SQL<unknown>;
session: TSession;
};
private sql;
private token?;
static readonly [entityKind] = "PgCountBuilder";
[Symbol.toStringTag]: string;
private session;
private static buildEmbeddedCount;
private static buildCount;
constructor(params: {
source: PgTable | SQL | SQLWrapper;
filters?: SQL<unknown>;
session: TSession;
});
/** @intrnal */
setToken(token?: NeonAuthToken): this;
then<TResult1 = number, TResult2 = never>(onfulfilled?: ((value: number) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined): Promise<TResult1 | TResult2>;
catch(onRejected?: ((reason: any) => any) | null | undefined): Promise<number>;
finally(onFinally?: (() => void) | null | undefined): Promise<number>;
}

View File

@ -0,0 +1,55 @@
import { entityKind } from "../../entity.js";
import { SQL, sql } from "../../sql/sql.js";
class PgCountBuilder extends SQL {
constructor(params) {
super(PgCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
this.params = params;
this.mapWith(Number);
this.session = params.session;
this.sql = PgCountBuilder.buildCount(
params.source,
params.filters
);
}
sql;
token;
static [entityKind] = "PgCountBuilder";
[Symbol.toStringTag] = "PgCountBuilder";
session;
static buildEmbeddedCount(source, filters) {
return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`;
}
static buildCount(source, filters) {
return sql`select count(*) as count from ${source}${sql.raw(" where ").if(filters)}${filters};`;
}
/** @intrnal */
setToken(token) {
this.token = token;
return this;
}
then(onfulfilled, onrejected) {
return Promise.resolve(this.session.count(this.sql, this.token)).then(
onfulfilled,
onrejected
);
}
catch(onRejected) {
return this.then(void 0, onRejected);
}
finally(onFinally) {
return this.then(
(value) => {
onFinally?.();
return value;
},
(reason) => {
onFinally?.();
throw reason;
}
);
}
}
export {
PgCountBuilder
};
//# sourceMappingURL=count.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/pg-core/query-builders/count.ts"],"sourcesContent":["import { entityKind } from '~/entity.ts';\nimport { SQL, sql, type SQLWrapper } from '~/sql/sql.ts';\nimport type { NeonAuthToken } from '~/utils.ts';\nimport type { PgSession } from '../session.ts';\nimport type { PgTable } from '../table.ts';\n\nexport class PgCountBuilder<\n\tTSession extends PgSession<any, any, any>,\n> extends SQL<number> implements Promise<number>, SQLWrapper {\n\tprivate sql: SQL<number>;\n\tprivate token?: NeonAuthToken;\n\n\tstatic override readonly [entityKind] = 'PgCountBuilder';\n\t[Symbol.toStringTag] = 'PgCountBuilder';\n\n\tprivate session: TSession;\n\n\tprivate static buildEmbeddedCount(\n\t\tsource: PgTable | SQL | SQLWrapper,\n\t\tfilters?: SQL<unknown>,\n\t): SQL<number> {\n\t\treturn sql<number>`(select count(*) from ${source}${sql.raw(' where ').if(filters)}${filters})`;\n\t}\n\n\tprivate static buildCount(\n\t\tsource: PgTable | SQL | SQLWrapper,\n\t\tfilters?: SQL<unknown>,\n\t): SQL<number> {\n\t\treturn sql<number>`select count(*) as count from ${source}${sql.raw(' where ').if(filters)}${filters};`;\n\t}\n\n\tconstructor(\n\t\treadonly params: {\n\t\t\tsource: PgTable | SQL | SQLWrapper;\n\t\t\tfilters?: SQL<unknown>;\n\t\t\tsession: TSession;\n\t\t},\n\t) {\n\t\tsuper(PgCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);\n\n\t\tthis.mapWith(Number);\n\n\t\tthis.session = params.session;\n\n\t\tthis.sql = PgCountBuilder.buildCount(\n\t\t\tparams.source,\n\t\t\tparams.filters,\n\t\t);\n\t}\n\n\t/** @intrnal */\n\tsetToken(token?: NeonAuthToken) {\n\t\tthis.token = token;\n\t\treturn this;\n\t}\n\n\tthen<TResult1 = number, TResult2 = never>(\n\t\tonfulfilled?: ((value: number) => TResult1 | PromiseLike<TResult1>) | null | undefined,\n\t\tonrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined,\n\t): Promise<TResult1 | TResult2> {\n\t\treturn Promise.resolve(this.session.count(this.sql, this.token))\n\t\t\t.then(\n\t\t\t\tonfulfilled,\n\t\t\t\tonrejected,\n\t\t\t);\n\t}\n\n\tcatch(\n\t\tonRejected?: ((reason: any) => any) | null | undefined,\n\t): Promise<number> {\n\t\treturn this.then(undefined, onRejected);\n\t}\n\n\tfinally(onFinally?: (() => void) | null | undefined): Promise<number> {\n\t\treturn this.then(\n\t\t\t(value) => {\n\t\t\t\tonFinally?.();\n\t\t\t\treturn value;\n\t\t\t},\n\t\t\t(reason) => {\n\t\t\t\tonFinally?.();\n\t\t\t\tthrow reason;\n\t\t\t},\n\t\t);\n\t}\n}\n"],"mappings":"AAAA,SAAS,kBAAkB;AAC3B,SAAS,KAAK,WAA4B;AAKnC,MAAM,uBAEH,IAAmD;AAAA,EAuB5D,YACU,QAKR;AACD,UAAM,eAAe,mBAAmB,OAAO,QAAQ,OAAO,OAAO,EAAE,WAAW;AANzE;AAQT,SAAK,QAAQ,MAAM;AAEnB,SAAK,UAAU,OAAO;AAEtB,SAAK,MAAM,eAAe;AAAA,MACzB,OAAO;AAAA,MACP,OAAO;AAAA,IACR;AAAA,EACD;AAAA,EAvCQ;AAAA,EACA;AAAA,EAER,QAA0B,UAAU,IAAI;AAAA,EACxC,CAAC,OAAO,WAAW,IAAI;AAAA,EAEf;AAAA,EAER,OAAe,mBACd,QACA,SACc;AACd,WAAO,4BAAoC,MAAM,GAAG,IAAI,IAAI,SAAS,EAAE,GAAG,OAAO,CAAC,GAAG,OAAO;AAAA,EAC7F;AAAA,EAEA,OAAe,WACd,QACA,SACc;AACd,WAAO,oCAA4C,MAAM,GAAG,IAAI,IAAI,SAAS,EAAE,GAAG,OAAO,CAAC,GAAG,OAAO;AAAA,EACrG;AAAA;AAAA,EAsBA,SAAS,OAAuB;AAC/B,SAAK,QAAQ;AACb,WAAO;AAAA,EACR;AAAA,EAEA,KACC,aACA,YAC+B;AAC/B,WAAO,QAAQ,QAAQ,KAAK,QAAQ,MAAM,KAAK,KAAK,KAAK,KAAK,CAAC,EAC7D;AAAA,MACA;AAAA,MACA;AAAA,IACD;AAAA,EACF;AAAA,EAEA,MACC,YACkB;AAClB,WAAO,KAAK,KAAK,QAAW,UAAU;AAAA,EACvC;AAAA,EAEA,QAAQ,WAA8D;AACrE,WAAO,KAAK;AAAA,MACX,CAAC,UAAU;AACV,oBAAY;AACZ,eAAO;AAAA,MACR;AAAA,MACA,CAAC,WAAW;AACX,oBAAY;AACZ,cAAM;AAAA,MACP;AAAA,IACD;AAAA,EACD;AACD;","names":[]}

View File

@ -0,0 +1,111 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var delete_exports = {};
__export(delete_exports, {
PgDeleteBase: () => PgDeleteBase
});
module.exports = __toCommonJS(delete_exports);
var import_entity = require("../../entity.cjs");
var import_query_promise = require("../../query-promise.cjs");
var import_table = require("../../table.cjs");
var import_tracing = require("../../tracing.cjs");
var import_utils = require("../../utils.cjs");
class PgDeleteBase extends import_query_promise.QueryPromise {
constructor(table, session, dialect, withList) {
super();
this.session = session;
this.dialect = dialect;
this.config = { table, withList };
}
static [import_entity.entityKind] = "PgDelete";
config;
/**
* Adds a `where` clause to the query.
*
* Calling this method will delete only those rows that fulfill a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/delete}
*
* @param where the `where` clause.
*
* @example
* You can use conditional operators and `sql function` to filter the rows to be deleted.
*
* ```ts
* // Delete all cars with green color
* await db.delete(cars).where(eq(cars.color, 'green'));
* // or
* await db.delete(cars).where(sql`${cars.color} = 'green'`)
* ```
*
* You can logically combine conditional operators with `and()` and `or()` operators:
*
* ```ts
* // Delete all BMW cars with a green color
* await db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
*
* // Delete all cars with the green or blue color
* await db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where) {
this.config.where = where;
return this;
}
returning(fields = this.config.table[import_table.Table.Symbol.Columns]) {
this.config.returning = (0, import_utils.orderSelectedFields)(fields);
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildDeleteQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
/** @internal */
_prepare(name) {
return import_tracing.tracer.startActiveSpan("drizzle.prepareQuery", () => {
return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true);
});
}
prepare(name) {
return this._prepare(name);
}
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
execute = (placeholderValues) => {
return import_tracing.tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(placeholderValues, this.authToken);
});
};
$dynamic() {
return this;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
PgDeleteBase
});
//# sourceMappingURL=delete.cjs.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,100 @@
import { entityKind } from "../../entity.cjs";
import type { PgDialect } from "../dialect.cjs";
import type { PgPreparedQuery, PgQueryResultHKT, PgQueryResultKind, PgSession, PreparedQueryConfig } from "../session.cjs";
import type { PgTable } from "../table.cjs";
import type { SelectResultFields } from "../../query-builders/select.types.cjs";
import { QueryPromise } from "../../query-promise.cjs";
import type { RunnableQuery } from "../../runnable-query.cjs";
import type { Query, SQL, SQLWrapper } from "../../sql/sql.cjs";
import type { Subquery } from "../../subquery.cjs";
import type { SelectedFieldsFlat, SelectedFieldsOrdered } from "./select.types.cjs";
export type PgDeleteWithout<T extends AnyPgDeleteBase, TDynamic extends boolean, K extends keyof T & string> = TDynamic extends true ? T : Omit<PgDeleteBase<T['_']['table'], T['_']['queryResult'], T['_']['returning'], TDynamic, T['_']['excludedMethods'] | K>, T['_']['excludedMethods'] | K>;
export type PgDelete<TTable extends PgTable = PgTable, TQueryResult extends PgQueryResultHKT = PgQueryResultHKT, TReturning extends Record<string, unknown> | undefined = Record<string, unknown> | undefined> = PgDeleteBase<TTable, TQueryResult, TReturning, true, never>;
export interface PgDeleteConfig {
where?: SQL | undefined;
table: PgTable;
returning?: SelectedFieldsOrdered;
withList?: Subquery[];
}
export type PgDeleteReturningAll<T extends AnyPgDeleteBase, TDynamic extends boolean> = PgDeleteWithout<PgDeleteBase<T['_']['table'], T['_']['queryResult'], T['_']['table']['$inferSelect'], TDynamic, T['_']['excludedMethods']>, TDynamic, 'returning'>;
export type PgDeleteReturning<T extends AnyPgDeleteBase, TDynamic extends boolean, TSelectedFields extends SelectedFieldsFlat> = PgDeleteWithout<PgDeleteBase<T['_']['table'], T['_']['queryResult'], SelectResultFields<TSelectedFields>, TDynamic, T['_']['excludedMethods']>, TDynamic, 'returning'>;
export type PgDeletePrepare<T extends AnyPgDeleteBase> = PgPreparedQuery<PreparedQueryConfig & {
execute: T['_']['returning'] extends undefined ? PgQueryResultKind<T['_']['queryResult'], never> : T['_']['returning'][];
}>;
export type PgDeleteDynamic<T extends AnyPgDeleteBase> = PgDelete<T['_']['table'], T['_']['queryResult'], T['_']['returning']>;
export type AnyPgDeleteBase = PgDeleteBase<any, any, any, any, any>;
export interface PgDeleteBase<TTable extends PgTable, TQueryResult extends PgQueryResultHKT, TReturning extends Record<string, unknown> | undefined = undefined, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[]>, RunnableQuery<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[], 'pg'>, SQLWrapper {
readonly _: {
dialect: 'pg';
readonly table: TTable;
readonly queryResult: TQueryResult;
readonly returning: TReturning;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
readonly result: TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[];
};
}
export declare class PgDeleteBase<TTable extends PgTable, TQueryResult extends PgQueryResultHKT, TReturning extends Record<string, unknown> | undefined = undefined, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[]> implements RunnableQuery<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[], 'pg'>, SQLWrapper {
private session;
private dialect;
static readonly [entityKind]: string;
private config;
constructor(table: TTable, session: PgSession, dialect: PgDialect, withList?: Subquery[]);
/**
* Adds a `where` clause to the query.
*
* Calling this method will delete only those rows that fulfill a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/delete}
*
* @param where the `where` clause.
*
* @example
* You can use conditional operators and `sql function` to filter the rows to be deleted.
*
* ```ts
* // Delete all cars with green color
* await db.delete(cars).where(eq(cars.color, 'green'));
* // or
* await db.delete(cars).where(sql`${cars.color} = 'green'`)
* ```
*
* You can logically combine conditional operators with `and()` and `or()` operators:
*
* ```ts
* // Delete all BMW cars with a green color
* await db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
*
* // Delete all cars with the green or blue color
* await db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where: SQL | undefined): PgDeleteWithout<this, TDynamic, 'where'>;
/**
* Adds a `returning` clause to the query.
*
* Calling this method will return the specified fields of the deleted rows. If no fields are specified, all fields will be returned.
*
* See docs: {@link https://orm.drizzle.team/docs/delete#delete-with-return}
*
* @example
* ```ts
* // Delete all cars with the green color and return all fields
* const deletedCars: Car[] = await db.delete(cars)
* .where(eq(cars.color, 'green'))
* .returning();
*
* // Delete all cars with the green color and return only their id and brand fields
* const deletedCarsIdsAndBrands: { id: number, brand: string }[] = await db.delete(cars)
* .where(eq(cars.color, 'green'))
* .returning({ id: cars.id, brand: cars.brand });
* ```
*/
returning(): PgDeleteReturningAll<this, TDynamic>;
returning<TSelectedFields extends SelectedFieldsFlat>(fields: TSelectedFields): PgDeleteReturning<this, TDynamic, TSelectedFields>;
toSQL(): Query;
prepare(name: string): PgDeletePrepare<this>;
private authToken?;
execute: ReturnType<this['prepare']>['execute'];
$dynamic(): PgDeleteDynamic<this>;
}

View File

@ -0,0 +1,100 @@
import { entityKind } from "../../entity.js";
import type { PgDialect } from "../dialect.js";
import type { PgPreparedQuery, PgQueryResultHKT, PgQueryResultKind, PgSession, PreparedQueryConfig } from "../session.js";
import type { PgTable } from "../table.js";
import type { SelectResultFields } from "../../query-builders/select.types.js";
import { QueryPromise } from "../../query-promise.js";
import type { RunnableQuery } from "../../runnable-query.js";
import type { Query, SQL, SQLWrapper } from "../../sql/sql.js";
import type { Subquery } from "../../subquery.js";
import type { SelectedFieldsFlat, SelectedFieldsOrdered } from "./select.types.js";
export type PgDeleteWithout<T extends AnyPgDeleteBase, TDynamic extends boolean, K extends keyof T & string> = TDynamic extends true ? T : Omit<PgDeleteBase<T['_']['table'], T['_']['queryResult'], T['_']['returning'], TDynamic, T['_']['excludedMethods'] | K>, T['_']['excludedMethods'] | K>;
export type PgDelete<TTable extends PgTable = PgTable, TQueryResult extends PgQueryResultHKT = PgQueryResultHKT, TReturning extends Record<string, unknown> | undefined = Record<string, unknown> | undefined> = PgDeleteBase<TTable, TQueryResult, TReturning, true, never>;
export interface PgDeleteConfig {
where?: SQL | undefined;
table: PgTable;
returning?: SelectedFieldsOrdered;
withList?: Subquery[];
}
export type PgDeleteReturningAll<T extends AnyPgDeleteBase, TDynamic extends boolean> = PgDeleteWithout<PgDeleteBase<T['_']['table'], T['_']['queryResult'], T['_']['table']['$inferSelect'], TDynamic, T['_']['excludedMethods']>, TDynamic, 'returning'>;
export type PgDeleteReturning<T extends AnyPgDeleteBase, TDynamic extends boolean, TSelectedFields extends SelectedFieldsFlat> = PgDeleteWithout<PgDeleteBase<T['_']['table'], T['_']['queryResult'], SelectResultFields<TSelectedFields>, TDynamic, T['_']['excludedMethods']>, TDynamic, 'returning'>;
export type PgDeletePrepare<T extends AnyPgDeleteBase> = PgPreparedQuery<PreparedQueryConfig & {
execute: T['_']['returning'] extends undefined ? PgQueryResultKind<T['_']['queryResult'], never> : T['_']['returning'][];
}>;
export type PgDeleteDynamic<T extends AnyPgDeleteBase> = PgDelete<T['_']['table'], T['_']['queryResult'], T['_']['returning']>;
export type AnyPgDeleteBase = PgDeleteBase<any, any, any, any, any>;
export interface PgDeleteBase<TTable extends PgTable, TQueryResult extends PgQueryResultHKT, TReturning extends Record<string, unknown> | undefined = undefined, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[]>, RunnableQuery<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[], 'pg'>, SQLWrapper {
readonly _: {
dialect: 'pg';
readonly table: TTable;
readonly queryResult: TQueryResult;
readonly returning: TReturning;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
readonly result: TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[];
};
}
export declare class PgDeleteBase<TTable extends PgTable, TQueryResult extends PgQueryResultHKT, TReturning extends Record<string, unknown> | undefined = undefined, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[]> implements RunnableQuery<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[], 'pg'>, SQLWrapper {
private session;
private dialect;
static readonly [entityKind]: string;
private config;
constructor(table: TTable, session: PgSession, dialect: PgDialect, withList?: Subquery[]);
/**
* Adds a `where` clause to the query.
*
* Calling this method will delete only those rows that fulfill a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/delete}
*
* @param where the `where` clause.
*
* @example
* You can use conditional operators and `sql function` to filter the rows to be deleted.
*
* ```ts
* // Delete all cars with green color
* await db.delete(cars).where(eq(cars.color, 'green'));
* // or
* await db.delete(cars).where(sql`${cars.color} = 'green'`)
* ```
*
* You can logically combine conditional operators with `and()` and `or()` operators:
*
* ```ts
* // Delete all BMW cars with a green color
* await db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
*
* // Delete all cars with the green or blue color
* await db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where: SQL | undefined): PgDeleteWithout<this, TDynamic, 'where'>;
/**
* Adds a `returning` clause to the query.
*
* Calling this method will return the specified fields of the deleted rows. If no fields are specified, all fields will be returned.
*
* See docs: {@link https://orm.drizzle.team/docs/delete#delete-with-return}
*
* @example
* ```ts
* // Delete all cars with the green color and return all fields
* const deletedCars: Car[] = await db.delete(cars)
* .where(eq(cars.color, 'green'))
* .returning();
*
* // Delete all cars with the green color and return only their id and brand fields
* const deletedCarsIdsAndBrands: { id: number, brand: string }[] = await db.delete(cars)
* .where(eq(cars.color, 'green'))
* .returning({ id: cars.id, brand: cars.brand });
* ```
*/
returning(): PgDeleteReturningAll<this, TDynamic>;
returning<TSelectedFields extends SelectedFieldsFlat>(fields: TSelectedFields): PgDeleteReturning<this, TDynamic, TSelectedFields>;
toSQL(): Query;
prepare(name: string): PgDeletePrepare<this>;
private authToken?;
execute: ReturnType<this['prepare']>['execute'];
$dynamic(): PgDeleteDynamic<this>;
}

View File

@ -0,0 +1,87 @@
import { entityKind } from "../../entity.js";
import { QueryPromise } from "../../query-promise.js";
import { Table } from "../../table.js";
import { tracer } from "../../tracing.js";
import { orderSelectedFields } from "../../utils.js";
class PgDeleteBase extends QueryPromise {
constructor(table, session, dialect, withList) {
super();
this.session = session;
this.dialect = dialect;
this.config = { table, withList };
}
static [entityKind] = "PgDelete";
config;
/**
* Adds a `where` clause to the query.
*
* Calling this method will delete only those rows that fulfill a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/delete}
*
* @param where the `where` clause.
*
* @example
* You can use conditional operators and `sql function` to filter the rows to be deleted.
*
* ```ts
* // Delete all cars with green color
* await db.delete(cars).where(eq(cars.color, 'green'));
* // or
* await db.delete(cars).where(sql`${cars.color} = 'green'`)
* ```
*
* You can logically combine conditional operators with `and()` and `or()` operators:
*
* ```ts
* // Delete all BMW cars with a green color
* await db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
*
* // Delete all cars with the green or blue color
* await db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where) {
this.config.where = where;
return this;
}
returning(fields = this.config.table[Table.Symbol.Columns]) {
this.config.returning = orderSelectedFields(fields);
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildDeleteQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
/** @internal */
_prepare(name) {
return tracer.startActiveSpan("drizzle.prepareQuery", () => {
return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true);
});
}
prepare(name) {
return this._prepare(name);
}
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
execute = (placeholderValues) => {
return tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(placeholderValues, this.authToken);
});
};
$dynamic() {
return this;
}
}
export {
PgDeleteBase
};
//# sourceMappingURL=delete.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,35 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var query_builders_exports = {};
module.exports = __toCommonJS(query_builders_exports);
__reExport(query_builders_exports, require("./delete.cjs"), module.exports);
__reExport(query_builders_exports, require("./insert.cjs"), module.exports);
__reExport(query_builders_exports, require("./query-builder.cjs"), module.exports);
__reExport(query_builders_exports, require("./refresh-materialized-view.cjs"), module.exports);
__reExport(query_builders_exports, require("./select.cjs"), module.exports);
__reExport(query_builders_exports, require("./select.types.cjs"), module.exports);
__reExport(query_builders_exports, require("./update.cjs"), module.exports);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
...require("./delete.cjs"),
...require("./insert.cjs"),
...require("./query-builder.cjs"),
...require("./refresh-materialized-view.cjs"),
...require("./select.cjs"),
...require("./select.types.cjs"),
...require("./update.cjs")
});
//# sourceMappingURL=index.cjs.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/pg-core/query-builders/index.ts"],"sourcesContent":["export * from './delete.ts';\nexport * from './insert.ts';\nexport * from './query-builder.ts';\nexport * from './refresh-materialized-view.ts';\nexport * from './select.ts';\nexport * from './select.types.ts';\nexport * from './update.ts';\n"],"mappings":";;;;;;;;;;;;;;;AAAA;AAAA;AAAA,mCAAc,wBAAd;AACA,mCAAc,wBADd;AAEA,mCAAc,+BAFd;AAGA,mCAAc,2CAHd;AAIA,mCAAc,wBAJd;AAKA,mCAAc,8BALd;AAMA,mCAAc,wBANd;","names":[]}

View File

@ -0,0 +1,7 @@
export * from "./delete.cjs";
export * from "./insert.cjs";
export * from "./query-builder.cjs";
export * from "./refresh-materialized-view.cjs";
export * from "./select.cjs";
export * from "./select.types.cjs";
export * from "./update.cjs";

View File

@ -0,0 +1,7 @@
export * from "./delete.js";
export * from "./insert.js";
export * from "./query-builder.js";
export * from "./refresh-materialized-view.js";
export * from "./select.js";
export * from "./select.types.js";
export * from "./update.js";

View File

@ -0,0 +1,8 @@
export * from "./delete.js";
export * from "./insert.js";
export * from "./query-builder.js";
export * from "./refresh-materialized-view.js";
export * from "./select.js";
export * from "./select.types.js";
export * from "./update.js";
//# sourceMappingURL=index.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/pg-core/query-builders/index.ts"],"sourcesContent":["export * from './delete.ts';\nexport * from './insert.ts';\nexport * from './query-builder.ts';\nexport * from './refresh-materialized-view.ts';\nexport * from './select.ts';\nexport * from './select.types.ts';\nexport * from './update.ts';\n"],"mappings":"AAAA,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;","names":[]}

View File

@ -0,0 +1,212 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var insert_exports = {};
__export(insert_exports, {
PgInsertBase: () => PgInsertBase,
PgInsertBuilder: () => PgInsertBuilder
});
module.exports = __toCommonJS(insert_exports);
var import_entity = require("../../entity.cjs");
var import_query_promise = require("../../query-promise.cjs");
var import_sql = require("../../sql/sql.cjs");
var import_table = require("../../table.cjs");
var import_tracing = require("../../tracing.cjs");
var import_utils = require("../../utils.cjs");
var import_query_builder = require("./query-builder.cjs");
class PgInsertBuilder {
constructor(table, session, dialect, withList, overridingSystemValue_) {
this.table = table;
this.session = session;
this.dialect = dialect;
this.withList = withList;
this.overridingSystemValue_ = overridingSystemValue_;
}
static [import_entity.entityKind] = "PgInsertBuilder";
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
overridingSystemValue() {
this.overridingSystemValue_ = true;
return this;
}
values(values) {
values = Array.isArray(values) ? values : [values];
if (values.length === 0) {
throw new Error("values() must be called with at least one value");
}
const mappedValues = values.map((entry) => {
const result = {};
const cols = this.table[import_table.Table.Symbol.Columns];
for (const colKey of Object.keys(entry)) {
const colValue = entry[colKey];
result[colKey] = (0, import_entity.is)(colValue, import_sql.SQL) ? colValue : new import_sql.Param(colValue, cols[colKey]);
}
return result;
});
return new PgInsertBase(
this.table,
mappedValues,
this.session,
this.dialect,
this.withList,
false,
this.overridingSystemValue_
).setToken(this.authToken);
}
select(selectQuery) {
const select = typeof selectQuery === "function" ? selectQuery(new import_query_builder.QueryBuilder()) : selectQuery;
if (!(0, import_entity.is)(select, import_sql.SQL) && !(0, import_utils.haveSameKeys)(this.table[import_table.Columns], select._.selectedFields)) {
throw new Error(
"Insert select error: selected fields are not the same or are in a different order compared to the table definition"
);
}
return new PgInsertBase(this.table, select, this.session, this.dialect, this.withList, true);
}
}
class PgInsertBase extends import_query_promise.QueryPromise {
constructor(table, values, session, dialect, withList, select, overridingSystemValue_) {
super();
this.session = session;
this.dialect = dialect;
this.config = { table, values, withList, select, overridingSystemValue_ };
}
static [import_entity.entityKind] = "PgInsert";
config;
returning(fields = this.config.table[import_table.Table.Symbol.Columns]) {
this.config.returning = (0, import_utils.orderSelectedFields)(fields);
return this;
}
/**
* Adds an `on conflict do nothing` clause to the query.
*
* Calling this method simply avoids inserting a row as its alternative action.
*
* See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}
*
* @param config The `target` and `where` clauses.
*
* @example
* ```ts
* // Insert one row and cancel the insert if there's a conflict
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoNothing();
*
* // Explicitly specify conflict target
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoNothing({ target: cars.id });
* ```
*/
onConflictDoNothing(config = {}) {
if (config.target === void 0) {
this.config.onConflict = import_sql.sql`do nothing`;
} else {
let targetColumn = "";
targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target));
const whereSql = config.where ? import_sql.sql` where ${config.where}` : void 0;
this.config.onConflict = import_sql.sql`(${import_sql.sql.raw(targetColumn)})${whereSql} do nothing`;
}
return this;
}
/**
* Adds an `on conflict do update` clause to the query.
*
* Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.
*
* See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}
*
* @param config The `target`, `set` and `where` clauses.
*
* @example
* ```ts
* // Update the row if there's a conflict
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoUpdate({
* target: cars.id,
* set: { brand: 'Porsche' }
* });
*
* // Upsert with 'where' clause
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoUpdate({
* target: cars.id,
* set: { brand: 'newBMW' },
* targetWhere: sql`${cars.createdAt} > '2023-01-01'::date`,
* });
* ```
*/
onConflictDoUpdate(config) {
if (config.where && (config.targetWhere || config.setWhere)) {
throw new Error(
'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.'
);
}
const whereSql = config.where ? import_sql.sql` where ${config.where}` : void 0;
const targetWhereSql = config.targetWhere ? import_sql.sql` where ${config.targetWhere}` : void 0;
const setWhereSql = config.setWhere ? import_sql.sql` where ${config.setWhere}` : void 0;
const setSql = this.dialect.buildUpdateSet(this.config.table, (0, import_utils.mapUpdateSet)(this.config.table, config.set));
let targetColumn = "";
targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target));
this.config.onConflict = import_sql.sql`(${import_sql.sql.raw(targetColumn)})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`;
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildInsertQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
/** @internal */
_prepare(name) {
return import_tracing.tracer.startActiveSpan("drizzle.prepareQuery", () => {
return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true);
});
}
prepare(name) {
return this._prepare(name);
}
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
execute = (placeholderValues) => {
return import_tracing.tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(placeholderValues, this.authToken);
});
};
$dynamic() {
return this;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
PgInsertBase,
PgInsertBuilder
});
//# sourceMappingURL=insert.cjs.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,173 @@
import { entityKind } from "../../entity.cjs";
import type { PgDialect } from "../dialect.cjs";
import type { IndexColumn } from "../indexes.cjs";
import type { PgPreparedQuery, PgQueryResultHKT, PgQueryResultKind, PgSession, PreparedQueryConfig } from "../session.cjs";
import type { PgTable, TableConfig } from "../table.cjs";
import type { TypedQueryBuilder } from "../../query-builders/query-builder.cjs";
import type { SelectResultFields } from "../../query-builders/select.types.cjs";
import { QueryPromise } from "../../query-promise.cjs";
import type { RunnableQuery } from "../../runnable-query.cjs";
import type { Placeholder, Query, SQLWrapper } from "../../sql/sql.cjs";
import { Param, SQL } from "../../sql/sql.cjs";
import type { Subquery } from "../../subquery.cjs";
import type { InferInsertModel } from "../../table.cjs";
import type { AnyPgColumn } from "../columns/common.cjs";
import { QueryBuilder } from "./query-builder.cjs";
import type { SelectedFieldsFlat, SelectedFieldsOrdered } from "./select.types.cjs";
import type { PgUpdateSetSource } from "./update.cjs";
export interface PgInsertConfig<TTable extends PgTable = PgTable> {
table: TTable;
values: Record<string, Param | SQL>[] | PgInsertSelectQueryBuilder<TTable> | SQL;
withList?: Subquery[];
onConflict?: SQL;
returning?: SelectedFieldsOrdered;
select?: boolean;
overridingSystemValue_?: boolean;
}
export type PgInsertValue<TTable extends PgTable<TableConfig>, OverrideT extends boolean = false> = {
[Key in keyof InferInsertModel<TTable, {
dbColumnNames: false;
override: OverrideT;
}>]: InferInsertModel<TTable, {
dbColumnNames: false;
override: OverrideT;
}>[Key] | SQL | Placeholder;
} & {};
export type PgInsertSelectQueryBuilder<TTable extends PgTable> = TypedQueryBuilder<{
[K in keyof TTable['$inferInsert']]: AnyPgColumn | SQL | SQL.Aliased | TTable['$inferInsert'][K];
}>;
export declare class PgInsertBuilder<TTable extends PgTable, TQueryResult extends PgQueryResultHKT, OverrideT extends boolean = false> {
private table;
private session;
private dialect;
private withList?;
private overridingSystemValue_?;
static readonly [entityKind]: string;
constructor(table: TTable, session: PgSession, dialect: PgDialect, withList?: Subquery[] | undefined, overridingSystemValue_?: boolean | undefined);
private authToken?;
overridingSystemValue(): Omit<PgInsertBuilder<TTable, TQueryResult, true>, 'overridingSystemValue'>;
values(value: PgInsertValue<TTable, OverrideT>): PgInsertBase<TTable, TQueryResult>;
values(values: PgInsertValue<TTable, OverrideT>[]): PgInsertBase<TTable, TQueryResult>;
select(selectQuery: (qb: QueryBuilder) => PgInsertSelectQueryBuilder<TTable>): PgInsertBase<TTable, TQueryResult>;
select(selectQuery: (qb: QueryBuilder) => SQL): PgInsertBase<TTable, TQueryResult>;
select(selectQuery: SQL): PgInsertBase<TTable, TQueryResult>;
select(selectQuery: PgInsertSelectQueryBuilder<TTable>): PgInsertBase<TTable, TQueryResult>;
}
export type PgInsertWithout<T extends AnyPgInsert, TDynamic extends boolean, K extends keyof T & string> = TDynamic extends true ? T : Omit<PgInsertBase<T['_']['table'], T['_']['queryResult'], T['_']['returning'], TDynamic, T['_']['excludedMethods'] | K>, T['_']['excludedMethods'] | K>;
export type PgInsertReturning<T extends AnyPgInsert, TDynamic extends boolean, TSelectedFields extends SelectedFieldsFlat> = PgInsertBase<T['_']['table'], T['_']['queryResult'], SelectResultFields<TSelectedFields>, TDynamic, T['_']['excludedMethods']>;
export type PgInsertReturningAll<T extends AnyPgInsert, TDynamic extends boolean> = PgInsertBase<T['_']['table'], T['_']['queryResult'], T['_']['table']['$inferSelect'], TDynamic, T['_']['excludedMethods']>;
export interface PgInsertOnConflictDoUpdateConfig<T extends AnyPgInsert> {
target: IndexColumn | IndexColumn[];
/** @deprecated use either `targetWhere` or `setWhere` */
where?: SQL;
targetWhere?: SQL;
setWhere?: SQL;
set: PgUpdateSetSource<T['_']['table']>;
}
export type PgInsertPrepare<T extends AnyPgInsert> = PgPreparedQuery<PreparedQueryConfig & {
execute: T['_']['returning'] extends undefined ? PgQueryResultKind<T['_']['queryResult'], never> : T['_']['returning'][];
}>;
export type PgInsertDynamic<T extends AnyPgInsert> = PgInsert<T['_']['table'], T['_']['queryResult'], T['_']['returning']>;
export type AnyPgInsert = PgInsertBase<any, any, any, any, any>;
export type PgInsert<TTable extends PgTable = PgTable, TQueryResult extends PgQueryResultHKT = PgQueryResultHKT, TReturning extends Record<string, unknown> | undefined = Record<string, unknown> | undefined> = PgInsertBase<TTable, TQueryResult, TReturning, true, never>;
export interface PgInsertBase<TTable extends PgTable, TQueryResult extends PgQueryResultHKT, TReturning extends Record<string, unknown> | undefined = undefined, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[]>, RunnableQuery<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[], 'pg'>, SQLWrapper {
readonly _: {
readonly dialect: 'pg';
readonly table: TTable;
readonly queryResult: TQueryResult;
readonly returning: TReturning;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
readonly result: TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[];
};
}
export declare class PgInsertBase<TTable extends PgTable, TQueryResult extends PgQueryResultHKT, TReturning extends Record<string, unknown> | undefined = undefined, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[]> implements RunnableQuery<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[], 'pg'>, SQLWrapper {
private session;
private dialect;
static readonly [entityKind]: string;
private config;
constructor(table: TTable, values: PgInsertConfig['values'], session: PgSession, dialect: PgDialect, withList?: Subquery[], select?: boolean, overridingSystemValue_?: boolean);
/**
* Adds a `returning` clause to the query.
*
* Calling this method will return the specified fields of the inserted rows. If no fields are specified, all fields will be returned.
*
* See docs: {@link https://orm.drizzle.team/docs/insert#insert-returning}
*
* @example
* ```ts
* // Insert one row and return all fields
* const insertedCar: Car[] = await db.insert(cars)
* .values({ brand: 'BMW' })
* .returning();
*
* // Insert one row and return only the id
* const insertedCarId: { id: number }[] = await db.insert(cars)
* .values({ brand: 'BMW' })
* .returning({ id: cars.id });
* ```
*/
returning(): PgInsertWithout<PgInsertReturningAll<this, TDynamic>, TDynamic, 'returning'>;
returning<TSelectedFields extends SelectedFieldsFlat>(fields: TSelectedFields): PgInsertWithout<PgInsertReturning<this, TDynamic, TSelectedFields>, TDynamic, 'returning'>;
/**
* Adds an `on conflict do nothing` clause to the query.
*
* Calling this method simply avoids inserting a row as its alternative action.
*
* See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}
*
* @param config The `target` and `where` clauses.
*
* @example
* ```ts
* // Insert one row and cancel the insert if there's a conflict
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoNothing();
*
* // Explicitly specify conflict target
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoNothing({ target: cars.id });
* ```
*/
onConflictDoNothing(config?: {
target?: IndexColumn | IndexColumn[];
where?: SQL;
}): PgInsertWithout<this, TDynamic, 'onConflictDoNothing' | 'onConflictDoUpdate'>;
/**
* Adds an `on conflict do update` clause to the query.
*
* Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.
*
* See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}
*
* @param config The `target`, `set` and `where` clauses.
*
* @example
* ```ts
* // Update the row if there's a conflict
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoUpdate({
* target: cars.id,
* set: { brand: 'Porsche' }
* });
*
* // Upsert with 'where' clause
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoUpdate({
* target: cars.id,
* set: { brand: 'newBMW' },
* targetWhere: sql`${cars.createdAt} > '2023-01-01'::date`,
* });
* ```
*/
onConflictDoUpdate(config: PgInsertOnConflictDoUpdateConfig<this>): PgInsertWithout<this, TDynamic, 'onConflictDoNothing' | 'onConflictDoUpdate'>;
toSQL(): Query;
prepare(name: string): PgInsertPrepare<this>;
private authToken?;
execute: ReturnType<this['prepare']>['execute'];
$dynamic(): PgInsertDynamic<this>;
}

View File

@ -0,0 +1,173 @@
import { entityKind } from "../../entity.js";
import type { PgDialect } from "../dialect.js";
import type { IndexColumn } from "../indexes.js";
import type { PgPreparedQuery, PgQueryResultHKT, PgQueryResultKind, PgSession, PreparedQueryConfig } from "../session.js";
import type { PgTable, TableConfig } from "../table.js";
import type { TypedQueryBuilder } from "../../query-builders/query-builder.js";
import type { SelectResultFields } from "../../query-builders/select.types.js";
import { QueryPromise } from "../../query-promise.js";
import type { RunnableQuery } from "../../runnable-query.js";
import type { Placeholder, Query, SQLWrapper } from "../../sql/sql.js";
import { Param, SQL } from "../../sql/sql.js";
import type { Subquery } from "../../subquery.js";
import type { InferInsertModel } from "../../table.js";
import type { AnyPgColumn } from "../columns/common.js";
import { QueryBuilder } from "./query-builder.js";
import type { SelectedFieldsFlat, SelectedFieldsOrdered } from "./select.types.js";
import type { PgUpdateSetSource } from "./update.js";
export interface PgInsertConfig<TTable extends PgTable = PgTable> {
table: TTable;
values: Record<string, Param | SQL>[] | PgInsertSelectQueryBuilder<TTable> | SQL;
withList?: Subquery[];
onConflict?: SQL;
returning?: SelectedFieldsOrdered;
select?: boolean;
overridingSystemValue_?: boolean;
}
export type PgInsertValue<TTable extends PgTable<TableConfig>, OverrideT extends boolean = false> = {
[Key in keyof InferInsertModel<TTable, {
dbColumnNames: false;
override: OverrideT;
}>]: InferInsertModel<TTable, {
dbColumnNames: false;
override: OverrideT;
}>[Key] | SQL | Placeholder;
} & {};
export type PgInsertSelectQueryBuilder<TTable extends PgTable> = TypedQueryBuilder<{
[K in keyof TTable['$inferInsert']]: AnyPgColumn | SQL | SQL.Aliased | TTable['$inferInsert'][K];
}>;
export declare class PgInsertBuilder<TTable extends PgTable, TQueryResult extends PgQueryResultHKT, OverrideT extends boolean = false> {
private table;
private session;
private dialect;
private withList?;
private overridingSystemValue_?;
static readonly [entityKind]: string;
constructor(table: TTable, session: PgSession, dialect: PgDialect, withList?: Subquery[] | undefined, overridingSystemValue_?: boolean | undefined);
private authToken?;
overridingSystemValue(): Omit<PgInsertBuilder<TTable, TQueryResult, true>, 'overridingSystemValue'>;
values(value: PgInsertValue<TTable, OverrideT>): PgInsertBase<TTable, TQueryResult>;
values(values: PgInsertValue<TTable, OverrideT>[]): PgInsertBase<TTable, TQueryResult>;
select(selectQuery: (qb: QueryBuilder) => PgInsertSelectQueryBuilder<TTable>): PgInsertBase<TTable, TQueryResult>;
select(selectQuery: (qb: QueryBuilder) => SQL): PgInsertBase<TTable, TQueryResult>;
select(selectQuery: SQL): PgInsertBase<TTable, TQueryResult>;
select(selectQuery: PgInsertSelectQueryBuilder<TTable>): PgInsertBase<TTable, TQueryResult>;
}
export type PgInsertWithout<T extends AnyPgInsert, TDynamic extends boolean, K extends keyof T & string> = TDynamic extends true ? T : Omit<PgInsertBase<T['_']['table'], T['_']['queryResult'], T['_']['returning'], TDynamic, T['_']['excludedMethods'] | K>, T['_']['excludedMethods'] | K>;
export type PgInsertReturning<T extends AnyPgInsert, TDynamic extends boolean, TSelectedFields extends SelectedFieldsFlat> = PgInsertBase<T['_']['table'], T['_']['queryResult'], SelectResultFields<TSelectedFields>, TDynamic, T['_']['excludedMethods']>;
export type PgInsertReturningAll<T extends AnyPgInsert, TDynamic extends boolean> = PgInsertBase<T['_']['table'], T['_']['queryResult'], T['_']['table']['$inferSelect'], TDynamic, T['_']['excludedMethods']>;
export interface PgInsertOnConflictDoUpdateConfig<T extends AnyPgInsert> {
target: IndexColumn | IndexColumn[];
/** @deprecated use either `targetWhere` or `setWhere` */
where?: SQL;
targetWhere?: SQL;
setWhere?: SQL;
set: PgUpdateSetSource<T['_']['table']>;
}
export type PgInsertPrepare<T extends AnyPgInsert> = PgPreparedQuery<PreparedQueryConfig & {
execute: T['_']['returning'] extends undefined ? PgQueryResultKind<T['_']['queryResult'], never> : T['_']['returning'][];
}>;
export type PgInsertDynamic<T extends AnyPgInsert> = PgInsert<T['_']['table'], T['_']['queryResult'], T['_']['returning']>;
export type AnyPgInsert = PgInsertBase<any, any, any, any, any>;
export type PgInsert<TTable extends PgTable = PgTable, TQueryResult extends PgQueryResultHKT = PgQueryResultHKT, TReturning extends Record<string, unknown> | undefined = Record<string, unknown> | undefined> = PgInsertBase<TTable, TQueryResult, TReturning, true, never>;
export interface PgInsertBase<TTable extends PgTable, TQueryResult extends PgQueryResultHKT, TReturning extends Record<string, unknown> | undefined = undefined, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[]>, RunnableQuery<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[], 'pg'>, SQLWrapper {
readonly _: {
readonly dialect: 'pg';
readonly table: TTable;
readonly queryResult: TQueryResult;
readonly returning: TReturning;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
readonly result: TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[];
};
}
export declare class PgInsertBase<TTable extends PgTable, TQueryResult extends PgQueryResultHKT, TReturning extends Record<string, unknown> | undefined = undefined, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[]> implements RunnableQuery<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[], 'pg'>, SQLWrapper {
private session;
private dialect;
static readonly [entityKind]: string;
private config;
constructor(table: TTable, values: PgInsertConfig['values'], session: PgSession, dialect: PgDialect, withList?: Subquery[], select?: boolean, overridingSystemValue_?: boolean);
/**
* Adds a `returning` clause to the query.
*
* Calling this method will return the specified fields of the inserted rows. If no fields are specified, all fields will be returned.
*
* See docs: {@link https://orm.drizzle.team/docs/insert#insert-returning}
*
* @example
* ```ts
* // Insert one row and return all fields
* const insertedCar: Car[] = await db.insert(cars)
* .values({ brand: 'BMW' })
* .returning();
*
* // Insert one row and return only the id
* const insertedCarId: { id: number }[] = await db.insert(cars)
* .values({ brand: 'BMW' })
* .returning({ id: cars.id });
* ```
*/
returning(): PgInsertWithout<PgInsertReturningAll<this, TDynamic>, TDynamic, 'returning'>;
returning<TSelectedFields extends SelectedFieldsFlat>(fields: TSelectedFields): PgInsertWithout<PgInsertReturning<this, TDynamic, TSelectedFields>, TDynamic, 'returning'>;
/**
* Adds an `on conflict do nothing` clause to the query.
*
* Calling this method simply avoids inserting a row as its alternative action.
*
* See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}
*
* @param config The `target` and `where` clauses.
*
* @example
* ```ts
* // Insert one row and cancel the insert if there's a conflict
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoNothing();
*
* // Explicitly specify conflict target
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoNothing({ target: cars.id });
* ```
*/
onConflictDoNothing(config?: {
target?: IndexColumn | IndexColumn[];
where?: SQL;
}): PgInsertWithout<this, TDynamic, 'onConflictDoNothing' | 'onConflictDoUpdate'>;
/**
* Adds an `on conflict do update` clause to the query.
*
* Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.
*
* See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}
*
* @param config The `target`, `set` and `where` clauses.
*
* @example
* ```ts
* // Update the row if there's a conflict
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoUpdate({
* target: cars.id,
* set: { brand: 'Porsche' }
* });
*
* // Upsert with 'where' clause
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoUpdate({
* target: cars.id,
* set: { brand: 'newBMW' },
* targetWhere: sql`${cars.createdAt} > '2023-01-01'::date`,
* });
* ```
*/
onConflictDoUpdate(config: PgInsertOnConflictDoUpdateConfig<this>): PgInsertWithout<this, TDynamic, 'onConflictDoNothing' | 'onConflictDoUpdate'>;
toSQL(): Query;
prepare(name: string): PgInsertPrepare<this>;
private authToken?;
execute: ReturnType<this['prepare']>['execute'];
$dynamic(): PgInsertDynamic<this>;
}

View File

@ -0,0 +1,187 @@
import { entityKind, is } from "../../entity.js";
import { QueryPromise } from "../../query-promise.js";
import { Param, SQL, sql } from "../../sql/sql.js";
import { Columns, Table } from "../../table.js";
import { tracer } from "../../tracing.js";
import { haveSameKeys, mapUpdateSet, orderSelectedFields } from "../../utils.js";
import { QueryBuilder } from "./query-builder.js";
class PgInsertBuilder {
constructor(table, session, dialect, withList, overridingSystemValue_) {
this.table = table;
this.session = session;
this.dialect = dialect;
this.withList = withList;
this.overridingSystemValue_ = overridingSystemValue_;
}
static [entityKind] = "PgInsertBuilder";
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
overridingSystemValue() {
this.overridingSystemValue_ = true;
return this;
}
values(values) {
values = Array.isArray(values) ? values : [values];
if (values.length === 0) {
throw new Error("values() must be called with at least one value");
}
const mappedValues = values.map((entry) => {
const result = {};
const cols = this.table[Table.Symbol.Columns];
for (const colKey of Object.keys(entry)) {
const colValue = entry[colKey];
result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
}
return result;
});
return new PgInsertBase(
this.table,
mappedValues,
this.session,
this.dialect,
this.withList,
false,
this.overridingSystemValue_
).setToken(this.authToken);
}
select(selectQuery) {
const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder()) : selectQuery;
if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) {
throw new Error(
"Insert select error: selected fields are not the same or are in a different order compared to the table definition"
);
}
return new PgInsertBase(this.table, select, this.session, this.dialect, this.withList, true);
}
}
class PgInsertBase extends QueryPromise {
constructor(table, values, session, dialect, withList, select, overridingSystemValue_) {
super();
this.session = session;
this.dialect = dialect;
this.config = { table, values, withList, select, overridingSystemValue_ };
}
static [entityKind] = "PgInsert";
config;
returning(fields = this.config.table[Table.Symbol.Columns]) {
this.config.returning = orderSelectedFields(fields);
return this;
}
/**
* Adds an `on conflict do nothing` clause to the query.
*
* Calling this method simply avoids inserting a row as its alternative action.
*
* See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}
*
* @param config The `target` and `where` clauses.
*
* @example
* ```ts
* // Insert one row and cancel the insert if there's a conflict
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoNothing();
*
* // Explicitly specify conflict target
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoNothing({ target: cars.id });
* ```
*/
onConflictDoNothing(config = {}) {
if (config.target === void 0) {
this.config.onConflict = sql`do nothing`;
} else {
let targetColumn = "";
targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target));
const whereSql = config.where ? sql` where ${config.where}` : void 0;
this.config.onConflict = sql`(${sql.raw(targetColumn)})${whereSql} do nothing`;
}
return this;
}
/**
* Adds an `on conflict do update` clause to the query.
*
* Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.
*
* See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}
*
* @param config The `target`, `set` and `where` clauses.
*
* @example
* ```ts
* // Update the row if there's a conflict
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoUpdate({
* target: cars.id,
* set: { brand: 'Porsche' }
* });
*
* // Upsert with 'where' clause
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoUpdate({
* target: cars.id,
* set: { brand: 'newBMW' },
* targetWhere: sql`${cars.createdAt} > '2023-01-01'::date`,
* });
* ```
*/
onConflictDoUpdate(config) {
if (config.where && (config.targetWhere || config.setWhere)) {
throw new Error(
'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.'
);
}
const whereSql = config.where ? sql` where ${config.where}` : void 0;
const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : void 0;
const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : void 0;
const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
let targetColumn = "";
targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target));
this.config.onConflict = sql`(${sql.raw(targetColumn)})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`;
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildInsertQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
/** @internal */
_prepare(name) {
return tracer.startActiveSpan("drizzle.prepareQuery", () => {
return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true);
});
}
prepare(name) {
return this._prepare(name);
}
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
execute = (placeholderValues) => {
return tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(placeholderValues, this.authToken);
});
};
$dynamic() {
return this;
}
}
export {
PgInsertBase,
PgInsertBuilder
};
//# sourceMappingURL=insert.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,114 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var query_builder_exports = {};
__export(query_builder_exports, {
QueryBuilder: () => QueryBuilder
});
module.exports = __toCommonJS(query_builder_exports);
var import_entity = require("../../entity.cjs");
var import_dialect = require("../dialect.cjs");
var import_selection_proxy = require("../../selection-proxy.cjs");
var import_subquery = require("../../subquery.cjs");
var import_select = require("./select.cjs");
class QueryBuilder {
static [import_entity.entityKind] = "PgQueryBuilder";
dialect;
dialectConfig;
constructor(dialect) {
this.dialect = (0, import_entity.is)(dialect, import_dialect.PgDialect) ? dialect : void 0;
this.dialectConfig = (0, import_entity.is)(dialect, import_dialect.PgDialect) ? void 0 : dialect;
}
$with(alias) {
const queryBuilder = this;
return {
as(qb) {
if (typeof qb === "function") {
qb = qb(queryBuilder);
}
return new Proxy(
new import_subquery.WithSubquery(qb.getSQL(), qb.getSelectedFields(), alias, true),
new import_selection_proxy.SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
);
}
};
}
with(...queries) {
const self = this;
function select(fields) {
return new import_select.PgSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: self.getDialect(),
withList: queries
});
}
function selectDistinct(fields) {
return new import_select.PgSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: self.getDialect(),
distinct: true
});
}
function selectDistinctOn(on, fields) {
return new import_select.PgSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: self.getDialect(),
distinct: { on }
});
}
return { select, selectDistinct, selectDistinctOn };
}
select(fields) {
return new import_select.PgSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: this.getDialect()
});
}
selectDistinct(fields) {
return new import_select.PgSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: this.getDialect(),
distinct: true
});
}
selectDistinctOn(on, fields) {
return new import_select.PgSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: this.getDialect(),
distinct: { on }
});
}
// Lazy load dialect to avoid circular dependency
getDialect() {
if (!this.dialect) {
this.dialect = new import_dialect.PgDialect(this.dialectConfig);
}
return this.dialect;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
QueryBuilder
});
//# sourceMappingURL=query-builder.cjs.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,40 @@
import { entityKind } from "../../entity.cjs";
import type { PgDialectConfig } from "../dialect.cjs";
import { PgDialect } from "../dialect.cjs";
import type { TypedQueryBuilder } from "../../query-builders/query-builder.cjs";
import type { ColumnsSelection, SQLWrapper } from "../../sql/sql.cjs";
import { WithSubquery } from "../../subquery.cjs";
import type { PgColumn } from "../columns/index.cjs";
import type { WithSubqueryWithSelection } from "../subquery.cjs";
import { PgSelectBuilder } from "./select.cjs";
import type { SelectedFields } from "./select.types.cjs";
export declare class QueryBuilder {
static readonly [entityKind]: string;
private dialect;
private dialectConfig;
constructor(dialect?: PgDialect | PgDialectConfig);
$with<TAlias extends string>(alias: TAlias): {
as<TSelection extends ColumnsSelection>(qb: TypedQueryBuilder<TSelection> | ((qb: QueryBuilder) => TypedQueryBuilder<TSelection>)): WithSubqueryWithSelection<TSelection, TAlias>;
};
with(...queries: WithSubquery[]): {
select: {
(): PgSelectBuilder<undefined, "qb">;
<TSelection extends SelectedFields>(fields: TSelection): PgSelectBuilder<TSelection, "qb">;
};
selectDistinct: {
(): PgSelectBuilder<undefined, "qb">;
<TSelection extends SelectedFields>(fields: TSelection): PgSelectBuilder<TSelection, "qb">;
};
selectDistinctOn: {
(on: (PgColumn | SQLWrapper)[]): PgSelectBuilder<undefined, "qb">;
<TSelection extends SelectedFields>(on: (PgColumn | SQLWrapper)[], fields: TSelection): PgSelectBuilder<TSelection, "qb">;
};
};
select(): PgSelectBuilder<undefined, 'qb'>;
select<TSelection extends SelectedFields>(fields: TSelection): PgSelectBuilder<TSelection, 'qb'>;
selectDistinct(): PgSelectBuilder<undefined>;
selectDistinct<TSelection extends SelectedFields>(fields: TSelection): PgSelectBuilder<TSelection>;
selectDistinctOn(on: (PgColumn | SQLWrapper)[]): PgSelectBuilder<undefined>;
selectDistinctOn<TSelection extends SelectedFields>(on: (PgColumn | SQLWrapper)[], fields: TSelection): PgSelectBuilder<TSelection>;
private getDialect;
}

View File

@ -0,0 +1,40 @@
import { entityKind } from "../../entity.js";
import type { PgDialectConfig } from "../dialect.js";
import { PgDialect } from "../dialect.js";
import type { TypedQueryBuilder } from "../../query-builders/query-builder.js";
import type { ColumnsSelection, SQLWrapper } from "../../sql/sql.js";
import { WithSubquery } from "../../subquery.js";
import type { PgColumn } from "../columns/index.js";
import type { WithSubqueryWithSelection } from "../subquery.js";
import { PgSelectBuilder } from "./select.js";
import type { SelectedFields } from "./select.types.js";
export declare class QueryBuilder {
static readonly [entityKind]: string;
private dialect;
private dialectConfig;
constructor(dialect?: PgDialect | PgDialectConfig);
$with<TAlias extends string>(alias: TAlias): {
as<TSelection extends ColumnsSelection>(qb: TypedQueryBuilder<TSelection> | ((qb: QueryBuilder) => TypedQueryBuilder<TSelection>)): WithSubqueryWithSelection<TSelection, TAlias>;
};
with(...queries: WithSubquery[]): {
select: {
(): PgSelectBuilder<undefined, "qb">;
<TSelection extends SelectedFields>(fields: TSelection): PgSelectBuilder<TSelection, "qb">;
};
selectDistinct: {
(): PgSelectBuilder<undefined, "qb">;
<TSelection extends SelectedFields>(fields: TSelection): PgSelectBuilder<TSelection, "qb">;
};
selectDistinctOn: {
(on: (PgColumn | SQLWrapper)[]): PgSelectBuilder<undefined, "qb">;
<TSelection extends SelectedFields>(on: (PgColumn | SQLWrapper)[], fields: TSelection): PgSelectBuilder<TSelection, "qb">;
};
};
select(): PgSelectBuilder<undefined, 'qb'>;
select<TSelection extends SelectedFields>(fields: TSelection): PgSelectBuilder<TSelection, 'qb'>;
selectDistinct(): PgSelectBuilder<undefined>;
selectDistinct<TSelection extends SelectedFields>(fields: TSelection): PgSelectBuilder<TSelection>;
selectDistinctOn(on: (PgColumn | SQLWrapper)[]): PgSelectBuilder<undefined>;
selectDistinctOn<TSelection extends SelectedFields>(on: (PgColumn | SQLWrapper)[], fields: TSelection): PgSelectBuilder<TSelection>;
private getDialect;
}

View File

@ -0,0 +1,90 @@
import { entityKind, is } from "../../entity.js";
import { PgDialect } from "../dialect.js";
import { SelectionProxyHandler } from "../../selection-proxy.js";
import { WithSubquery } from "../../subquery.js";
import { PgSelectBuilder } from "./select.js";
class QueryBuilder {
static [entityKind] = "PgQueryBuilder";
dialect;
dialectConfig;
constructor(dialect) {
this.dialect = is(dialect, PgDialect) ? dialect : void 0;
this.dialectConfig = is(dialect, PgDialect) ? void 0 : dialect;
}
$with(alias) {
const queryBuilder = this;
return {
as(qb) {
if (typeof qb === "function") {
qb = qb(queryBuilder);
}
return new Proxy(
new WithSubquery(qb.getSQL(), qb.getSelectedFields(), alias, true),
new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
);
}
};
}
with(...queries) {
const self = this;
function select(fields) {
return new PgSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: self.getDialect(),
withList: queries
});
}
function selectDistinct(fields) {
return new PgSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: self.getDialect(),
distinct: true
});
}
function selectDistinctOn(on, fields) {
return new PgSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: self.getDialect(),
distinct: { on }
});
}
return { select, selectDistinct, selectDistinctOn };
}
select(fields) {
return new PgSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: this.getDialect()
});
}
selectDistinct(fields) {
return new PgSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: this.getDialect(),
distinct: true
});
}
selectDistinctOn(on, fields) {
return new PgSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: this.getDialect(),
distinct: { on }
});
}
// Lazy load dialect to avoid circular dependency
getDialect() {
if (!this.dialect) {
this.dialect = new PgDialect(this.dialectConfig);
}
return this.dialect;
}
}
export {
QueryBuilder
};
//# sourceMappingURL=query-builder.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,145 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var query_exports = {};
__export(query_exports, {
PgRelationalQuery: () => PgRelationalQuery,
RelationalQueryBuilder: () => RelationalQueryBuilder
});
module.exports = __toCommonJS(query_exports);
var import_entity = require("../../entity.cjs");
var import_query_promise = require("../../query-promise.cjs");
var import_relations = require("../../relations.cjs");
var import_tracing = require("../../tracing.cjs");
class RelationalQueryBuilder {
constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session) {
this.fullSchema = fullSchema;
this.schema = schema;
this.tableNamesMap = tableNamesMap;
this.table = table;
this.tableConfig = tableConfig;
this.dialect = dialect;
this.session = session;
}
static [import_entity.entityKind] = "PgRelationalQueryBuilder";
findMany(config) {
return new PgRelationalQuery(
this.fullSchema,
this.schema,
this.tableNamesMap,
this.table,
this.tableConfig,
this.dialect,
this.session,
config ? config : {},
"many"
);
}
findFirst(config) {
return new PgRelationalQuery(
this.fullSchema,
this.schema,
this.tableNamesMap,
this.table,
this.tableConfig,
this.dialect,
this.session,
config ? { ...config, limit: 1 } : { limit: 1 },
"first"
);
}
}
class PgRelationalQuery extends import_query_promise.QueryPromise {
constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session, config, mode) {
super();
this.fullSchema = fullSchema;
this.schema = schema;
this.tableNamesMap = tableNamesMap;
this.table = table;
this.tableConfig = tableConfig;
this.dialect = dialect;
this.session = session;
this.config = config;
this.mode = mode;
}
static [import_entity.entityKind] = "PgRelationalQuery";
/** @internal */
_prepare(name) {
return import_tracing.tracer.startActiveSpan("drizzle.prepareQuery", () => {
const { query, builtQuery } = this._toSQL();
return this.session.prepareQuery(
builtQuery,
void 0,
name,
true,
(rawRows, mapColumnValue) => {
const rows = rawRows.map(
(row) => (0, import_relations.mapRelationalRow)(this.schema, this.tableConfig, row, query.selection, mapColumnValue)
);
if (this.mode === "first") {
return rows[0];
}
return rows;
}
);
});
}
prepare(name) {
return this._prepare(name);
}
_getQuery() {
return this.dialect.buildRelationalQueryWithoutPK({
fullSchema: this.fullSchema,
schema: this.schema,
tableNamesMap: this.tableNamesMap,
table: this.table,
tableConfig: this.tableConfig,
queryConfig: this.config,
tableAlias: this.tableConfig.tsName
});
}
/** @internal */
getSQL() {
return this._getQuery().sql;
}
_toSQL() {
const query = this._getQuery();
const builtQuery = this.dialect.sqlToQuery(query.sql);
return { query, builtQuery };
}
toSQL() {
return this._toSQL().builtQuery;
}
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
execute() {
return import_tracing.tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(void 0, this.authToken);
});
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
PgRelationalQuery,
RelationalQueryBuilder
});
//# sourceMappingURL=query.cjs.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,47 @@
import { entityKind } from "../../entity.cjs";
import { QueryPromise } from "../../query-promise.cjs";
import { type BuildQueryResult, type DBQueryConfig, type TableRelationalConfig, type TablesRelationalConfig } from "../../relations.cjs";
import type { RunnableQuery } from "../../runnable-query.cjs";
import type { Query, SQLWrapper } from "../../sql/sql.cjs";
import type { KnownKeysOnly } from "../../utils.cjs";
import type { PgDialect } from "../dialect.cjs";
import type { PgPreparedQuery, PgSession, PreparedQueryConfig } from "../session.cjs";
import type { PgTable } from "../table.cjs";
export declare class RelationalQueryBuilder<TSchema extends TablesRelationalConfig, TFields extends TableRelationalConfig> {
private fullSchema;
private schema;
private tableNamesMap;
private table;
private tableConfig;
private dialect;
private session;
static readonly [entityKind]: string;
constructor(fullSchema: Record<string, unknown>, schema: TSchema, tableNamesMap: Record<string, string>, table: PgTable, tableConfig: TableRelationalConfig, dialect: PgDialect, session: PgSession);
findMany<TConfig extends DBQueryConfig<'many', true, TSchema, TFields>>(config?: KnownKeysOnly<TConfig, DBQueryConfig<'many', true, TSchema, TFields>>): PgRelationalQuery<BuildQueryResult<TSchema, TFields, TConfig>[]>;
findFirst<TSelection extends Omit<DBQueryConfig<'many', true, TSchema, TFields>, 'limit'>>(config?: KnownKeysOnly<TSelection, Omit<DBQueryConfig<'many', true, TSchema, TFields>, 'limit'>>): PgRelationalQuery<BuildQueryResult<TSchema, TFields, TSelection> | undefined>;
}
export declare class PgRelationalQuery<TResult> extends QueryPromise<TResult> implements RunnableQuery<TResult, 'pg'>, SQLWrapper {
private fullSchema;
private schema;
private tableNamesMap;
private table;
private tableConfig;
private dialect;
private session;
private config;
private mode;
static readonly [entityKind]: string;
readonly _: {
readonly dialect: 'pg';
readonly result: TResult;
};
constructor(fullSchema: Record<string, unknown>, schema: TablesRelationalConfig, tableNamesMap: Record<string, string>, table: PgTable, tableConfig: TableRelationalConfig, dialect: PgDialect, session: PgSession, config: DBQueryConfig<'many', true> | true, mode: 'many' | 'first');
prepare(name: string): PgPreparedQuery<PreparedQueryConfig & {
execute: TResult;
}>;
private _getQuery;
private _toSQL;
toSQL(): Query;
private authToken?;
execute(): Promise<TResult>;
}

View File

@ -0,0 +1,47 @@
import { entityKind } from "../../entity.js";
import { QueryPromise } from "../../query-promise.js";
import { type BuildQueryResult, type DBQueryConfig, type TableRelationalConfig, type TablesRelationalConfig } from "../../relations.js";
import type { RunnableQuery } from "../../runnable-query.js";
import type { Query, SQLWrapper } from "../../sql/sql.js";
import type { KnownKeysOnly } from "../../utils.js";
import type { PgDialect } from "../dialect.js";
import type { PgPreparedQuery, PgSession, PreparedQueryConfig } from "../session.js";
import type { PgTable } from "../table.js";
export declare class RelationalQueryBuilder<TSchema extends TablesRelationalConfig, TFields extends TableRelationalConfig> {
private fullSchema;
private schema;
private tableNamesMap;
private table;
private tableConfig;
private dialect;
private session;
static readonly [entityKind]: string;
constructor(fullSchema: Record<string, unknown>, schema: TSchema, tableNamesMap: Record<string, string>, table: PgTable, tableConfig: TableRelationalConfig, dialect: PgDialect, session: PgSession);
findMany<TConfig extends DBQueryConfig<'many', true, TSchema, TFields>>(config?: KnownKeysOnly<TConfig, DBQueryConfig<'many', true, TSchema, TFields>>): PgRelationalQuery<BuildQueryResult<TSchema, TFields, TConfig>[]>;
findFirst<TSelection extends Omit<DBQueryConfig<'many', true, TSchema, TFields>, 'limit'>>(config?: KnownKeysOnly<TSelection, Omit<DBQueryConfig<'many', true, TSchema, TFields>, 'limit'>>): PgRelationalQuery<BuildQueryResult<TSchema, TFields, TSelection> | undefined>;
}
export declare class PgRelationalQuery<TResult> extends QueryPromise<TResult> implements RunnableQuery<TResult, 'pg'>, SQLWrapper {
private fullSchema;
private schema;
private tableNamesMap;
private table;
private tableConfig;
private dialect;
private session;
private config;
private mode;
static readonly [entityKind]: string;
readonly _: {
readonly dialect: 'pg';
readonly result: TResult;
};
constructor(fullSchema: Record<string, unknown>, schema: TablesRelationalConfig, tableNamesMap: Record<string, string>, table: PgTable, tableConfig: TableRelationalConfig, dialect: PgDialect, session: PgSession, config: DBQueryConfig<'many', true> | true, mode: 'many' | 'first');
prepare(name: string): PgPreparedQuery<PreparedQueryConfig & {
execute: TResult;
}>;
private _getQuery;
private _toSQL;
toSQL(): Query;
private authToken?;
execute(): Promise<TResult>;
}

View File

@ -0,0 +1,122 @@
import { entityKind } from "../../entity.js";
import { QueryPromise } from "../../query-promise.js";
import {
mapRelationalRow
} from "../../relations.js";
import { tracer } from "../../tracing.js";
class RelationalQueryBuilder {
constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session) {
this.fullSchema = fullSchema;
this.schema = schema;
this.tableNamesMap = tableNamesMap;
this.table = table;
this.tableConfig = tableConfig;
this.dialect = dialect;
this.session = session;
}
static [entityKind] = "PgRelationalQueryBuilder";
findMany(config) {
return new PgRelationalQuery(
this.fullSchema,
this.schema,
this.tableNamesMap,
this.table,
this.tableConfig,
this.dialect,
this.session,
config ? config : {},
"many"
);
}
findFirst(config) {
return new PgRelationalQuery(
this.fullSchema,
this.schema,
this.tableNamesMap,
this.table,
this.tableConfig,
this.dialect,
this.session,
config ? { ...config, limit: 1 } : { limit: 1 },
"first"
);
}
}
class PgRelationalQuery extends QueryPromise {
constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session, config, mode) {
super();
this.fullSchema = fullSchema;
this.schema = schema;
this.tableNamesMap = tableNamesMap;
this.table = table;
this.tableConfig = tableConfig;
this.dialect = dialect;
this.session = session;
this.config = config;
this.mode = mode;
}
static [entityKind] = "PgRelationalQuery";
/** @internal */
_prepare(name) {
return tracer.startActiveSpan("drizzle.prepareQuery", () => {
const { query, builtQuery } = this._toSQL();
return this.session.prepareQuery(
builtQuery,
void 0,
name,
true,
(rawRows, mapColumnValue) => {
const rows = rawRows.map(
(row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue)
);
if (this.mode === "first") {
return rows[0];
}
return rows;
}
);
});
}
prepare(name) {
return this._prepare(name);
}
_getQuery() {
return this.dialect.buildRelationalQueryWithoutPK({
fullSchema: this.fullSchema,
schema: this.schema,
tableNamesMap: this.tableNamesMap,
table: this.table,
tableConfig: this.tableConfig,
queryConfig: this.config,
tableAlias: this.tableConfig.tsName
});
}
/** @internal */
getSQL() {
return this._getQuery().sql;
}
_toSQL() {
const query = this._getQuery();
const builtQuery = this.dialect.sqlToQuery(query.sql);
return { query, builtQuery };
}
toSQL() {
return this._toSQL().builtQuery;
}
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
execute() {
return tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(void 0, this.authToken);
});
}
}
export {
PgRelationalQuery,
RelationalQueryBuilder
};
//# sourceMappingURL=query.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,57 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var raw_exports = {};
__export(raw_exports, {
PgRaw: () => PgRaw
});
module.exports = __toCommonJS(raw_exports);
var import_entity = require("../../entity.cjs");
var import_query_promise = require("../../query-promise.cjs");
class PgRaw extends import_query_promise.QueryPromise {
constructor(execute, sql, query, mapBatchResult) {
super();
this.execute = execute;
this.sql = sql;
this.query = query;
this.mapBatchResult = mapBatchResult;
}
static [import_entity.entityKind] = "PgRaw";
/** @internal */
getSQL() {
return this.sql;
}
getQuery() {
return this.query;
}
mapResult(result, isFromBatch) {
return isFromBatch ? this.mapBatchResult(result) : result;
}
_prepare() {
return this;
}
/** @internal */
isResponseInArrayMode() {
return false;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
PgRaw
});
//# sourceMappingURL=raw.cjs.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/pg-core/query-builders/raw.ts"],"sourcesContent":["import { entityKind } from '~/entity.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport type { PreparedQuery } from '~/session.ts';\nimport type { Query, SQL, SQLWrapper } from '~/sql/sql.ts';\n\nexport interface PgRaw<TResult> extends QueryPromise<TResult>, RunnableQuery<TResult, 'pg'>, SQLWrapper {}\n\nexport class PgRaw<TResult> extends QueryPromise<TResult>\n\timplements RunnableQuery<TResult, 'pg'>, SQLWrapper, PreparedQuery\n{\n\tstatic override readonly [entityKind]: string = 'PgRaw';\n\n\tdeclare readonly _: {\n\t\treadonly dialect: 'pg';\n\t\treadonly result: TResult;\n\t};\n\n\tconstructor(\n\t\tpublic execute: () => Promise<TResult>,\n\t\tprivate sql: SQL,\n\t\tprivate query: Query,\n\t\tprivate mapBatchResult: (result: unknown) => unknown,\n\t) {\n\t\tsuper();\n\t}\n\n\t/** @internal */\n\tgetSQL() {\n\t\treturn this.sql;\n\t}\n\n\tgetQuery() {\n\t\treturn this.query;\n\t}\n\n\tmapResult(result: unknown, isFromBatch?: boolean) {\n\t\treturn isFromBatch ? this.mapBatchResult(result) : result;\n\t}\n\n\t_prepare(): PreparedQuery {\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tisResponseInArrayMode() {\n\t\treturn false;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA2B;AAC3B,2BAA6B;AAOtB,MAAM,cAAuB,kCAEpC;AAAA,EAQC,YACQ,SACC,KACA,OACA,gBACP;AACD,UAAM;AALC;AACC;AACA;AACA;AAAA,EAGT;AAAA,EAdA,QAA0B,wBAAU,IAAY;AAAA;AAAA,EAiBhD,SAAS;AACR,WAAO,KAAK;AAAA,EACb;AAAA,EAEA,WAAW;AACV,WAAO,KAAK;AAAA,EACb;AAAA,EAEA,UAAU,QAAiB,aAAuB;AACjD,WAAO,cAAc,KAAK,eAAe,MAAM,IAAI;AAAA,EACpD;AAAA,EAEA,WAA0B;AACzB,WAAO;AAAA,EACR;AAAA;AAAA,EAGA,wBAAwB;AACvB,WAAO;AAAA,EACR;AACD;","names":[]}

View File

@ -0,0 +1,22 @@
import { entityKind } from "../../entity.cjs";
import { QueryPromise } from "../../query-promise.cjs";
import type { RunnableQuery } from "../../runnable-query.cjs";
import type { PreparedQuery } from "../../session.cjs";
import type { Query, SQL, SQLWrapper } from "../../sql/sql.cjs";
export interface PgRaw<TResult> extends QueryPromise<TResult>, RunnableQuery<TResult, 'pg'>, SQLWrapper {
}
export declare class PgRaw<TResult> extends QueryPromise<TResult> implements RunnableQuery<TResult, 'pg'>, SQLWrapper, PreparedQuery {
execute: () => Promise<TResult>;
private sql;
private query;
private mapBatchResult;
static readonly [entityKind]: string;
readonly _: {
readonly dialect: 'pg';
readonly result: TResult;
};
constructor(execute: () => Promise<TResult>, sql: SQL, query: Query, mapBatchResult: (result: unknown) => unknown);
getQuery(): Query;
mapResult(result: unknown, isFromBatch?: boolean): unknown;
_prepare(): PreparedQuery;
}

View File

@ -0,0 +1,22 @@
import { entityKind } from "../../entity.js";
import { QueryPromise } from "../../query-promise.js";
import type { RunnableQuery } from "../../runnable-query.js";
import type { PreparedQuery } from "../../session.js";
import type { Query, SQL, SQLWrapper } from "../../sql/sql.js";
export interface PgRaw<TResult> extends QueryPromise<TResult>, RunnableQuery<TResult, 'pg'>, SQLWrapper {
}
export declare class PgRaw<TResult> extends QueryPromise<TResult> implements RunnableQuery<TResult, 'pg'>, SQLWrapper, PreparedQuery {
execute: () => Promise<TResult>;
private sql;
private query;
private mapBatchResult;
static readonly [entityKind]: string;
readonly _: {
readonly dialect: 'pg';
readonly result: TResult;
};
constructor(execute: () => Promise<TResult>, sql: SQL, query: Query, mapBatchResult: (result: unknown) => unknown);
getQuery(): Query;
mapResult(result: unknown, isFromBatch?: boolean): unknown;
_prepare(): PreparedQuery;
}

33
node_modules/drizzle-orm/pg-core/query-builders/raw.js generated vendored Normal file
View File

@ -0,0 +1,33 @@
import { entityKind } from "../../entity.js";
import { QueryPromise } from "../../query-promise.js";
class PgRaw extends QueryPromise {
constructor(execute, sql, query, mapBatchResult) {
super();
this.execute = execute;
this.sql = sql;
this.query = query;
this.mapBatchResult = mapBatchResult;
}
static [entityKind] = "PgRaw";
/** @internal */
getSQL() {
return this.sql;
}
getQuery() {
return this.query;
}
mapResult(result, isFromBatch) {
return isFromBatch ? this.mapBatchResult(result) : result;
}
_prepare() {
return this;
}
/** @internal */
isResponseInArrayMode() {
return false;
}
}
export {
PgRaw
};
//# sourceMappingURL=raw.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/pg-core/query-builders/raw.ts"],"sourcesContent":["import { entityKind } from '~/entity.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport type { PreparedQuery } from '~/session.ts';\nimport type { Query, SQL, SQLWrapper } from '~/sql/sql.ts';\n\nexport interface PgRaw<TResult> extends QueryPromise<TResult>, RunnableQuery<TResult, 'pg'>, SQLWrapper {}\n\nexport class PgRaw<TResult> extends QueryPromise<TResult>\n\timplements RunnableQuery<TResult, 'pg'>, SQLWrapper, PreparedQuery\n{\n\tstatic override readonly [entityKind]: string = 'PgRaw';\n\n\tdeclare readonly _: {\n\t\treadonly dialect: 'pg';\n\t\treadonly result: TResult;\n\t};\n\n\tconstructor(\n\t\tpublic execute: () => Promise<TResult>,\n\t\tprivate sql: SQL,\n\t\tprivate query: Query,\n\t\tprivate mapBatchResult: (result: unknown) => unknown,\n\t) {\n\t\tsuper();\n\t}\n\n\t/** @internal */\n\tgetSQL() {\n\t\treturn this.sql;\n\t}\n\n\tgetQuery() {\n\t\treturn this.query;\n\t}\n\n\tmapResult(result: unknown, isFromBatch?: boolean) {\n\t\treturn isFromBatch ? this.mapBatchResult(result) : result;\n\t}\n\n\t_prepare(): PreparedQuery {\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tisResponseInArrayMode() {\n\t\treturn false;\n\t}\n}\n"],"mappings":"AAAA,SAAS,kBAAkB;AAC3B,SAAS,oBAAoB;AAOtB,MAAM,cAAuB,aAEpC;AAAA,EAQC,YACQ,SACC,KACA,OACA,gBACP;AACD,UAAM;AALC;AACC;AACA;AACA;AAAA,EAGT;AAAA,EAdA,QAA0B,UAAU,IAAY;AAAA;AAAA,EAiBhD,SAAS;AACR,WAAO,KAAK;AAAA,EACb;AAAA,EAEA,WAAW;AACV,WAAO,KAAK;AAAA,EACb;AAAA,EAEA,UAAU,QAAiB,aAAuB;AACjD,WAAO,cAAc,KAAK,eAAe,MAAM,IAAI;AAAA,EACpD;AAAA,EAEA,WAA0B;AACzB,WAAO;AAAA,EACR;AAAA;AAAA,EAGA,wBAAwB;AACvB,WAAO;AAAA,EACR;AACD;","names":[]}

View File

@ -0,0 +1,83 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var refresh_materialized_view_exports = {};
__export(refresh_materialized_view_exports, {
PgRefreshMaterializedView: () => PgRefreshMaterializedView
});
module.exports = __toCommonJS(refresh_materialized_view_exports);
var import_entity = require("../../entity.cjs");
var import_query_promise = require("../../query-promise.cjs");
var import_tracing = require("../../tracing.cjs");
class PgRefreshMaterializedView extends import_query_promise.QueryPromise {
constructor(view, session, dialect) {
super();
this.session = session;
this.dialect = dialect;
this.config = { view };
}
static [import_entity.entityKind] = "PgRefreshMaterializedView";
config;
concurrently() {
if (this.config.withNoData !== void 0) {
throw new Error("Cannot use concurrently and withNoData together");
}
this.config.concurrently = true;
return this;
}
withNoData() {
if (this.config.concurrently !== void 0) {
throw new Error("Cannot use concurrently and withNoData together");
}
this.config.withNoData = true;
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildRefreshMaterializedViewQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
/** @internal */
_prepare(name) {
return import_tracing.tracer.startActiveSpan("drizzle.prepareQuery", () => {
return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), void 0, name, true);
});
}
prepare(name) {
return this._prepare(name);
}
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
execute = (placeholderValues) => {
return import_tracing.tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(placeholderValues, this.authToken);
});
};
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
PgRefreshMaterializedView
});
//# sourceMappingURL=refresh-materialized-view.cjs.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/pg-core/query-builders/refresh-materialized-view.ts"],"sourcesContent":["import { entityKind } from '~/entity.ts';\nimport type { PgDialect } from '~/pg-core/dialect.ts';\nimport type {\n\tPgPreparedQuery,\n\tPgQueryResultHKT,\n\tPgQueryResultKind,\n\tPgSession,\n\tPreparedQueryConfig,\n} from '~/pg-core/session.ts';\nimport type { PgMaterializedView } from '~/pg-core/view.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport type { Query, SQL, SQLWrapper } from '~/sql/sql.ts';\nimport { tracer } from '~/tracing.ts';\nimport type { NeonAuthToken } from '~/utils';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface PgRefreshMaterializedView<TQueryResult extends PgQueryResultHKT>\n\textends\n\t\tQueryPromise<PgQueryResultKind<TQueryResult, never>>,\n\t\tRunnableQuery<PgQueryResultKind<TQueryResult, never>, 'pg'>,\n\t\tSQLWrapper\n{\n\treadonly _: {\n\t\treadonly dialect: 'pg';\n\t\treadonly result: PgQueryResultKind<TQueryResult, never>;\n\t};\n}\n\nexport class PgRefreshMaterializedView<TQueryResult extends PgQueryResultHKT>\n\textends QueryPromise<PgQueryResultKind<TQueryResult, never>>\n\timplements RunnableQuery<PgQueryResultKind<TQueryResult, never>, 'pg'>, SQLWrapper\n{\n\tstatic override readonly [entityKind]: string = 'PgRefreshMaterializedView';\n\n\tprivate config: {\n\t\tview: PgMaterializedView;\n\t\tconcurrently?: boolean;\n\t\twithNoData?: boolean;\n\t};\n\n\tconstructor(\n\t\tview: PgMaterializedView,\n\t\tprivate session: PgSession,\n\t\tprivate dialect: PgDialect,\n\t) {\n\t\tsuper();\n\t\tthis.config = { view };\n\t}\n\n\tconcurrently(): this {\n\t\tif (this.config.withNoData !== undefined) {\n\t\t\tthrow new Error('Cannot use concurrently and withNoData together');\n\t\t}\n\t\tthis.config.concurrently = true;\n\t\treturn this;\n\t}\n\n\twithNoData(): this {\n\t\tif (this.config.concurrently !== undefined) {\n\t\t\tthrow new Error('Cannot use concurrently and withNoData together');\n\t\t}\n\t\tthis.config.withNoData = true;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tgetSQL(): SQL {\n\t\treturn this.dialect.buildRefreshMaterializedViewQuery(this.config);\n\t}\n\n\ttoSQL(): Query {\n\t\tconst { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());\n\t\treturn rest;\n\t}\n\n\t/** @internal */\n\t_prepare(name?: string): PgPreparedQuery<\n\t\tPreparedQueryConfig & {\n\t\t\texecute: PgQueryResultKind<TQueryResult, never>;\n\t\t}\n\t> {\n\t\treturn tracer.startActiveSpan('drizzle.prepareQuery', () => {\n\t\t\treturn this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), undefined, name, true);\n\t\t});\n\t}\n\n\tprepare(name: string): PgPreparedQuery<\n\t\tPreparedQueryConfig & {\n\t\t\texecute: PgQueryResultKind<TQueryResult, never>;\n\t\t}\n\t> {\n\t\treturn this._prepare(name);\n\t}\n\n\tprivate authToken?: NeonAuthToken;\n\t/** @internal */\n\tsetToken(token: NeonAuthToken) {\n\t\tthis.authToken = token;\n\t\treturn this;\n\t}\n\n\texecute: ReturnType<this['prepare']>['execute'] = (placeholderValues) => {\n\t\treturn tracer.startActiveSpan('drizzle.operation', () => {\n\t\t\treturn this._prepare().execute(placeholderValues, this.authToken);\n\t\t});\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA2B;AAU3B,2BAA6B;AAG7B,qBAAuB;AAgBhB,MAAM,kCACJ,kCAET;AAAA,EASC,YACC,MACQ,SACA,SACP;AACD,UAAM;AAHE;AACA;AAGR,SAAK,SAAS,EAAE,KAAK;AAAA,EACtB;AAAA,EAfA,QAA0B,wBAAU,IAAY;AAAA,EAExC;AAAA,EAeR,eAAqB;AACpB,QAAI,KAAK,OAAO,eAAe,QAAW;AACzC,YAAM,IAAI,MAAM,iDAAiD;AAAA,IAClE;AACA,SAAK,OAAO,eAAe;AAC3B,WAAO;AAAA,EACR;AAAA,EAEA,aAAmB;AAClB,QAAI,KAAK,OAAO,iBAAiB,QAAW;AAC3C,YAAM,IAAI,MAAM,iDAAiD;AAAA,IAClE;AACA,SAAK,OAAO,aAAa;AACzB,WAAO;AAAA,EACR;AAAA;AAAA,EAGA,SAAc;AACb,WAAO,KAAK,QAAQ,kCAAkC,KAAK,MAAM;AAAA,EAClE;AAAA,EAEA,QAAe;AACd,UAAM,EAAE,SAAS,UAAU,GAAG,KAAK,IAAI,KAAK,QAAQ,WAAW,KAAK,OAAO,CAAC;AAC5E,WAAO;AAAA,EACR;AAAA;AAAA,EAGA,SAAS,MAIP;AACD,WAAO,sBAAO,gBAAgB,wBAAwB,MAAM;AAC3D,aAAO,KAAK,QAAQ,aAAa,KAAK,QAAQ,WAAW,KAAK,OAAO,CAAC,GAAG,QAAW,MAAM,IAAI;AAAA,IAC/F,CAAC;AAAA,EACF;AAAA,EAEA,QAAQ,MAIN;AACD,WAAO,KAAK,SAAS,IAAI;AAAA,EAC1B;AAAA,EAEQ;AAAA;AAAA,EAER,SAAS,OAAsB;AAC9B,SAAK,YAAY;AACjB,WAAO;AAAA,EACR;AAAA,EAEA,UAAkD,CAAC,sBAAsB;AACxE,WAAO,sBAAO,gBAAgB,qBAAqB,MAAM;AACxD,aAAO,KAAK,SAAS,EAAE,QAAQ,mBAAmB,KAAK,SAAS;AAAA,IACjE,CAAC;AAAA,EACF;AACD;","names":[]}

View File

@ -0,0 +1,28 @@
import { entityKind } from "../../entity.cjs";
import type { PgDialect } from "../dialect.cjs";
import type { PgPreparedQuery, PgQueryResultHKT, PgQueryResultKind, PgSession, PreparedQueryConfig } from "../session.cjs";
import type { PgMaterializedView } from "../view.cjs";
import { QueryPromise } from "../../query-promise.cjs";
import type { RunnableQuery } from "../../runnable-query.cjs";
import type { Query, SQLWrapper } from "../../sql/sql.cjs";
export interface PgRefreshMaterializedView<TQueryResult extends PgQueryResultHKT> extends QueryPromise<PgQueryResultKind<TQueryResult, never>>, RunnableQuery<PgQueryResultKind<TQueryResult, never>, 'pg'>, SQLWrapper {
readonly _: {
readonly dialect: 'pg';
readonly result: PgQueryResultKind<TQueryResult, never>;
};
}
export declare class PgRefreshMaterializedView<TQueryResult extends PgQueryResultHKT> extends QueryPromise<PgQueryResultKind<TQueryResult, never>> implements RunnableQuery<PgQueryResultKind<TQueryResult, never>, 'pg'>, SQLWrapper {
private session;
private dialect;
static readonly [entityKind]: string;
private config;
constructor(view: PgMaterializedView, session: PgSession, dialect: PgDialect);
concurrently(): this;
withNoData(): this;
toSQL(): Query;
prepare(name: string): PgPreparedQuery<PreparedQueryConfig & {
execute: PgQueryResultKind<TQueryResult, never>;
}>;
private authToken?;
execute: ReturnType<this['prepare']>['execute'];
}

View File

@ -0,0 +1,28 @@
import { entityKind } from "../../entity.js";
import type { PgDialect } from "../dialect.js";
import type { PgPreparedQuery, PgQueryResultHKT, PgQueryResultKind, PgSession, PreparedQueryConfig } from "../session.js";
import type { PgMaterializedView } from "../view.js";
import { QueryPromise } from "../../query-promise.js";
import type { RunnableQuery } from "../../runnable-query.js";
import type { Query, SQLWrapper } from "../../sql/sql.js";
export interface PgRefreshMaterializedView<TQueryResult extends PgQueryResultHKT> extends QueryPromise<PgQueryResultKind<TQueryResult, never>>, RunnableQuery<PgQueryResultKind<TQueryResult, never>, 'pg'>, SQLWrapper {
readonly _: {
readonly dialect: 'pg';
readonly result: PgQueryResultKind<TQueryResult, never>;
};
}
export declare class PgRefreshMaterializedView<TQueryResult extends PgQueryResultHKT> extends QueryPromise<PgQueryResultKind<TQueryResult, never>> implements RunnableQuery<PgQueryResultKind<TQueryResult, never>, 'pg'>, SQLWrapper {
private session;
private dialect;
static readonly [entityKind]: string;
private config;
constructor(view: PgMaterializedView, session: PgSession, dialect: PgDialect);
concurrently(): this;
withNoData(): this;
toSQL(): Query;
prepare(name: string): PgPreparedQuery<PreparedQueryConfig & {
execute: PgQueryResultKind<TQueryResult, never>;
}>;
private authToken?;
execute: ReturnType<this['prepare']>['execute'];
}

View File

@ -0,0 +1,59 @@
import { entityKind } from "../../entity.js";
import { QueryPromise } from "../../query-promise.js";
import { tracer } from "../../tracing.js";
class PgRefreshMaterializedView extends QueryPromise {
constructor(view, session, dialect) {
super();
this.session = session;
this.dialect = dialect;
this.config = { view };
}
static [entityKind] = "PgRefreshMaterializedView";
config;
concurrently() {
if (this.config.withNoData !== void 0) {
throw new Error("Cannot use concurrently and withNoData together");
}
this.config.concurrently = true;
return this;
}
withNoData() {
if (this.config.concurrently !== void 0) {
throw new Error("Cannot use concurrently and withNoData together");
}
this.config.withNoData = true;
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildRefreshMaterializedViewQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
/** @internal */
_prepare(name) {
return tracer.startActiveSpan("drizzle.prepareQuery", () => {
return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), void 0, name, true);
});
}
prepare(name) {
return this._prepare(name);
}
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
execute = (placeholderValues) => {
return tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(placeholderValues, this.authToken);
});
};
}
export {
PgRefreshMaterializedView
};
//# sourceMappingURL=refresh-materialized-view.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/pg-core/query-builders/refresh-materialized-view.ts"],"sourcesContent":["import { entityKind } from '~/entity.ts';\nimport type { PgDialect } from '~/pg-core/dialect.ts';\nimport type {\n\tPgPreparedQuery,\n\tPgQueryResultHKT,\n\tPgQueryResultKind,\n\tPgSession,\n\tPreparedQueryConfig,\n} from '~/pg-core/session.ts';\nimport type { PgMaterializedView } from '~/pg-core/view.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport type { Query, SQL, SQLWrapper } from '~/sql/sql.ts';\nimport { tracer } from '~/tracing.ts';\nimport type { NeonAuthToken } from '~/utils';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface PgRefreshMaterializedView<TQueryResult extends PgQueryResultHKT>\n\textends\n\t\tQueryPromise<PgQueryResultKind<TQueryResult, never>>,\n\t\tRunnableQuery<PgQueryResultKind<TQueryResult, never>, 'pg'>,\n\t\tSQLWrapper\n{\n\treadonly _: {\n\t\treadonly dialect: 'pg';\n\t\treadonly result: PgQueryResultKind<TQueryResult, never>;\n\t};\n}\n\nexport class PgRefreshMaterializedView<TQueryResult extends PgQueryResultHKT>\n\textends QueryPromise<PgQueryResultKind<TQueryResult, never>>\n\timplements RunnableQuery<PgQueryResultKind<TQueryResult, never>, 'pg'>, SQLWrapper\n{\n\tstatic override readonly [entityKind]: string = 'PgRefreshMaterializedView';\n\n\tprivate config: {\n\t\tview: PgMaterializedView;\n\t\tconcurrently?: boolean;\n\t\twithNoData?: boolean;\n\t};\n\n\tconstructor(\n\t\tview: PgMaterializedView,\n\t\tprivate session: PgSession,\n\t\tprivate dialect: PgDialect,\n\t) {\n\t\tsuper();\n\t\tthis.config = { view };\n\t}\n\n\tconcurrently(): this {\n\t\tif (this.config.withNoData !== undefined) {\n\t\t\tthrow new Error('Cannot use concurrently and withNoData together');\n\t\t}\n\t\tthis.config.concurrently = true;\n\t\treturn this;\n\t}\n\n\twithNoData(): this {\n\t\tif (this.config.concurrently !== undefined) {\n\t\t\tthrow new Error('Cannot use concurrently and withNoData together');\n\t\t}\n\t\tthis.config.withNoData = true;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tgetSQL(): SQL {\n\t\treturn this.dialect.buildRefreshMaterializedViewQuery(this.config);\n\t}\n\n\ttoSQL(): Query {\n\t\tconst { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());\n\t\treturn rest;\n\t}\n\n\t/** @internal */\n\t_prepare(name?: string): PgPreparedQuery<\n\t\tPreparedQueryConfig & {\n\t\t\texecute: PgQueryResultKind<TQueryResult, never>;\n\t\t}\n\t> {\n\t\treturn tracer.startActiveSpan('drizzle.prepareQuery', () => {\n\t\t\treturn this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), undefined, name, true);\n\t\t});\n\t}\n\n\tprepare(name: string): PgPreparedQuery<\n\t\tPreparedQueryConfig & {\n\t\t\texecute: PgQueryResultKind<TQueryResult, never>;\n\t\t}\n\t> {\n\t\treturn this._prepare(name);\n\t}\n\n\tprivate authToken?: NeonAuthToken;\n\t/** @internal */\n\tsetToken(token: NeonAuthToken) {\n\t\tthis.authToken = token;\n\t\treturn this;\n\t}\n\n\texecute: ReturnType<this['prepare']>['execute'] = (placeholderValues) => {\n\t\treturn tracer.startActiveSpan('drizzle.operation', () => {\n\t\t\treturn this._prepare().execute(placeholderValues, this.authToken);\n\t\t});\n\t};\n}\n"],"mappings":"AAAA,SAAS,kBAAkB;AAU3B,SAAS,oBAAoB;AAG7B,SAAS,cAAc;AAgBhB,MAAM,kCACJ,aAET;AAAA,EASC,YACC,MACQ,SACA,SACP;AACD,UAAM;AAHE;AACA;AAGR,SAAK,SAAS,EAAE,KAAK;AAAA,EACtB;AAAA,EAfA,QAA0B,UAAU,IAAY;AAAA,EAExC;AAAA,EAeR,eAAqB;AACpB,QAAI,KAAK,OAAO,eAAe,QAAW;AACzC,YAAM,IAAI,MAAM,iDAAiD;AAAA,IAClE;AACA,SAAK,OAAO,eAAe;AAC3B,WAAO;AAAA,EACR;AAAA,EAEA,aAAmB;AAClB,QAAI,KAAK,OAAO,iBAAiB,QAAW;AAC3C,YAAM,IAAI,MAAM,iDAAiD;AAAA,IAClE;AACA,SAAK,OAAO,aAAa;AACzB,WAAO;AAAA,EACR;AAAA;AAAA,EAGA,SAAc;AACb,WAAO,KAAK,QAAQ,kCAAkC,KAAK,MAAM;AAAA,EAClE;AAAA,EAEA,QAAe;AACd,UAAM,EAAE,SAAS,UAAU,GAAG,KAAK,IAAI,KAAK,QAAQ,WAAW,KAAK,OAAO,CAAC;AAC5E,WAAO;AAAA,EACR;AAAA;AAAA,EAGA,SAAS,MAIP;AACD,WAAO,OAAO,gBAAgB,wBAAwB,MAAM;AAC3D,aAAO,KAAK,QAAQ,aAAa,KAAK,QAAQ,WAAW,KAAK,OAAO,CAAC,GAAG,QAAW,MAAM,IAAI;AAAA,IAC/F,CAAC;AAAA,EACF;AAAA,EAEA,QAAQ,MAIN;AACD,WAAO,KAAK,SAAS,IAAI;AAAA,EAC1B;AAAA,EAEQ;AAAA;AAAA,EAER,SAAS,OAAsB;AAC9B,SAAK,YAAY;AACjB,WAAO;AAAA,EACR;AAAA,EAEA,UAAkD,CAAC,sBAAsB;AACxE,WAAO,OAAO,gBAAgB,qBAAqB,MAAM;AACxD,aAAO,KAAK,SAAS,EAAE,QAAQ,mBAAmB,KAAK,SAAS;AAAA,IACjE,CAAC;AAAA,EACF;AACD;","names":[]}

View File

@ -0,0 +1,781 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except2, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except2)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var select_exports = {};
__export(select_exports, {
PgSelectBase: () => PgSelectBase,
PgSelectBuilder: () => PgSelectBuilder,
PgSelectQueryBuilderBase: () => PgSelectQueryBuilderBase,
except: () => except,
exceptAll: () => exceptAll,
intersect: () => intersect,
intersectAll: () => intersectAll,
union: () => union,
unionAll: () => unionAll
});
module.exports = __toCommonJS(select_exports);
var import_entity = require("../../entity.cjs");
var import_view_base = require("../view-base.cjs");
var import_query_builder = require("../../query-builders/query-builder.cjs");
var import_query_promise = require("../../query-promise.cjs");
var import_selection_proxy = require("../../selection-proxy.cjs");
var import_sql = require("../../sql/sql.cjs");
var import_subquery = require("../../subquery.cjs");
var import_table = require("../../table.cjs");
var import_tracing = require("../../tracing.cjs");
var import_utils = require("../../utils.cjs");
var import_utils2 = require("../../utils.cjs");
var import_view_common = require("../../view-common.cjs");
class PgSelectBuilder {
static [import_entity.entityKind] = "PgSelectBuilder";
fields;
session;
dialect;
withList = [];
distinct;
constructor(config) {
this.fields = config.fields;
this.session = config.session;
this.dialect = config.dialect;
if (config.withList) {
this.withList = config.withList;
}
this.distinct = config.distinct;
}
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
/**
* Specify the table, subquery, or other target that you're
* building a select query against.
*
* {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FROM | Postgres from documentation}
*/
from(source) {
const isPartialSelect = !!this.fields;
let fields;
if (this.fields) {
fields = this.fields;
} else if ((0, import_entity.is)(source, import_subquery.Subquery)) {
fields = Object.fromEntries(
Object.keys(source._.selectedFields).map((key) => [key, source[key]])
);
} else if ((0, import_entity.is)(source, import_view_base.PgViewBase)) {
fields = source[import_view_common.ViewBaseConfig].selectedFields;
} else if ((0, import_entity.is)(source, import_sql.SQL)) {
fields = {};
} else {
fields = (0, import_utils.getTableColumns)(source);
}
return new PgSelectBase({
table: source,
fields,
isPartialSelect,
session: this.session,
dialect: this.dialect,
withList: this.withList,
distinct: this.distinct
}).setToken(this.authToken);
}
}
class PgSelectQueryBuilderBase extends import_query_builder.TypedQueryBuilder {
static [import_entity.entityKind] = "PgSelectQueryBuilder";
_;
config;
joinsNotNullableMap;
tableName;
isPartialSelect;
session;
dialect;
constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }) {
super();
this.config = {
withList,
table,
fields: { ...fields },
distinct,
setOperators: []
};
this.isPartialSelect = isPartialSelect;
this.session = session;
this.dialect = dialect;
this._ = {
selectedFields: fields
};
this.tableName = (0, import_utils.getTableLikeName)(table);
this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
}
createJoin(joinType) {
return (table, on) => {
const baseTableName = this.tableName;
const tableName = (0, import_utils.getTableLikeName)(table);
if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) {
throw new Error(`Alias "${tableName}" is already used in this query`);
}
if (!this.isPartialSelect) {
if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") {
this.config.fields = {
[baseTableName]: this.config.fields
};
}
if (typeof tableName === "string" && !(0, import_entity.is)(table, import_sql.SQL)) {
const selection = (0, import_entity.is)(table, import_subquery.Subquery) ? table._.selectedFields : (0, import_entity.is)(table, import_sql.View) ? table[import_view_common.ViewBaseConfig].selectedFields : table[import_table.Table.Symbol.Columns];
this.config.fields[tableName] = selection;
}
}
if (typeof on === "function") {
on = on(
new Proxy(
this.config.fields,
new import_selection_proxy.SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
)
);
}
if (!this.config.joins) {
this.config.joins = [];
}
this.config.joins.push({ on, table, joinType, alias: tableName });
if (typeof tableName === "string") {
switch (joinType) {
case "left": {
this.joinsNotNullableMap[tableName] = false;
break;
}
case "right": {
this.joinsNotNullableMap = Object.fromEntries(
Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
);
this.joinsNotNullableMap[tableName] = true;
break;
}
case "inner": {
this.joinsNotNullableMap[tableName] = true;
break;
}
case "full": {
this.joinsNotNullableMap = Object.fromEntries(
Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
);
this.joinsNotNullableMap[tableName] = false;
break;
}
}
}
return this;
};
}
/**
* Executes a `left join` operation by adding another table to the current query.
*
* Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User; pets: Pet | null }[] = await db.select()
* .from(users)
* .leftJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number | null }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .leftJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
leftJoin = this.createJoin("left");
/**
* Executes a `right join` operation by adding another table to the current query.
*
* Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User | null; pets: Pet }[] = await db.select()
* .from(users)
* .rightJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number | null; petId: number }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .rightJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
rightJoin = this.createJoin("right");
/**
* Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
*
* Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User; pets: Pet }[] = await db.select()
* .from(users)
* .innerJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .innerJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
innerJoin = this.createJoin("inner");
/**
* Executes a `full join` operation by combining rows from two tables into a new table.
*
* Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User | null; pets: Pet | null }[] = await db.select()
* .from(users)
* .fullJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number | null; petId: number | null }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .fullJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
fullJoin = this.createJoin("full");
createSetOperator(type, isAll) {
return (rightSelection) => {
const rightSelect = typeof rightSelection === "function" ? rightSelection(getPgSetOperators()) : rightSelection;
if (!(0, import_utils.haveSameKeys)(this.getSelectedFields(), rightSelect.getSelectedFields())) {
throw new Error(
"Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
);
}
this.config.setOperators.push({ type, isAll, rightSelect });
return this;
};
}
/**
* Adds `union` set operator to the query.
*
* Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
*
* @example
*
* ```ts
* // Select all unique names from customers and users tables
* await db.select({ name: users.name })
* .from(users)
* .union(
* db.select({ name: customers.name }).from(customers)
* );
* // or
* import { union } from 'drizzle-orm/pg-core'
*
* await union(
* db.select({ name: users.name }).from(users),
* db.select({ name: customers.name }).from(customers)
* );
* ```
*/
union = this.createSetOperator("union", false);
/**
* Adds `union all` set operator to the query.
*
* Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
*
* @example
*
* ```ts
* // Select all transaction ids from both online and in-store sales
* await db.select({ transaction: onlineSales.transactionId })
* .from(onlineSales)
* .unionAll(
* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
* );
* // or
* import { unionAll } from 'drizzle-orm/pg-core'
*
* await unionAll(
* db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
* );
* ```
*/
unionAll = this.createSetOperator("union", true);
/**
* Adds `intersect` set operator to the query.
*
* Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
*
* @example
*
* ```ts
* // Select course names that are offered in both departments A and B
* await db.select({ courseName: depA.courseName })
* .from(depA)
* .intersect(
* db.select({ courseName: depB.courseName }).from(depB)
* );
* // or
* import { intersect } from 'drizzle-orm/pg-core'
*
* await intersect(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
intersect = this.createSetOperator("intersect", false);
/**
* Adds `intersect all` set operator to the query.
*
* Calling this method will retain only the rows that are present in both result sets including all duplicates.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect-all}
*
* @example
*
* ```ts
* // Select all products and quantities that are ordered by both regular and VIP customers
* await db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered
* })
* .from(regularCustomerOrders)
* .intersectAll(
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered
* })
* .from(vipCustomerOrders)
* );
* // or
* import { intersectAll } from 'drizzle-orm/pg-core'
*
* await intersectAll(
* db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered
* })
* .from(regularCustomerOrders),
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered
* })
* .from(vipCustomerOrders)
* );
* ```
*/
intersectAll = this.createSetOperator("intersect", true);
/**
* Adds `except` set operator to the query.
*
* Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
*
* @example
*
* ```ts
* // Select all courses offered in department A but not in department B
* await db.select({ courseName: depA.courseName })
* .from(depA)
* .except(
* db.select({ courseName: depB.courseName }).from(depB)
* );
* // or
* import { except } from 'drizzle-orm/pg-core'
*
* await except(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
except = this.createSetOperator("except", false);
/**
* Adds `except all` set operator to the query.
*
* Calling this method will retrieve all rows from the left query, except for the rows that are present in the result set of the right query.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#except-all}
*
* @example
*
* ```ts
* // Select all products that are ordered by regular customers but not by VIP customers
* await db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered,
* })
* .from(regularCustomerOrders)
* .exceptAll(
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered,
* })
* .from(vipCustomerOrders)
* );
* // or
* import { exceptAll } from 'drizzle-orm/pg-core'
*
* await exceptAll(
* db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered
* })
* .from(regularCustomerOrders),
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered
* })
* .from(vipCustomerOrders)
* );
* ```
*/
exceptAll = this.createSetOperator("except", true);
/** @internal */
addSetOperators(setOperators) {
this.config.setOperators.push(...setOperators);
return this;
}
/**
* Adds a `where` clause to the query.
*
* Calling this method will select only those rows that fulfill a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/select#filtering}
*
* @param where the `where` clause.
*
* @example
* You can use conditional operators and `sql function` to filter the rows to be selected.
*
* ```ts
* // Select all cars with green color
* await db.select().from(cars).where(eq(cars.color, 'green'));
* // or
* await db.select().from(cars).where(sql`${cars.color} = 'green'`)
* ```
*
* You can logically combine conditional operators with `and()` and `or()` operators:
*
* ```ts
* // Select all BMW cars with a green color
* await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
*
* // Select all cars with the green or blue color
* await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where) {
if (typeof where === "function") {
where = where(
new Proxy(
this.config.fields,
new import_selection_proxy.SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
)
);
}
this.config.where = where;
return this;
}
/**
* Adds a `having` clause to the query.
*
* Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
*
* @param having the `having` clause.
*
* @example
*
* ```ts
* // Select all brands with more than one car
* await db.select({
* brand: cars.brand,
* count: sql<number>`cast(count(${cars.id}) as int)`,
* })
* .from(cars)
* .groupBy(cars.brand)
* .having(({ count }) => gt(count, 1));
* ```
*/
having(having) {
if (typeof having === "function") {
having = having(
new Proxy(
this.config.fields,
new import_selection_proxy.SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
)
);
}
this.config.having = having;
return this;
}
groupBy(...columns) {
if (typeof columns[0] === "function") {
const groupBy = columns[0](
new Proxy(
this.config.fields,
new import_selection_proxy.SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
)
);
this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
} else {
this.config.groupBy = columns;
}
return this;
}
orderBy(...columns) {
if (typeof columns[0] === "function") {
const orderBy = columns[0](
new Proxy(
this.config.fields,
new import_selection_proxy.SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
)
);
const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
if (this.config.setOperators.length > 0) {
this.config.setOperators.at(-1).orderBy = orderByArray;
} else {
this.config.orderBy = orderByArray;
}
} else {
const orderByArray = columns;
if (this.config.setOperators.length > 0) {
this.config.setOperators.at(-1).orderBy = orderByArray;
} else {
this.config.orderBy = orderByArray;
}
}
return this;
}
/**
* Adds a `limit` clause to the query.
*
* Calling this method will set the maximum number of rows that will be returned by this query.
*
* See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
*
* @param limit the `limit` clause.
*
* @example
*
* ```ts
* // Get the first 10 people from this query.
* await db.select().from(people).limit(10);
* ```
*/
limit(limit) {
if (this.config.setOperators.length > 0) {
this.config.setOperators.at(-1).limit = limit;
} else {
this.config.limit = limit;
}
return this;
}
/**
* Adds an `offset` clause to the query.
*
* Calling this method will skip a number of rows when returning results from this query.
*
* See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
*
* @param offset the `offset` clause.
*
* @example
*
* ```ts
* // Get the 10th-20th people from this query.
* await db.select().from(people).offset(10).limit(10);
* ```
*/
offset(offset) {
if (this.config.setOperators.length > 0) {
this.config.setOperators.at(-1).offset = offset;
} else {
this.config.offset = offset;
}
return this;
}
/**
* Adds a `for` clause to the query.
*
* Calling this method will specify a lock strength for this query that controls how strictly it acquires exclusive access to the rows being queried.
*
* See docs: {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE}
*
* @param strength the lock strength.
* @param config the lock configuration.
*/
for(strength, config = {}) {
this.config.lockingClause = { strength, config };
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildSelectQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
as(alias) {
return new Proxy(
new import_subquery.Subquery(this.getSQL(), this.config.fields, alias),
new import_selection_proxy.SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
);
}
/** @internal */
getSelectedFields() {
return new Proxy(
this.config.fields,
new import_selection_proxy.SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
);
}
$dynamic() {
return this;
}
}
class PgSelectBase extends PgSelectQueryBuilderBase {
static [import_entity.entityKind] = "PgSelect";
/** @internal */
_prepare(name) {
const { session, config, dialect, joinsNotNullableMap, authToken } = this;
if (!session) {
throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
}
return import_tracing.tracer.startActiveSpan("drizzle.prepareQuery", () => {
const fieldsList = (0, import_utils2.orderSelectedFields)(config.fields);
const query = session.prepareQuery(dialect.sqlToQuery(this.getSQL()), fieldsList, name, true);
query.joinsNotNullableMap = joinsNotNullableMap;
return query.setToken(authToken);
});
}
/**
* Create a prepared statement for this query. This allows
* the database to remember this query for the given session
* and call it by name, rather than specifying the full query.
*
* {@link https://www.postgresql.org/docs/current/sql-prepare.html | Postgres prepare documentation}
*/
prepare(name) {
return this._prepare(name);
}
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
execute = (placeholderValues) => {
return import_tracing.tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(placeholderValues, this.authToken);
});
};
}
(0, import_utils.applyMixins)(PgSelectBase, [import_query_promise.QueryPromise]);
function createSetOperator(type, isAll) {
return (leftSelect, rightSelect, ...restSelects) => {
const setOperators = [rightSelect, ...restSelects].map((select) => ({
type,
isAll,
rightSelect: select
}));
for (const setOperator of setOperators) {
if (!(0, import_utils.haveSameKeys)(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {
throw new Error(
"Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
);
}
}
return leftSelect.addSetOperators(setOperators);
};
}
const getPgSetOperators = () => ({
union,
unionAll,
intersect,
intersectAll,
except,
exceptAll
});
const union = createSetOperator("union", false);
const unionAll = createSetOperator("union", true);
const intersect = createSetOperator("intersect", false);
const intersectAll = createSetOperator("intersect", true);
const except = createSetOperator("except", false);
const exceptAll = createSetOperator("except", true);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
PgSelectBase,
PgSelectBuilder,
PgSelectQueryBuilderBase,
except,
exceptAll,
intersect,
intersectAll,
union,
unionAll
});
//# sourceMappingURL=select.cjs.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,722 @@
import { entityKind } from "../../entity.cjs";
import type { PgColumn } from "../columns/index.cjs";
import type { PgDialect } from "../dialect.cjs";
import type { PgSession } from "../session.cjs";
import type { SubqueryWithSelection } from "../subquery.cjs";
import type { PgTable } from "../table.cjs";
import { PgViewBase } from "../view-base.cjs";
import { TypedQueryBuilder } from "../../query-builders/query-builder.cjs";
import type { BuildSubquerySelection, GetSelectTableName, GetSelectTableSelection, JoinNullability, SelectMode, SelectResult } from "../../query-builders/select.types.cjs";
import { QueryPromise } from "../../query-promise.cjs";
import type { RunnableQuery } from "../../runnable-query.cjs";
import { SQL } from "../../sql/sql.cjs";
import type { ColumnsSelection, Placeholder, Query, SQLWrapper } from "../../sql/sql.cjs";
import { Subquery } from "../../subquery.cjs";
import { type ValueOrArray } from "../../utils.cjs";
import type { CreatePgSelectFromBuilderMode, GetPgSetOperators, LockConfig, LockStrength, PgCreateSetOperatorFn, PgSelectConfig, PgSelectDynamic, PgSelectHKT, PgSelectHKTBase, PgSelectJoinFn, PgSelectPrepare, PgSelectWithout, PgSetOperatorExcludedMethods, PgSetOperatorWithResult, SelectedFields, SetOperatorRightSelect } from "./select.types.cjs";
export declare class PgSelectBuilder<TSelection extends SelectedFields | undefined, TBuilderMode extends 'db' | 'qb' = 'db'> {
static readonly [entityKind]: string;
private fields;
private session;
private dialect;
private withList;
private distinct;
constructor(config: {
fields: TSelection;
session: PgSession | undefined;
dialect: PgDialect;
withList?: Subquery[];
distinct?: boolean | {
on: (PgColumn | SQLWrapper)[];
};
});
private authToken?;
/**
* Specify the table, subquery, or other target that you're
* building a select query against.
*
* {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FROM | Postgres from documentation}
*/
from<TFrom extends PgTable | Subquery | PgViewBase | SQL>(source: TFrom): CreatePgSelectFromBuilderMode<TBuilderMode, GetSelectTableName<TFrom>, TSelection extends undefined ? GetSelectTableSelection<TFrom> : TSelection, TSelection extends undefined ? 'single' : 'partial'>;
}
export declare abstract class PgSelectQueryBuilderBase<THKT extends PgSelectHKTBase, TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TNullabilityMap extends Record<string, JoinNullability> = TTableName extends string ? Record<TTableName, 'not-null'> : {}, TDynamic extends boolean = false, TExcludedMethods extends string = never, TResult extends any[] = SelectResult<TSelection, TSelectMode, TNullabilityMap>[], TSelectedFields extends ColumnsSelection = BuildSubquerySelection<TSelection, TNullabilityMap>> extends TypedQueryBuilder<TSelectedFields, TResult> {
static readonly [entityKind]: string;
readonly _: {
readonly dialect: 'pg';
readonly hkt: THKT;
readonly tableName: TTableName;
readonly selection: TSelection;
readonly selectMode: TSelectMode;
readonly nullabilityMap: TNullabilityMap;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
readonly result: TResult;
readonly selectedFields: TSelectedFields;
};
protected config: PgSelectConfig;
protected joinsNotNullableMap: Record<string, boolean>;
private tableName;
private isPartialSelect;
protected session: PgSession | undefined;
protected dialect: PgDialect;
constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }: {
table: PgSelectConfig['table'];
fields: PgSelectConfig['fields'];
isPartialSelect: boolean;
session: PgSession | undefined;
dialect: PgDialect;
withList: Subquery[];
distinct: boolean | {
on: (PgColumn | SQLWrapper)[];
} | undefined;
});
private createJoin;
/**
* Executes a `left join` operation by adding another table to the current query.
*
* Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User; pets: Pet | null }[] = await db.select()
* .from(users)
* .leftJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number | null }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .leftJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
leftJoin: PgSelectJoinFn<this, TDynamic, "left">;
/**
* Executes a `right join` operation by adding another table to the current query.
*
* Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User | null; pets: Pet }[] = await db.select()
* .from(users)
* .rightJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number | null; petId: number }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .rightJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
rightJoin: PgSelectJoinFn<this, TDynamic, "right">;
/**
* Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
*
* Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User; pets: Pet }[] = await db.select()
* .from(users)
* .innerJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .innerJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
innerJoin: PgSelectJoinFn<this, TDynamic, "inner">;
/**
* Executes a `full join` operation by combining rows from two tables into a new table.
*
* Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User | null; pets: Pet | null }[] = await db.select()
* .from(users)
* .fullJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number | null; petId: number | null }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .fullJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
fullJoin: PgSelectJoinFn<this, TDynamic, "full">;
private createSetOperator;
/**
* Adds `union` set operator to the query.
*
* Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
*
* @example
*
* ```ts
* // Select all unique names from customers and users tables
* await db.select({ name: users.name })
* .from(users)
* .union(
* db.select({ name: customers.name }).from(customers)
* );
* // or
* import { union } from 'drizzle-orm/pg-core'
*
* await union(
* db.select({ name: users.name }).from(users),
* db.select({ name: customers.name }).from(customers)
* );
* ```
*/
union: <TValue extends PgSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetPgSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => PgSelectWithout<this, TDynamic, PgSetOperatorExcludedMethods, true>;
/**
* Adds `union all` set operator to the query.
*
* Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
*
* @example
*
* ```ts
* // Select all transaction ids from both online and in-store sales
* await db.select({ transaction: onlineSales.transactionId })
* .from(onlineSales)
* .unionAll(
* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
* );
* // or
* import { unionAll } from 'drizzle-orm/pg-core'
*
* await unionAll(
* db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
* );
* ```
*/
unionAll: <TValue extends PgSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetPgSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => PgSelectWithout<this, TDynamic, PgSetOperatorExcludedMethods, true>;
/**
* Adds `intersect` set operator to the query.
*
* Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
*
* @example
*
* ```ts
* // Select course names that are offered in both departments A and B
* await db.select({ courseName: depA.courseName })
* .from(depA)
* .intersect(
* db.select({ courseName: depB.courseName }).from(depB)
* );
* // or
* import { intersect } from 'drizzle-orm/pg-core'
*
* await intersect(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
intersect: <TValue extends PgSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetPgSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => PgSelectWithout<this, TDynamic, PgSetOperatorExcludedMethods, true>;
/**
* Adds `intersect all` set operator to the query.
*
* Calling this method will retain only the rows that are present in both result sets including all duplicates.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect-all}
*
* @example
*
* ```ts
* // Select all products and quantities that are ordered by both regular and VIP customers
* await db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered
* })
* .from(regularCustomerOrders)
* .intersectAll(
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered
* })
* .from(vipCustomerOrders)
* );
* // or
* import { intersectAll } from 'drizzle-orm/pg-core'
*
* await intersectAll(
* db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered
* })
* .from(regularCustomerOrders),
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered
* })
* .from(vipCustomerOrders)
* );
* ```
*/
intersectAll: <TValue extends PgSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetPgSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => PgSelectWithout<this, TDynamic, PgSetOperatorExcludedMethods, true>;
/**
* Adds `except` set operator to the query.
*
* Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
*
* @example
*
* ```ts
* // Select all courses offered in department A but not in department B
* await db.select({ courseName: depA.courseName })
* .from(depA)
* .except(
* db.select({ courseName: depB.courseName }).from(depB)
* );
* // or
* import { except } from 'drizzle-orm/pg-core'
*
* await except(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
except: <TValue extends PgSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetPgSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => PgSelectWithout<this, TDynamic, PgSetOperatorExcludedMethods, true>;
/**
* Adds `except all` set operator to the query.
*
* Calling this method will retrieve all rows from the left query, except for the rows that are present in the result set of the right query.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#except-all}
*
* @example
*
* ```ts
* // Select all products that are ordered by regular customers but not by VIP customers
* await db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered,
* })
* .from(regularCustomerOrders)
* .exceptAll(
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered,
* })
* .from(vipCustomerOrders)
* );
* // or
* import { exceptAll } from 'drizzle-orm/pg-core'
*
* await exceptAll(
* db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered
* })
* .from(regularCustomerOrders),
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered
* })
* .from(vipCustomerOrders)
* );
* ```
*/
exceptAll: <TValue extends PgSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetPgSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => PgSelectWithout<this, TDynamic, PgSetOperatorExcludedMethods, true>;
/**
* Adds a `where` clause to the query.
*
* Calling this method will select only those rows that fulfill a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/select#filtering}
*
* @param where the `where` clause.
*
* @example
* You can use conditional operators and `sql function` to filter the rows to be selected.
*
* ```ts
* // Select all cars with green color
* await db.select().from(cars).where(eq(cars.color, 'green'));
* // or
* await db.select().from(cars).where(sql`${cars.color} = 'green'`)
* ```
*
* You can logically combine conditional operators with `and()` and `or()` operators:
*
* ```ts
* // Select all BMW cars with a green color
* await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
*
* // Select all cars with the green or blue color
* await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where: ((aliases: this['_']['selection']) => SQL | undefined) | SQL | undefined): PgSelectWithout<this, TDynamic, 'where'>;
/**
* Adds a `having` clause to the query.
*
* Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
*
* @param having the `having` clause.
*
* @example
*
* ```ts
* // Select all brands with more than one car
* await db.select({
* brand: cars.brand,
* count: sql<number>`cast(count(${cars.id}) as int)`,
* })
* .from(cars)
* .groupBy(cars.brand)
* .having(({ count }) => gt(count, 1));
* ```
*/
having(having: ((aliases: this['_']['selection']) => SQL | undefined) | SQL | undefined): PgSelectWithout<this, TDynamic, 'having'>;
/**
* Adds a `group by` clause to the query.
*
* Calling this method will group rows that have the same values into summary rows, often used for aggregation purposes.
*
* See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
*
* @example
*
* ```ts
* // Group and count people by their last names
* await db.select({
* lastName: people.lastName,
* count: sql<number>`cast(count(*) as int)`
* })
* .from(people)
* .groupBy(people.lastName);
* ```
*/
groupBy(builder: (aliases: this['_']['selection']) => ValueOrArray<PgColumn | SQL | SQL.Aliased>): PgSelectWithout<this, TDynamic, 'groupBy'>;
groupBy(...columns: (PgColumn | SQL | SQL.Aliased)[]): PgSelectWithout<this, TDynamic, 'groupBy'>;
/**
* Adds an `order by` clause to the query.
*
* Calling this method will sort the result-set in ascending or descending order. By default, the sort order is ascending.
*
* See docs: {@link https://orm.drizzle.team/docs/select#order-by}
*
* @example
*
* ```
* // Select cars ordered by year
* await db.select().from(cars).orderBy(cars.year);
* ```
*
* You can specify whether results are in ascending or descending order with the `asc()` and `desc()` operators.
*
* ```ts
* // Select cars ordered by year in descending order
* await db.select().from(cars).orderBy(desc(cars.year));
*
* // Select cars ordered by year and price
* await db.select().from(cars).orderBy(asc(cars.year), desc(cars.price));
* ```
*/
orderBy(builder: (aliases: this['_']['selection']) => ValueOrArray<PgColumn | SQL | SQL.Aliased>): PgSelectWithout<this, TDynamic, 'orderBy'>;
orderBy(...columns: (PgColumn | SQL | SQL.Aliased)[]): PgSelectWithout<this, TDynamic, 'orderBy'>;
/**
* Adds a `limit` clause to the query.
*
* Calling this method will set the maximum number of rows that will be returned by this query.
*
* See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
*
* @param limit the `limit` clause.
*
* @example
*
* ```ts
* // Get the first 10 people from this query.
* await db.select().from(people).limit(10);
* ```
*/
limit(limit: number | Placeholder): PgSelectWithout<this, TDynamic, 'limit'>;
/**
* Adds an `offset` clause to the query.
*
* Calling this method will skip a number of rows when returning results from this query.
*
* See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
*
* @param offset the `offset` clause.
*
* @example
*
* ```ts
* // Get the 10th-20th people from this query.
* await db.select().from(people).offset(10).limit(10);
* ```
*/
offset(offset: number | Placeholder): PgSelectWithout<this, TDynamic, 'offset'>;
/**
* Adds a `for` clause to the query.
*
* Calling this method will specify a lock strength for this query that controls how strictly it acquires exclusive access to the rows being queried.
*
* See docs: {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE}
*
* @param strength the lock strength.
* @param config the lock configuration.
*/
for(strength: LockStrength, config?: LockConfig): PgSelectWithout<this, TDynamic, 'for'>;
toSQL(): Query;
as<TAlias extends string>(alias: TAlias): SubqueryWithSelection<this['_']['selectedFields'], TAlias>;
$dynamic(): PgSelectDynamic<this>;
}
export interface PgSelectBase<TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TNullabilityMap extends Record<string, JoinNullability> = TTableName extends string ? Record<TTableName, 'not-null'> : {}, TDynamic extends boolean = false, TExcludedMethods extends string = never, TResult extends any[] = SelectResult<TSelection, TSelectMode, TNullabilityMap>[], TSelectedFields extends ColumnsSelection = BuildSubquerySelection<TSelection, TNullabilityMap>> extends PgSelectQueryBuilderBase<PgSelectHKT, TTableName, TSelection, TSelectMode, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields>, QueryPromise<TResult>, SQLWrapper {
}
export declare class PgSelectBase<TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TNullabilityMap extends Record<string, JoinNullability> = TTableName extends string ? Record<TTableName, 'not-null'> : {}, TDynamic extends boolean = false, TExcludedMethods extends string = never, TResult = SelectResult<TSelection, TSelectMode, TNullabilityMap>[], TSelectedFields = BuildSubquerySelection<TSelection, TNullabilityMap>> extends PgSelectQueryBuilderBase<PgSelectHKT, TTableName, TSelection, TSelectMode, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields> implements RunnableQuery<TResult, 'pg'>, SQLWrapper {
static readonly [entityKind]: string;
/**
* Create a prepared statement for this query. This allows
* the database to remember this query for the given session
* and call it by name, rather than specifying the full query.
*
* {@link https://www.postgresql.org/docs/current/sql-prepare.html | Postgres prepare documentation}
*/
prepare(name: string): PgSelectPrepare<this>;
private authToken?;
execute: ReturnType<this['prepare']>['execute'];
}
/**
* Adds `union` set operator to the query.
*
* Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
*
* @example
*
* ```ts
* // Select all unique names from customers and users tables
* import { union } from 'drizzle-orm/pg-core'
*
* await union(
* db.select({ name: users.name }).from(users),
* db.select({ name: customers.name }).from(customers)
* );
* // or
* await db.select({ name: users.name })
* .from(users)
* .union(
* db.select({ name: customers.name }).from(customers)
* );
* ```
*/
export declare const union: PgCreateSetOperatorFn;
/**
* Adds `union all` set operator to the query.
*
* Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
*
* @example
*
* ```ts
* // Select all transaction ids from both online and in-store sales
* import { unionAll } from 'drizzle-orm/pg-core'
*
* await unionAll(
* db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
* );
* // or
* await db.select({ transaction: onlineSales.transactionId })
* .from(onlineSales)
* .unionAll(
* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
* );
* ```
*/
export declare const unionAll: PgCreateSetOperatorFn;
/**
* Adds `intersect` set operator to the query.
*
* Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
*
* @example
*
* ```ts
* // Select course names that are offered in both departments A and B
* import { intersect } from 'drizzle-orm/pg-core'
*
* await intersect(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* // or
* await db.select({ courseName: depA.courseName })
* .from(depA)
* .intersect(
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
export declare const intersect: PgCreateSetOperatorFn;
/**
* Adds `intersect all` set operator to the query.
*
* Calling this method will retain only the rows that are present in both result sets including all duplicates.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect-all}
*
* @example
*
* ```ts
* // Select all products and quantities that are ordered by both regular and VIP customers
* import { intersectAll } from 'drizzle-orm/pg-core'
*
* await intersectAll(
* db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered
* })
* .from(regularCustomerOrders),
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered
* })
* .from(vipCustomerOrders)
* );
* // or
* await db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered
* })
* .from(regularCustomerOrders)
* .intersectAll(
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered
* })
* .from(vipCustomerOrders)
* );
* ```
*/
export declare const intersectAll: PgCreateSetOperatorFn;
/**
* Adds `except` set operator to the query.
*
* Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
*
* @example
*
* ```ts
* // Select all courses offered in department A but not in department B
* import { except } from 'drizzle-orm/pg-core'
*
* await except(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* // or
* await db.select({ courseName: depA.courseName })
* .from(depA)
* .except(
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
export declare const except: PgCreateSetOperatorFn;
/**
* Adds `except all` set operator to the query.
*
* Calling this method will retrieve all rows from the left query, except for the rows that are present in the result set of the right query.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#except-all}
*
* @example
*
* ```ts
* // Select all products that are ordered by regular customers but not by VIP customers
* import { exceptAll } from 'drizzle-orm/pg-core'
*
* await exceptAll(
* db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered
* })
* .from(regularCustomerOrders),
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered
* })
* .from(vipCustomerOrders)
* );
* // or
* await db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered,
* })
* .from(regularCustomerOrders)
* .exceptAll(
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered,
* })
* .from(vipCustomerOrders)
* );
* ```
*/
export declare const exceptAll: PgCreateSetOperatorFn;

View File

@ -0,0 +1,722 @@
import { entityKind } from "../../entity.js";
import type { PgColumn } from "../columns/index.js";
import type { PgDialect } from "../dialect.js";
import type { PgSession } from "../session.js";
import type { SubqueryWithSelection } from "../subquery.js";
import type { PgTable } from "../table.js";
import { PgViewBase } from "../view-base.js";
import { TypedQueryBuilder } from "../../query-builders/query-builder.js";
import type { BuildSubquerySelection, GetSelectTableName, GetSelectTableSelection, JoinNullability, SelectMode, SelectResult } from "../../query-builders/select.types.js";
import { QueryPromise } from "../../query-promise.js";
import type { RunnableQuery } from "../../runnable-query.js";
import { SQL } from "../../sql/sql.js";
import type { ColumnsSelection, Placeholder, Query, SQLWrapper } from "../../sql/sql.js";
import { Subquery } from "../../subquery.js";
import { type ValueOrArray } from "../../utils.js";
import type { CreatePgSelectFromBuilderMode, GetPgSetOperators, LockConfig, LockStrength, PgCreateSetOperatorFn, PgSelectConfig, PgSelectDynamic, PgSelectHKT, PgSelectHKTBase, PgSelectJoinFn, PgSelectPrepare, PgSelectWithout, PgSetOperatorExcludedMethods, PgSetOperatorWithResult, SelectedFields, SetOperatorRightSelect } from "./select.types.js";
export declare class PgSelectBuilder<TSelection extends SelectedFields | undefined, TBuilderMode extends 'db' | 'qb' = 'db'> {
static readonly [entityKind]: string;
private fields;
private session;
private dialect;
private withList;
private distinct;
constructor(config: {
fields: TSelection;
session: PgSession | undefined;
dialect: PgDialect;
withList?: Subquery[];
distinct?: boolean | {
on: (PgColumn | SQLWrapper)[];
};
});
private authToken?;
/**
* Specify the table, subquery, or other target that you're
* building a select query against.
*
* {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FROM | Postgres from documentation}
*/
from<TFrom extends PgTable | Subquery | PgViewBase | SQL>(source: TFrom): CreatePgSelectFromBuilderMode<TBuilderMode, GetSelectTableName<TFrom>, TSelection extends undefined ? GetSelectTableSelection<TFrom> : TSelection, TSelection extends undefined ? 'single' : 'partial'>;
}
export declare abstract class PgSelectQueryBuilderBase<THKT extends PgSelectHKTBase, TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TNullabilityMap extends Record<string, JoinNullability> = TTableName extends string ? Record<TTableName, 'not-null'> : {}, TDynamic extends boolean = false, TExcludedMethods extends string = never, TResult extends any[] = SelectResult<TSelection, TSelectMode, TNullabilityMap>[], TSelectedFields extends ColumnsSelection = BuildSubquerySelection<TSelection, TNullabilityMap>> extends TypedQueryBuilder<TSelectedFields, TResult> {
static readonly [entityKind]: string;
readonly _: {
readonly dialect: 'pg';
readonly hkt: THKT;
readonly tableName: TTableName;
readonly selection: TSelection;
readonly selectMode: TSelectMode;
readonly nullabilityMap: TNullabilityMap;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
readonly result: TResult;
readonly selectedFields: TSelectedFields;
};
protected config: PgSelectConfig;
protected joinsNotNullableMap: Record<string, boolean>;
private tableName;
private isPartialSelect;
protected session: PgSession | undefined;
protected dialect: PgDialect;
constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }: {
table: PgSelectConfig['table'];
fields: PgSelectConfig['fields'];
isPartialSelect: boolean;
session: PgSession | undefined;
dialect: PgDialect;
withList: Subquery[];
distinct: boolean | {
on: (PgColumn | SQLWrapper)[];
} | undefined;
});
private createJoin;
/**
* Executes a `left join` operation by adding another table to the current query.
*
* Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User; pets: Pet | null }[] = await db.select()
* .from(users)
* .leftJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number | null }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .leftJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
leftJoin: PgSelectJoinFn<this, TDynamic, "left">;
/**
* Executes a `right join` operation by adding another table to the current query.
*
* Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User | null; pets: Pet }[] = await db.select()
* .from(users)
* .rightJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number | null; petId: number }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .rightJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
rightJoin: PgSelectJoinFn<this, TDynamic, "right">;
/**
* Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
*
* Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User; pets: Pet }[] = await db.select()
* .from(users)
* .innerJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .innerJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
innerJoin: PgSelectJoinFn<this, TDynamic, "inner">;
/**
* Executes a `full join` operation by combining rows from two tables into a new table.
*
* Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User | null; pets: Pet | null }[] = await db.select()
* .from(users)
* .fullJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number | null; petId: number | null }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .fullJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
fullJoin: PgSelectJoinFn<this, TDynamic, "full">;
private createSetOperator;
/**
* Adds `union` set operator to the query.
*
* Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
*
* @example
*
* ```ts
* // Select all unique names from customers and users tables
* await db.select({ name: users.name })
* .from(users)
* .union(
* db.select({ name: customers.name }).from(customers)
* );
* // or
* import { union } from 'drizzle-orm/pg-core'
*
* await union(
* db.select({ name: users.name }).from(users),
* db.select({ name: customers.name }).from(customers)
* );
* ```
*/
union: <TValue extends PgSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetPgSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => PgSelectWithout<this, TDynamic, PgSetOperatorExcludedMethods, true>;
/**
* Adds `union all` set operator to the query.
*
* Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
*
* @example
*
* ```ts
* // Select all transaction ids from both online and in-store sales
* await db.select({ transaction: onlineSales.transactionId })
* .from(onlineSales)
* .unionAll(
* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
* );
* // or
* import { unionAll } from 'drizzle-orm/pg-core'
*
* await unionAll(
* db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
* );
* ```
*/
unionAll: <TValue extends PgSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetPgSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => PgSelectWithout<this, TDynamic, PgSetOperatorExcludedMethods, true>;
/**
* Adds `intersect` set operator to the query.
*
* Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
*
* @example
*
* ```ts
* // Select course names that are offered in both departments A and B
* await db.select({ courseName: depA.courseName })
* .from(depA)
* .intersect(
* db.select({ courseName: depB.courseName }).from(depB)
* );
* // or
* import { intersect } from 'drizzle-orm/pg-core'
*
* await intersect(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
intersect: <TValue extends PgSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetPgSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => PgSelectWithout<this, TDynamic, PgSetOperatorExcludedMethods, true>;
/**
* Adds `intersect all` set operator to the query.
*
* Calling this method will retain only the rows that are present in both result sets including all duplicates.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect-all}
*
* @example
*
* ```ts
* // Select all products and quantities that are ordered by both regular and VIP customers
* await db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered
* })
* .from(regularCustomerOrders)
* .intersectAll(
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered
* })
* .from(vipCustomerOrders)
* );
* // or
* import { intersectAll } from 'drizzle-orm/pg-core'
*
* await intersectAll(
* db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered
* })
* .from(regularCustomerOrders),
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered
* })
* .from(vipCustomerOrders)
* );
* ```
*/
intersectAll: <TValue extends PgSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetPgSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => PgSelectWithout<this, TDynamic, PgSetOperatorExcludedMethods, true>;
/**
* Adds `except` set operator to the query.
*
* Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
*
* @example
*
* ```ts
* // Select all courses offered in department A but not in department B
* await db.select({ courseName: depA.courseName })
* .from(depA)
* .except(
* db.select({ courseName: depB.courseName }).from(depB)
* );
* // or
* import { except } from 'drizzle-orm/pg-core'
*
* await except(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
except: <TValue extends PgSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetPgSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => PgSelectWithout<this, TDynamic, PgSetOperatorExcludedMethods, true>;
/**
* Adds `except all` set operator to the query.
*
* Calling this method will retrieve all rows from the left query, except for the rows that are present in the result set of the right query.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#except-all}
*
* @example
*
* ```ts
* // Select all products that are ordered by regular customers but not by VIP customers
* await db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered,
* })
* .from(regularCustomerOrders)
* .exceptAll(
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered,
* })
* .from(vipCustomerOrders)
* );
* // or
* import { exceptAll } from 'drizzle-orm/pg-core'
*
* await exceptAll(
* db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered
* })
* .from(regularCustomerOrders),
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered
* })
* .from(vipCustomerOrders)
* );
* ```
*/
exceptAll: <TValue extends PgSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetPgSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => PgSelectWithout<this, TDynamic, PgSetOperatorExcludedMethods, true>;
/**
* Adds a `where` clause to the query.
*
* Calling this method will select only those rows that fulfill a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/select#filtering}
*
* @param where the `where` clause.
*
* @example
* You can use conditional operators and `sql function` to filter the rows to be selected.
*
* ```ts
* // Select all cars with green color
* await db.select().from(cars).where(eq(cars.color, 'green'));
* // or
* await db.select().from(cars).where(sql`${cars.color} = 'green'`)
* ```
*
* You can logically combine conditional operators with `and()` and `or()` operators:
*
* ```ts
* // Select all BMW cars with a green color
* await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
*
* // Select all cars with the green or blue color
* await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where: ((aliases: this['_']['selection']) => SQL | undefined) | SQL | undefined): PgSelectWithout<this, TDynamic, 'where'>;
/**
* Adds a `having` clause to the query.
*
* Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
*
* @param having the `having` clause.
*
* @example
*
* ```ts
* // Select all brands with more than one car
* await db.select({
* brand: cars.brand,
* count: sql<number>`cast(count(${cars.id}) as int)`,
* })
* .from(cars)
* .groupBy(cars.brand)
* .having(({ count }) => gt(count, 1));
* ```
*/
having(having: ((aliases: this['_']['selection']) => SQL | undefined) | SQL | undefined): PgSelectWithout<this, TDynamic, 'having'>;
/**
* Adds a `group by` clause to the query.
*
* Calling this method will group rows that have the same values into summary rows, often used for aggregation purposes.
*
* See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
*
* @example
*
* ```ts
* // Group and count people by their last names
* await db.select({
* lastName: people.lastName,
* count: sql<number>`cast(count(*) as int)`
* })
* .from(people)
* .groupBy(people.lastName);
* ```
*/
groupBy(builder: (aliases: this['_']['selection']) => ValueOrArray<PgColumn | SQL | SQL.Aliased>): PgSelectWithout<this, TDynamic, 'groupBy'>;
groupBy(...columns: (PgColumn | SQL | SQL.Aliased)[]): PgSelectWithout<this, TDynamic, 'groupBy'>;
/**
* Adds an `order by` clause to the query.
*
* Calling this method will sort the result-set in ascending or descending order. By default, the sort order is ascending.
*
* See docs: {@link https://orm.drizzle.team/docs/select#order-by}
*
* @example
*
* ```
* // Select cars ordered by year
* await db.select().from(cars).orderBy(cars.year);
* ```
*
* You can specify whether results are in ascending or descending order with the `asc()` and `desc()` operators.
*
* ```ts
* // Select cars ordered by year in descending order
* await db.select().from(cars).orderBy(desc(cars.year));
*
* // Select cars ordered by year and price
* await db.select().from(cars).orderBy(asc(cars.year), desc(cars.price));
* ```
*/
orderBy(builder: (aliases: this['_']['selection']) => ValueOrArray<PgColumn | SQL | SQL.Aliased>): PgSelectWithout<this, TDynamic, 'orderBy'>;
orderBy(...columns: (PgColumn | SQL | SQL.Aliased)[]): PgSelectWithout<this, TDynamic, 'orderBy'>;
/**
* Adds a `limit` clause to the query.
*
* Calling this method will set the maximum number of rows that will be returned by this query.
*
* See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
*
* @param limit the `limit` clause.
*
* @example
*
* ```ts
* // Get the first 10 people from this query.
* await db.select().from(people).limit(10);
* ```
*/
limit(limit: number | Placeholder): PgSelectWithout<this, TDynamic, 'limit'>;
/**
* Adds an `offset` clause to the query.
*
* Calling this method will skip a number of rows when returning results from this query.
*
* See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
*
* @param offset the `offset` clause.
*
* @example
*
* ```ts
* // Get the 10th-20th people from this query.
* await db.select().from(people).offset(10).limit(10);
* ```
*/
offset(offset: number | Placeholder): PgSelectWithout<this, TDynamic, 'offset'>;
/**
* Adds a `for` clause to the query.
*
* Calling this method will specify a lock strength for this query that controls how strictly it acquires exclusive access to the rows being queried.
*
* See docs: {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE}
*
* @param strength the lock strength.
* @param config the lock configuration.
*/
for(strength: LockStrength, config?: LockConfig): PgSelectWithout<this, TDynamic, 'for'>;
toSQL(): Query;
as<TAlias extends string>(alias: TAlias): SubqueryWithSelection<this['_']['selectedFields'], TAlias>;
$dynamic(): PgSelectDynamic<this>;
}
export interface PgSelectBase<TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TNullabilityMap extends Record<string, JoinNullability> = TTableName extends string ? Record<TTableName, 'not-null'> : {}, TDynamic extends boolean = false, TExcludedMethods extends string = never, TResult extends any[] = SelectResult<TSelection, TSelectMode, TNullabilityMap>[], TSelectedFields extends ColumnsSelection = BuildSubquerySelection<TSelection, TNullabilityMap>> extends PgSelectQueryBuilderBase<PgSelectHKT, TTableName, TSelection, TSelectMode, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields>, QueryPromise<TResult>, SQLWrapper {
}
export declare class PgSelectBase<TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TNullabilityMap extends Record<string, JoinNullability> = TTableName extends string ? Record<TTableName, 'not-null'> : {}, TDynamic extends boolean = false, TExcludedMethods extends string = never, TResult = SelectResult<TSelection, TSelectMode, TNullabilityMap>[], TSelectedFields = BuildSubquerySelection<TSelection, TNullabilityMap>> extends PgSelectQueryBuilderBase<PgSelectHKT, TTableName, TSelection, TSelectMode, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields> implements RunnableQuery<TResult, 'pg'>, SQLWrapper {
static readonly [entityKind]: string;
/**
* Create a prepared statement for this query. This allows
* the database to remember this query for the given session
* and call it by name, rather than specifying the full query.
*
* {@link https://www.postgresql.org/docs/current/sql-prepare.html | Postgres prepare documentation}
*/
prepare(name: string): PgSelectPrepare<this>;
private authToken?;
execute: ReturnType<this['prepare']>['execute'];
}
/**
* Adds `union` set operator to the query.
*
* Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
*
* @example
*
* ```ts
* // Select all unique names from customers and users tables
* import { union } from 'drizzle-orm/pg-core'
*
* await union(
* db.select({ name: users.name }).from(users),
* db.select({ name: customers.name }).from(customers)
* );
* // or
* await db.select({ name: users.name })
* .from(users)
* .union(
* db.select({ name: customers.name }).from(customers)
* );
* ```
*/
export declare const union: PgCreateSetOperatorFn;
/**
* Adds `union all` set operator to the query.
*
* Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
*
* @example
*
* ```ts
* // Select all transaction ids from both online and in-store sales
* import { unionAll } from 'drizzle-orm/pg-core'
*
* await unionAll(
* db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
* );
* // or
* await db.select({ transaction: onlineSales.transactionId })
* .from(onlineSales)
* .unionAll(
* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
* );
* ```
*/
export declare const unionAll: PgCreateSetOperatorFn;
/**
* Adds `intersect` set operator to the query.
*
* Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
*
* @example
*
* ```ts
* // Select course names that are offered in both departments A and B
* import { intersect } from 'drizzle-orm/pg-core'
*
* await intersect(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* // or
* await db.select({ courseName: depA.courseName })
* .from(depA)
* .intersect(
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
export declare const intersect: PgCreateSetOperatorFn;
/**
* Adds `intersect all` set operator to the query.
*
* Calling this method will retain only the rows that are present in both result sets including all duplicates.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect-all}
*
* @example
*
* ```ts
* // Select all products and quantities that are ordered by both regular and VIP customers
* import { intersectAll } from 'drizzle-orm/pg-core'
*
* await intersectAll(
* db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered
* })
* .from(regularCustomerOrders),
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered
* })
* .from(vipCustomerOrders)
* );
* // or
* await db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered
* })
* .from(regularCustomerOrders)
* .intersectAll(
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered
* })
* .from(vipCustomerOrders)
* );
* ```
*/
export declare const intersectAll: PgCreateSetOperatorFn;
/**
* Adds `except` set operator to the query.
*
* Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
*
* @example
*
* ```ts
* // Select all courses offered in department A but not in department B
* import { except } from 'drizzle-orm/pg-core'
*
* await except(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* // or
* await db.select({ courseName: depA.courseName })
* .from(depA)
* .except(
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
export declare const except: PgCreateSetOperatorFn;
/**
* Adds `except all` set operator to the query.
*
* Calling this method will retrieve all rows from the left query, except for the rows that are present in the result set of the right query.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#except-all}
*
* @example
*
* ```ts
* // Select all products that are ordered by regular customers but not by VIP customers
* import { exceptAll } from 'drizzle-orm/pg-core'
*
* await exceptAll(
* db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered
* })
* .from(regularCustomerOrders),
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered
* })
* .from(vipCustomerOrders)
* );
* // or
* await db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered,
* })
* .from(regularCustomerOrders)
* .exceptAll(
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered,
* })
* .from(vipCustomerOrders)
* );
* ```
*/
export declare const exceptAll: PgCreateSetOperatorFn;

View File

@ -0,0 +1,754 @@
import { entityKind, is } from "../../entity.js";
import { PgViewBase } from "../view-base.js";
import { TypedQueryBuilder } from "../../query-builders/query-builder.js";
import { QueryPromise } from "../../query-promise.js";
import { SelectionProxyHandler } from "../../selection-proxy.js";
import { SQL, View } from "../../sql/sql.js";
import { Subquery } from "../../subquery.js";
import { Table } from "../../table.js";
import { tracer } from "../../tracing.js";
import {
applyMixins,
getTableColumns,
getTableLikeName,
haveSameKeys
} from "../../utils.js";
import { orderSelectedFields } from "../../utils.js";
import { ViewBaseConfig } from "../../view-common.js";
class PgSelectBuilder {
static [entityKind] = "PgSelectBuilder";
fields;
session;
dialect;
withList = [];
distinct;
constructor(config) {
this.fields = config.fields;
this.session = config.session;
this.dialect = config.dialect;
if (config.withList) {
this.withList = config.withList;
}
this.distinct = config.distinct;
}
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
/**
* Specify the table, subquery, or other target that you're
* building a select query against.
*
* {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FROM | Postgres from documentation}
*/
from(source) {
const isPartialSelect = !!this.fields;
let fields;
if (this.fields) {
fields = this.fields;
} else if (is(source, Subquery)) {
fields = Object.fromEntries(
Object.keys(source._.selectedFields).map((key) => [key, source[key]])
);
} else if (is(source, PgViewBase)) {
fields = source[ViewBaseConfig].selectedFields;
} else if (is(source, SQL)) {
fields = {};
} else {
fields = getTableColumns(source);
}
return new PgSelectBase({
table: source,
fields,
isPartialSelect,
session: this.session,
dialect: this.dialect,
withList: this.withList,
distinct: this.distinct
}).setToken(this.authToken);
}
}
class PgSelectQueryBuilderBase extends TypedQueryBuilder {
static [entityKind] = "PgSelectQueryBuilder";
_;
config;
joinsNotNullableMap;
tableName;
isPartialSelect;
session;
dialect;
constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }) {
super();
this.config = {
withList,
table,
fields: { ...fields },
distinct,
setOperators: []
};
this.isPartialSelect = isPartialSelect;
this.session = session;
this.dialect = dialect;
this._ = {
selectedFields: fields
};
this.tableName = getTableLikeName(table);
this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
}
createJoin(joinType) {
return (table, on) => {
const baseTableName = this.tableName;
const tableName = getTableLikeName(table);
if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) {
throw new Error(`Alias "${tableName}" is already used in this query`);
}
if (!this.isPartialSelect) {
if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") {
this.config.fields = {
[baseTableName]: this.config.fields
};
}
if (typeof tableName === "string" && !is(table, SQL)) {
const selection = is(table, Subquery) ? table._.selectedFields : is(table, View) ? table[ViewBaseConfig].selectedFields : table[Table.Symbol.Columns];
this.config.fields[tableName] = selection;
}
}
if (typeof on === "function") {
on = on(
new Proxy(
this.config.fields,
new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
)
);
}
if (!this.config.joins) {
this.config.joins = [];
}
this.config.joins.push({ on, table, joinType, alias: tableName });
if (typeof tableName === "string") {
switch (joinType) {
case "left": {
this.joinsNotNullableMap[tableName] = false;
break;
}
case "right": {
this.joinsNotNullableMap = Object.fromEntries(
Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
);
this.joinsNotNullableMap[tableName] = true;
break;
}
case "inner": {
this.joinsNotNullableMap[tableName] = true;
break;
}
case "full": {
this.joinsNotNullableMap = Object.fromEntries(
Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
);
this.joinsNotNullableMap[tableName] = false;
break;
}
}
}
return this;
};
}
/**
* Executes a `left join` operation by adding another table to the current query.
*
* Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User; pets: Pet | null }[] = await db.select()
* .from(users)
* .leftJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number | null }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .leftJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
leftJoin = this.createJoin("left");
/**
* Executes a `right join` operation by adding another table to the current query.
*
* Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User | null; pets: Pet }[] = await db.select()
* .from(users)
* .rightJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number | null; petId: number }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .rightJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
rightJoin = this.createJoin("right");
/**
* Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
*
* Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User; pets: Pet }[] = await db.select()
* .from(users)
* .innerJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .innerJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
innerJoin = this.createJoin("inner");
/**
* Executes a `full join` operation by combining rows from two tables into a new table.
*
* Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User | null; pets: Pet | null }[] = await db.select()
* .from(users)
* .fullJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number | null; petId: number | null }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .fullJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
fullJoin = this.createJoin("full");
createSetOperator(type, isAll) {
return (rightSelection) => {
const rightSelect = typeof rightSelection === "function" ? rightSelection(getPgSetOperators()) : rightSelection;
if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) {
throw new Error(
"Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
);
}
this.config.setOperators.push({ type, isAll, rightSelect });
return this;
};
}
/**
* Adds `union` set operator to the query.
*
* Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
*
* @example
*
* ```ts
* // Select all unique names from customers and users tables
* await db.select({ name: users.name })
* .from(users)
* .union(
* db.select({ name: customers.name }).from(customers)
* );
* // or
* import { union } from 'drizzle-orm/pg-core'
*
* await union(
* db.select({ name: users.name }).from(users),
* db.select({ name: customers.name }).from(customers)
* );
* ```
*/
union = this.createSetOperator("union", false);
/**
* Adds `union all` set operator to the query.
*
* Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
*
* @example
*
* ```ts
* // Select all transaction ids from both online and in-store sales
* await db.select({ transaction: onlineSales.transactionId })
* .from(onlineSales)
* .unionAll(
* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
* );
* // or
* import { unionAll } from 'drizzle-orm/pg-core'
*
* await unionAll(
* db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
* );
* ```
*/
unionAll = this.createSetOperator("union", true);
/**
* Adds `intersect` set operator to the query.
*
* Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
*
* @example
*
* ```ts
* // Select course names that are offered in both departments A and B
* await db.select({ courseName: depA.courseName })
* .from(depA)
* .intersect(
* db.select({ courseName: depB.courseName }).from(depB)
* );
* // or
* import { intersect } from 'drizzle-orm/pg-core'
*
* await intersect(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
intersect = this.createSetOperator("intersect", false);
/**
* Adds `intersect all` set operator to the query.
*
* Calling this method will retain only the rows that are present in both result sets including all duplicates.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect-all}
*
* @example
*
* ```ts
* // Select all products and quantities that are ordered by both regular and VIP customers
* await db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered
* })
* .from(regularCustomerOrders)
* .intersectAll(
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered
* })
* .from(vipCustomerOrders)
* );
* // or
* import { intersectAll } from 'drizzle-orm/pg-core'
*
* await intersectAll(
* db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered
* })
* .from(regularCustomerOrders),
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered
* })
* .from(vipCustomerOrders)
* );
* ```
*/
intersectAll = this.createSetOperator("intersect", true);
/**
* Adds `except` set operator to the query.
*
* Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
*
* @example
*
* ```ts
* // Select all courses offered in department A but not in department B
* await db.select({ courseName: depA.courseName })
* .from(depA)
* .except(
* db.select({ courseName: depB.courseName }).from(depB)
* );
* // or
* import { except } from 'drizzle-orm/pg-core'
*
* await except(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
except = this.createSetOperator("except", false);
/**
* Adds `except all` set operator to the query.
*
* Calling this method will retrieve all rows from the left query, except for the rows that are present in the result set of the right query.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#except-all}
*
* @example
*
* ```ts
* // Select all products that are ordered by regular customers but not by VIP customers
* await db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered,
* })
* .from(regularCustomerOrders)
* .exceptAll(
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered,
* })
* .from(vipCustomerOrders)
* );
* // or
* import { exceptAll } from 'drizzle-orm/pg-core'
*
* await exceptAll(
* db.select({
* productId: regularCustomerOrders.productId,
* quantityOrdered: regularCustomerOrders.quantityOrdered
* })
* .from(regularCustomerOrders),
* db.select({
* productId: vipCustomerOrders.productId,
* quantityOrdered: vipCustomerOrders.quantityOrdered
* })
* .from(vipCustomerOrders)
* );
* ```
*/
exceptAll = this.createSetOperator("except", true);
/** @internal */
addSetOperators(setOperators) {
this.config.setOperators.push(...setOperators);
return this;
}
/**
* Adds a `where` clause to the query.
*
* Calling this method will select only those rows that fulfill a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/select#filtering}
*
* @param where the `where` clause.
*
* @example
* You can use conditional operators and `sql function` to filter the rows to be selected.
*
* ```ts
* // Select all cars with green color
* await db.select().from(cars).where(eq(cars.color, 'green'));
* // or
* await db.select().from(cars).where(sql`${cars.color} = 'green'`)
* ```
*
* You can logically combine conditional operators with `and()` and `or()` operators:
*
* ```ts
* // Select all BMW cars with a green color
* await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
*
* // Select all cars with the green or blue color
* await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where) {
if (typeof where === "function") {
where = where(
new Proxy(
this.config.fields,
new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
)
);
}
this.config.where = where;
return this;
}
/**
* Adds a `having` clause to the query.
*
* Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
*
* @param having the `having` clause.
*
* @example
*
* ```ts
* // Select all brands with more than one car
* await db.select({
* brand: cars.brand,
* count: sql<number>`cast(count(${cars.id}) as int)`,
* })
* .from(cars)
* .groupBy(cars.brand)
* .having(({ count }) => gt(count, 1));
* ```
*/
having(having) {
if (typeof having === "function") {
having = having(
new Proxy(
this.config.fields,
new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
)
);
}
this.config.having = having;
return this;
}
groupBy(...columns) {
if (typeof columns[0] === "function") {
const groupBy = columns[0](
new Proxy(
this.config.fields,
new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
)
);
this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
} else {
this.config.groupBy = columns;
}
return this;
}
orderBy(...columns) {
if (typeof columns[0] === "function") {
const orderBy = columns[0](
new Proxy(
this.config.fields,
new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
)
);
const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
if (this.config.setOperators.length > 0) {
this.config.setOperators.at(-1).orderBy = orderByArray;
} else {
this.config.orderBy = orderByArray;
}
} else {
const orderByArray = columns;
if (this.config.setOperators.length > 0) {
this.config.setOperators.at(-1).orderBy = orderByArray;
} else {
this.config.orderBy = orderByArray;
}
}
return this;
}
/**
* Adds a `limit` clause to the query.
*
* Calling this method will set the maximum number of rows that will be returned by this query.
*
* See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
*
* @param limit the `limit` clause.
*
* @example
*
* ```ts
* // Get the first 10 people from this query.
* await db.select().from(people).limit(10);
* ```
*/
limit(limit) {
if (this.config.setOperators.length > 0) {
this.config.setOperators.at(-1).limit = limit;
} else {
this.config.limit = limit;
}
return this;
}
/**
* Adds an `offset` clause to the query.
*
* Calling this method will skip a number of rows when returning results from this query.
*
* See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
*
* @param offset the `offset` clause.
*
* @example
*
* ```ts
* // Get the 10th-20th people from this query.
* await db.select().from(people).offset(10).limit(10);
* ```
*/
offset(offset) {
if (this.config.setOperators.length > 0) {
this.config.setOperators.at(-1).offset = offset;
} else {
this.config.offset = offset;
}
return this;
}
/**
* Adds a `for` clause to the query.
*
* Calling this method will specify a lock strength for this query that controls how strictly it acquires exclusive access to the rows being queried.
*
* See docs: {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE}
*
* @param strength the lock strength.
* @param config the lock configuration.
*/
for(strength, config = {}) {
this.config.lockingClause = { strength, config };
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildSelectQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
as(alias) {
return new Proxy(
new Subquery(this.getSQL(), this.config.fields, alias),
new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
);
}
/** @internal */
getSelectedFields() {
return new Proxy(
this.config.fields,
new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
);
}
$dynamic() {
return this;
}
}
class PgSelectBase extends PgSelectQueryBuilderBase {
static [entityKind] = "PgSelect";
/** @internal */
_prepare(name) {
const { session, config, dialect, joinsNotNullableMap, authToken } = this;
if (!session) {
throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
}
return tracer.startActiveSpan("drizzle.prepareQuery", () => {
const fieldsList = orderSelectedFields(config.fields);
const query = session.prepareQuery(dialect.sqlToQuery(this.getSQL()), fieldsList, name, true);
query.joinsNotNullableMap = joinsNotNullableMap;
return query.setToken(authToken);
});
}
/**
* Create a prepared statement for this query. This allows
* the database to remember this query for the given session
* and call it by name, rather than specifying the full query.
*
* {@link https://www.postgresql.org/docs/current/sql-prepare.html | Postgres prepare documentation}
*/
prepare(name) {
return this._prepare(name);
}
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
execute = (placeholderValues) => {
return tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(placeholderValues, this.authToken);
});
};
}
applyMixins(PgSelectBase, [QueryPromise]);
function createSetOperator(type, isAll) {
return (leftSelect, rightSelect, ...restSelects) => {
const setOperators = [rightSelect, ...restSelects].map((select) => ({
type,
isAll,
rightSelect: select
}));
for (const setOperator of setOperators) {
if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {
throw new Error(
"Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
);
}
}
return leftSelect.addSetOperators(setOperators);
};
}
const getPgSetOperators = () => ({
union,
unionAll,
intersect,
intersectAll,
except,
exceptAll
});
const union = createSetOperator("union", false);
const unionAll = createSetOperator("union", true);
const intersect = createSetOperator("intersect", false);
const intersectAll = createSetOperator("intersect", true);
const except = createSetOperator("except", false);
const exceptAll = createSetOperator("except", true);
export {
PgSelectBase,
PgSelectBuilder,
PgSelectQueryBuilderBase,
except,
exceptAll,
intersect,
intersectAll,
union,
unionAll
};
//# sourceMappingURL=select.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,17 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var select_types_exports = {};
module.exports = __toCommonJS(select_types_exports);
//# sourceMappingURL=select.types.cjs.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,138 @@
import type { SelectedFields as SelectedFieldsBase, SelectedFieldsFlat as SelectedFieldsFlatBase, SelectedFieldsOrdered as SelectedFieldsOrderedBase } from "../../operations.cjs";
import type { PgColumn } from "../columns/index.cjs";
import type { PgTable, PgTableWithColumns } from "../table.cjs";
import type { PgViewBase } from "../view-base.cjs";
import type { PgViewWithSelection } from "../view.cjs";
import type { TypedQueryBuilder } from "../../query-builders/query-builder.cjs";
import type { AppendToNullabilityMap, AppendToResult, BuildSubquerySelection, GetSelectTableName, JoinNullability, JoinType, MapColumnsToTableAlias, SelectMode, SelectResult, SetOperator } from "../../query-builders/select.types.cjs";
import type { ColumnsSelection, Placeholder, SQL, SQLWrapper, View } from "../../sql/sql.cjs";
import type { Subquery } from "../../subquery.cjs";
import type { Table, UpdateTableConfig } from "../../table.cjs";
import type { Assume, ValidateShape, ValueOrArray } from "../../utils.cjs";
import type { PgPreparedQuery, PreparedQueryConfig } from "../session.cjs";
import type { PgSelectBase, PgSelectQueryBuilderBase } from "./select.cjs";
export interface PgSelectJoinConfig {
on: SQL | undefined;
table: PgTable | Subquery | PgViewBase | SQL;
alias: string | undefined;
joinType: JoinType;
lateral?: boolean;
}
export type BuildAliasTable<TTable extends PgTable | View, TAlias extends string> = TTable extends Table ? PgTableWithColumns<UpdateTableConfig<TTable['_']['config'], {
name: TAlias;
columns: MapColumnsToTableAlias<TTable['_']['columns'], TAlias, 'pg'>;
}>> : TTable extends View ? PgViewWithSelection<TAlias, TTable['_']['existing'], MapColumnsToTableAlias<TTable['_']['selectedFields'], TAlias, 'pg'>> : never;
export interface PgSelectConfig {
withList?: Subquery[];
fields: Record<string, unknown>;
fieldsFlat?: SelectedFieldsOrdered;
where?: SQL;
having?: SQL;
table: PgTable | Subquery | PgViewBase | SQL;
limit?: number | Placeholder;
offset?: number | Placeholder;
joins?: PgSelectJoinConfig[];
orderBy?: (PgColumn | SQL | SQL.Aliased)[];
groupBy?: (PgColumn | SQL | SQL.Aliased)[];
lockingClause?: {
strength: LockStrength;
config: LockConfig;
};
distinct?: boolean | {
on: (PgColumn | SQLWrapper)[];
};
setOperators: {
rightSelect: TypedQueryBuilder<any, any>;
type: SetOperator;
isAll: boolean;
orderBy?: (PgColumn | SQL | SQL.Aliased)[];
limit?: number | Placeholder;
offset?: number | Placeholder;
}[];
}
export type PgSelectJoin<T extends AnyPgSelectQueryBuilder, TDynamic extends boolean, TJoinType extends JoinType, TJoinedTable extends PgTable | Subquery | PgViewBase | SQL, TJoinedName extends GetSelectTableName<TJoinedTable> = GetSelectTableName<TJoinedTable>> = T extends any ? PgSelectWithout<PgSelectKind<T['_']['hkt'], T['_']['tableName'], AppendToResult<T['_']['tableName'], T['_']['selection'], TJoinedName, TJoinedTable extends Table ? TJoinedTable['_']['columns'] : TJoinedTable extends Subquery ? Assume<TJoinedTable['_']['selectedFields'], SelectedFields> : never, T['_']['selectMode']>, T['_']['selectMode'] extends 'partial' ? T['_']['selectMode'] : 'multiple', AppendToNullabilityMap<T['_']['nullabilityMap'], TJoinedName, TJoinType>, T['_']['dynamic'], T['_']['excludedMethods']>, TDynamic, T['_']['excludedMethods']> : never;
export type PgSelectJoinFn<T extends AnyPgSelectQueryBuilder, TDynamic extends boolean, TJoinType extends JoinType> = <TJoinedTable extends PgTable | Subquery | PgViewBase | SQL, TJoinedName extends GetSelectTableName<TJoinedTable> = GetSelectTableName<TJoinedTable>>(table: TJoinedTable, on: ((aliases: T['_']['selection']) => SQL | undefined) | SQL | undefined) => PgSelectJoin<T, TDynamic, TJoinType, TJoinedTable, TJoinedName>;
export type SelectedFieldsFlat = SelectedFieldsFlatBase<PgColumn>;
export type SelectedFields = SelectedFieldsBase<PgColumn, PgTable>;
export type SelectedFieldsOrdered = SelectedFieldsOrderedBase<PgColumn>;
export type LockStrength = 'update' | 'no key update' | 'share' | 'key share';
export type LockConfig = {
of?: ValueOrArray<PgTable>;
} & ({
noWait: true;
skipLocked?: undefined;
} | {
noWait?: undefined;
skipLocked: true;
} | {
noWait?: undefined;
skipLocked?: undefined;
});
export interface PgSelectHKTBase {
tableName: string | undefined;
selection: unknown;
selectMode: SelectMode;
nullabilityMap: unknown;
dynamic: boolean;
excludedMethods: string;
result: unknown;
selectedFields: unknown;
_type: unknown;
}
export type PgSelectKind<T extends PgSelectHKTBase, TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TNullabilityMap extends Record<string, JoinNullability>, TDynamic extends boolean, TExcludedMethods extends string, TResult = SelectResult<TSelection, TSelectMode, TNullabilityMap>[], TSelectedFields = BuildSubquerySelection<TSelection, TNullabilityMap>> = (T & {
tableName: TTableName;
selection: TSelection;
selectMode: TSelectMode;
nullabilityMap: TNullabilityMap;
dynamic: TDynamic;
excludedMethods: TExcludedMethods;
result: TResult;
selectedFields: TSelectedFields;
})['_type'];
export interface PgSelectQueryBuilderHKT extends PgSelectHKTBase {
_type: PgSelectQueryBuilderBase<PgSelectQueryBuilderHKT, this['tableName'], Assume<this['selection'], ColumnsSelection>, this['selectMode'], Assume<this['nullabilityMap'], Record<string, JoinNullability>>, this['dynamic'], this['excludedMethods'], Assume<this['result'], any[]>, Assume<this['selectedFields'], ColumnsSelection>>;
}
export interface PgSelectHKT extends PgSelectHKTBase {
_type: PgSelectBase<this['tableName'], Assume<this['selection'], ColumnsSelection>, this['selectMode'], Assume<this['nullabilityMap'], Record<string, JoinNullability>>, this['dynamic'], this['excludedMethods'], Assume<this['result'], any[]>, Assume<this['selectedFields'], ColumnsSelection>>;
}
export type CreatePgSelectFromBuilderMode<TBuilderMode extends 'db' | 'qb', TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode> = TBuilderMode extends 'db' ? PgSelectBase<TTableName, TSelection, TSelectMode> : PgSelectQueryBuilderBase<PgSelectQueryBuilderHKT, TTableName, TSelection, TSelectMode>;
export type PgSetOperatorExcludedMethods = 'leftJoin' | 'rightJoin' | 'innerJoin' | 'fullJoin' | 'where' | 'having' | 'groupBy' | 'for';
export type PgSelectWithout<T extends AnyPgSelectQueryBuilder, TDynamic extends boolean, K extends keyof T & string, TResetExcluded extends boolean = false> = TDynamic extends true ? T : Omit<PgSelectKind<T['_']['hkt'], T['_']['tableName'], T['_']['selection'], T['_']['selectMode'], T['_']['nullabilityMap'], TDynamic, TResetExcluded extends true ? K : T['_']['excludedMethods'] | K, T['_']['result'], T['_']['selectedFields']>, TResetExcluded extends true ? K : T['_']['excludedMethods'] | K>;
export type PgSelectPrepare<T extends AnyPgSelect> = PgPreparedQuery<PreparedQueryConfig & {
execute: T['_']['result'];
}>;
export type PgSelectDynamic<T extends AnyPgSelectQueryBuilder> = PgSelectKind<T['_']['hkt'], T['_']['tableName'], T['_']['selection'], T['_']['selectMode'], T['_']['nullabilityMap'], true, never, T['_']['result'], T['_']['selectedFields']>;
export type PgSelectQueryBuilder<THKT extends PgSelectHKTBase = PgSelectQueryBuilderHKT, TTableName extends string | undefined = string | undefined, TSelection extends ColumnsSelection = ColumnsSelection, TSelectMode extends SelectMode = SelectMode, TNullabilityMap extends Record<string, JoinNullability> = Record<string, JoinNullability>, TResult extends any[] = unknown[], TSelectedFields extends ColumnsSelection = ColumnsSelection> = PgSelectQueryBuilderBase<THKT, TTableName, TSelection, TSelectMode, TNullabilityMap, true, never, TResult, TSelectedFields>;
export type AnyPgSelectQueryBuilder = PgSelectQueryBuilderBase<any, any, any, any, any, any, any, any, any>;
export type AnyPgSetOperatorInterface = PgSetOperatorInterface<any, any, any, any, any, any, any, any>;
export interface PgSetOperatorInterface<TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TNullabilityMap extends Record<string, JoinNullability> = TTableName extends string ? Record<TTableName, 'not-null'> : {}, TDynamic extends boolean = false, TExcludedMethods extends string = never, TResult extends any[] = SelectResult<TSelection, TSelectMode, TNullabilityMap>[], TSelectedFields extends ColumnsSelection = BuildSubquerySelection<TSelection, TNullabilityMap>> {
_: {
readonly hkt: PgSelectHKT;
readonly tableName: TTableName;
readonly selection: TSelection;
readonly selectMode: TSelectMode;
readonly nullabilityMap: TNullabilityMap;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
readonly result: TResult;
readonly selectedFields: TSelectedFields;
};
}
export type PgSetOperatorWithResult<TResult extends any[]> = PgSetOperatorInterface<any, any, any, any, any, any, TResult, any>;
export type PgSelect<TTableName extends string | undefined = string | undefined, TSelection extends ColumnsSelection = Record<string, any>, TSelectMode extends SelectMode = SelectMode, TNullabilityMap extends Record<string, JoinNullability> = Record<string, JoinNullability>> = PgSelectBase<TTableName, TSelection, TSelectMode, TNullabilityMap, true, never>;
export type AnyPgSelect = PgSelectBase<any, any, any, any, any, any, any, any>;
export type PgSetOperator<TTableName extends string | undefined = string | undefined, TSelection extends ColumnsSelection = Record<string, any>, TSelectMode extends SelectMode = SelectMode, TNullabilityMap extends Record<string, JoinNullability> = Record<string, JoinNullability>> = PgSelectBase<TTableName, TSelection, TSelectMode, TNullabilityMap, true, PgSetOperatorExcludedMethods>;
export type SetOperatorRightSelect<TValue extends PgSetOperatorWithResult<TResult>, TResult extends any[]> = TValue extends PgSetOperatorInterface<any, any, any, any, any, any, infer TValueResult, any> ? ValidateShape<TValueResult[number], TResult[number], TypedQueryBuilder<any, TValueResult>> : TValue;
export type SetOperatorRestSelect<TValue extends readonly PgSetOperatorWithResult<TResult>[], TResult extends any[]> = TValue extends [infer First, ...infer Rest] ? First extends PgSetOperatorInterface<any, any, any, any, any, any, infer TValueResult, any> ? Rest extends AnyPgSetOperatorInterface[] ? [
ValidateShape<TValueResult[number], TResult[number], TypedQueryBuilder<any, TValueResult>>,
...SetOperatorRestSelect<Rest, TResult>
] : ValidateShape<TValueResult[number], TResult[number], TypedQueryBuilder<any, TValueResult>[]> : never : TValue;
export type PgCreateSetOperatorFn = <TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TValue extends PgSetOperatorWithResult<TResult>, TRest extends PgSetOperatorWithResult<TResult>[], TNullabilityMap extends Record<string, JoinNullability> = TTableName extends string ? Record<TTableName, 'not-null'> : {}, TDynamic extends boolean = false, TExcludedMethods extends string = never, TResult extends any[] = SelectResult<TSelection, TSelectMode, TNullabilityMap>[], TSelectedFields extends ColumnsSelection = BuildSubquerySelection<TSelection, TNullabilityMap>>(leftSelect: PgSetOperatorInterface<TTableName, TSelection, TSelectMode, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields>, rightSelect: SetOperatorRightSelect<TValue, TResult>, ...restSelects: SetOperatorRestSelect<TRest, TResult>) => PgSelectWithout<PgSelectBase<TTableName, TSelection, TSelectMode, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields>, false, PgSetOperatorExcludedMethods, true>;
export type GetPgSetOperators = {
union: PgCreateSetOperatorFn;
intersect: PgCreateSetOperatorFn;
except: PgCreateSetOperatorFn;
unionAll: PgCreateSetOperatorFn;
intersectAll: PgCreateSetOperatorFn;
exceptAll: PgCreateSetOperatorFn;
};

View File

@ -0,0 +1,138 @@
import type { SelectedFields as SelectedFieldsBase, SelectedFieldsFlat as SelectedFieldsFlatBase, SelectedFieldsOrdered as SelectedFieldsOrderedBase } from "../../operations.js";
import type { PgColumn } from "../columns/index.js";
import type { PgTable, PgTableWithColumns } from "../table.js";
import type { PgViewBase } from "../view-base.js";
import type { PgViewWithSelection } from "../view.js";
import type { TypedQueryBuilder } from "../../query-builders/query-builder.js";
import type { AppendToNullabilityMap, AppendToResult, BuildSubquerySelection, GetSelectTableName, JoinNullability, JoinType, MapColumnsToTableAlias, SelectMode, SelectResult, SetOperator } from "../../query-builders/select.types.js";
import type { ColumnsSelection, Placeholder, SQL, SQLWrapper, View } from "../../sql/sql.js";
import type { Subquery } from "../../subquery.js";
import type { Table, UpdateTableConfig } from "../../table.js";
import type { Assume, ValidateShape, ValueOrArray } from "../../utils.js";
import type { PgPreparedQuery, PreparedQueryConfig } from "../session.js";
import type { PgSelectBase, PgSelectQueryBuilderBase } from "./select.js";
export interface PgSelectJoinConfig {
on: SQL | undefined;
table: PgTable | Subquery | PgViewBase | SQL;
alias: string | undefined;
joinType: JoinType;
lateral?: boolean;
}
export type BuildAliasTable<TTable extends PgTable | View, TAlias extends string> = TTable extends Table ? PgTableWithColumns<UpdateTableConfig<TTable['_']['config'], {
name: TAlias;
columns: MapColumnsToTableAlias<TTable['_']['columns'], TAlias, 'pg'>;
}>> : TTable extends View ? PgViewWithSelection<TAlias, TTable['_']['existing'], MapColumnsToTableAlias<TTable['_']['selectedFields'], TAlias, 'pg'>> : never;
export interface PgSelectConfig {
withList?: Subquery[];
fields: Record<string, unknown>;
fieldsFlat?: SelectedFieldsOrdered;
where?: SQL;
having?: SQL;
table: PgTable | Subquery | PgViewBase | SQL;
limit?: number | Placeholder;
offset?: number | Placeholder;
joins?: PgSelectJoinConfig[];
orderBy?: (PgColumn | SQL | SQL.Aliased)[];
groupBy?: (PgColumn | SQL | SQL.Aliased)[];
lockingClause?: {
strength: LockStrength;
config: LockConfig;
};
distinct?: boolean | {
on: (PgColumn | SQLWrapper)[];
};
setOperators: {
rightSelect: TypedQueryBuilder<any, any>;
type: SetOperator;
isAll: boolean;
orderBy?: (PgColumn | SQL | SQL.Aliased)[];
limit?: number | Placeholder;
offset?: number | Placeholder;
}[];
}
export type PgSelectJoin<T extends AnyPgSelectQueryBuilder, TDynamic extends boolean, TJoinType extends JoinType, TJoinedTable extends PgTable | Subquery | PgViewBase | SQL, TJoinedName extends GetSelectTableName<TJoinedTable> = GetSelectTableName<TJoinedTable>> = T extends any ? PgSelectWithout<PgSelectKind<T['_']['hkt'], T['_']['tableName'], AppendToResult<T['_']['tableName'], T['_']['selection'], TJoinedName, TJoinedTable extends Table ? TJoinedTable['_']['columns'] : TJoinedTable extends Subquery ? Assume<TJoinedTable['_']['selectedFields'], SelectedFields> : never, T['_']['selectMode']>, T['_']['selectMode'] extends 'partial' ? T['_']['selectMode'] : 'multiple', AppendToNullabilityMap<T['_']['nullabilityMap'], TJoinedName, TJoinType>, T['_']['dynamic'], T['_']['excludedMethods']>, TDynamic, T['_']['excludedMethods']> : never;
export type PgSelectJoinFn<T extends AnyPgSelectQueryBuilder, TDynamic extends boolean, TJoinType extends JoinType> = <TJoinedTable extends PgTable | Subquery | PgViewBase | SQL, TJoinedName extends GetSelectTableName<TJoinedTable> = GetSelectTableName<TJoinedTable>>(table: TJoinedTable, on: ((aliases: T['_']['selection']) => SQL | undefined) | SQL | undefined) => PgSelectJoin<T, TDynamic, TJoinType, TJoinedTable, TJoinedName>;
export type SelectedFieldsFlat = SelectedFieldsFlatBase<PgColumn>;
export type SelectedFields = SelectedFieldsBase<PgColumn, PgTable>;
export type SelectedFieldsOrdered = SelectedFieldsOrderedBase<PgColumn>;
export type LockStrength = 'update' | 'no key update' | 'share' | 'key share';
export type LockConfig = {
of?: ValueOrArray<PgTable>;
} & ({
noWait: true;
skipLocked?: undefined;
} | {
noWait?: undefined;
skipLocked: true;
} | {
noWait?: undefined;
skipLocked?: undefined;
});
export interface PgSelectHKTBase {
tableName: string | undefined;
selection: unknown;
selectMode: SelectMode;
nullabilityMap: unknown;
dynamic: boolean;
excludedMethods: string;
result: unknown;
selectedFields: unknown;
_type: unknown;
}
export type PgSelectKind<T extends PgSelectHKTBase, TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TNullabilityMap extends Record<string, JoinNullability>, TDynamic extends boolean, TExcludedMethods extends string, TResult = SelectResult<TSelection, TSelectMode, TNullabilityMap>[], TSelectedFields = BuildSubquerySelection<TSelection, TNullabilityMap>> = (T & {
tableName: TTableName;
selection: TSelection;
selectMode: TSelectMode;
nullabilityMap: TNullabilityMap;
dynamic: TDynamic;
excludedMethods: TExcludedMethods;
result: TResult;
selectedFields: TSelectedFields;
})['_type'];
export interface PgSelectQueryBuilderHKT extends PgSelectHKTBase {
_type: PgSelectQueryBuilderBase<PgSelectQueryBuilderHKT, this['tableName'], Assume<this['selection'], ColumnsSelection>, this['selectMode'], Assume<this['nullabilityMap'], Record<string, JoinNullability>>, this['dynamic'], this['excludedMethods'], Assume<this['result'], any[]>, Assume<this['selectedFields'], ColumnsSelection>>;
}
export interface PgSelectHKT extends PgSelectHKTBase {
_type: PgSelectBase<this['tableName'], Assume<this['selection'], ColumnsSelection>, this['selectMode'], Assume<this['nullabilityMap'], Record<string, JoinNullability>>, this['dynamic'], this['excludedMethods'], Assume<this['result'], any[]>, Assume<this['selectedFields'], ColumnsSelection>>;
}
export type CreatePgSelectFromBuilderMode<TBuilderMode extends 'db' | 'qb', TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode> = TBuilderMode extends 'db' ? PgSelectBase<TTableName, TSelection, TSelectMode> : PgSelectQueryBuilderBase<PgSelectQueryBuilderHKT, TTableName, TSelection, TSelectMode>;
export type PgSetOperatorExcludedMethods = 'leftJoin' | 'rightJoin' | 'innerJoin' | 'fullJoin' | 'where' | 'having' | 'groupBy' | 'for';
export type PgSelectWithout<T extends AnyPgSelectQueryBuilder, TDynamic extends boolean, K extends keyof T & string, TResetExcluded extends boolean = false> = TDynamic extends true ? T : Omit<PgSelectKind<T['_']['hkt'], T['_']['tableName'], T['_']['selection'], T['_']['selectMode'], T['_']['nullabilityMap'], TDynamic, TResetExcluded extends true ? K : T['_']['excludedMethods'] | K, T['_']['result'], T['_']['selectedFields']>, TResetExcluded extends true ? K : T['_']['excludedMethods'] | K>;
export type PgSelectPrepare<T extends AnyPgSelect> = PgPreparedQuery<PreparedQueryConfig & {
execute: T['_']['result'];
}>;
export type PgSelectDynamic<T extends AnyPgSelectQueryBuilder> = PgSelectKind<T['_']['hkt'], T['_']['tableName'], T['_']['selection'], T['_']['selectMode'], T['_']['nullabilityMap'], true, never, T['_']['result'], T['_']['selectedFields']>;
export type PgSelectQueryBuilder<THKT extends PgSelectHKTBase = PgSelectQueryBuilderHKT, TTableName extends string | undefined = string | undefined, TSelection extends ColumnsSelection = ColumnsSelection, TSelectMode extends SelectMode = SelectMode, TNullabilityMap extends Record<string, JoinNullability> = Record<string, JoinNullability>, TResult extends any[] = unknown[], TSelectedFields extends ColumnsSelection = ColumnsSelection> = PgSelectQueryBuilderBase<THKT, TTableName, TSelection, TSelectMode, TNullabilityMap, true, never, TResult, TSelectedFields>;
export type AnyPgSelectQueryBuilder = PgSelectQueryBuilderBase<any, any, any, any, any, any, any, any, any>;
export type AnyPgSetOperatorInterface = PgSetOperatorInterface<any, any, any, any, any, any, any, any>;
export interface PgSetOperatorInterface<TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TNullabilityMap extends Record<string, JoinNullability> = TTableName extends string ? Record<TTableName, 'not-null'> : {}, TDynamic extends boolean = false, TExcludedMethods extends string = never, TResult extends any[] = SelectResult<TSelection, TSelectMode, TNullabilityMap>[], TSelectedFields extends ColumnsSelection = BuildSubquerySelection<TSelection, TNullabilityMap>> {
_: {
readonly hkt: PgSelectHKT;
readonly tableName: TTableName;
readonly selection: TSelection;
readonly selectMode: TSelectMode;
readonly nullabilityMap: TNullabilityMap;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
readonly result: TResult;
readonly selectedFields: TSelectedFields;
};
}
export type PgSetOperatorWithResult<TResult extends any[]> = PgSetOperatorInterface<any, any, any, any, any, any, TResult, any>;
export type PgSelect<TTableName extends string | undefined = string | undefined, TSelection extends ColumnsSelection = Record<string, any>, TSelectMode extends SelectMode = SelectMode, TNullabilityMap extends Record<string, JoinNullability> = Record<string, JoinNullability>> = PgSelectBase<TTableName, TSelection, TSelectMode, TNullabilityMap, true, never>;
export type AnyPgSelect = PgSelectBase<any, any, any, any, any, any, any, any>;
export type PgSetOperator<TTableName extends string | undefined = string | undefined, TSelection extends ColumnsSelection = Record<string, any>, TSelectMode extends SelectMode = SelectMode, TNullabilityMap extends Record<string, JoinNullability> = Record<string, JoinNullability>> = PgSelectBase<TTableName, TSelection, TSelectMode, TNullabilityMap, true, PgSetOperatorExcludedMethods>;
export type SetOperatorRightSelect<TValue extends PgSetOperatorWithResult<TResult>, TResult extends any[]> = TValue extends PgSetOperatorInterface<any, any, any, any, any, any, infer TValueResult, any> ? ValidateShape<TValueResult[number], TResult[number], TypedQueryBuilder<any, TValueResult>> : TValue;
export type SetOperatorRestSelect<TValue extends readonly PgSetOperatorWithResult<TResult>[], TResult extends any[]> = TValue extends [infer First, ...infer Rest] ? First extends PgSetOperatorInterface<any, any, any, any, any, any, infer TValueResult, any> ? Rest extends AnyPgSetOperatorInterface[] ? [
ValidateShape<TValueResult[number], TResult[number], TypedQueryBuilder<any, TValueResult>>,
...SetOperatorRestSelect<Rest, TResult>
] : ValidateShape<TValueResult[number], TResult[number], TypedQueryBuilder<any, TValueResult>[]> : never : TValue;
export type PgCreateSetOperatorFn = <TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TValue extends PgSetOperatorWithResult<TResult>, TRest extends PgSetOperatorWithResult<TResult>[], TNullabilityMap extends Record<string, JoinNullability> = TTableName extends string ? Record<TTableName, 'not-null'> : {}, TDynamic extends boolean = false, TExcludedMethods extends string = never, TResult extends any[] = SelectResult<TSelection, TSelectMode, TNullabilityMap>[], TSelectedFields extends ColumnsSelection = BuildSubquerySelection<TSelection, TNullabilityMap>>(leftSelect: PgSetOperatorInterface<TTableName, TSelection, TSelectMode, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields>, rightSelect: SetOperatorRightSelect<TValue, TResult>, ...restSelects: SetOperatorRestSelect<TRest, TResult>) => PgSelectWithout<PgSelectBase<TTableName, TSelection, TSelectMode, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields>, false, PgSetOperatorExcludedMethods, true>;
export type GetPgSetOperators = {
union: PgCreateSetOperatorFn;
intersect: PgCreateSetOperatorFn;
except: PgCreateSetOperatorFn;
unionAll: PgCreateSetOperatorFn;
intersectAll: PgCreateSetOperatorFn;
exceptAll: PgCreateSetOperatorFn;
};

View File

@ -0,0 +1 @@
//# sourceMappingURL=select.types.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}

View File

@ -0,0 +1,232 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var update_exports = {};
__export(update_exports, {
PgUpdateBase: () => PgUpdateBase,
PgUpdateBuilder: () => PgUpdateBuilder
});
module.exports = __toCommonJS(update_exports);
var import_entity = require("../../entity.cjs");
var import_table = require("../table.cjs");
var import_query_promise = require("../../query-promise.cjs");
var import_selection_proxy = require("../../selection-proxy.cjs");
var import_sql = require("../../sql/sql.cjs");
var import_subquery = require("../../subquery.cjs");
var import_table2 = require("../../table.cjs");
var import_utils = require("../../utils.cjs");
var import_view_common = require("../../view-common.cjs");
class PgUpdateBuilder {
constructor(table, session, dialect, withList) {
this.table = table;
this.session = session;
this.dialect = dialect;
this.withList = withList;
}
static [import_entity.entityKind] = "PgUpdateBuilder";
authToken;
setToken(token) {
this.authToken = token;
return this;
}
set(values) {
return new PgUpdateBase(
this.table,
(0, import_utils.mapUpdateSet)(this.table, values),
this.session,
this.dialect,
this.withList
).setToken(this.authToken);
}
}
class PgUpdateBase extends import_query_promise.QueryPromise {
constructor(table, set, session, dialect, withList) {
super();
this.session = session;
this.dialect = dialect;
this.config = { set, table, withList, joins: [] };
this.tableName = (0, import_utils.getTableLikeName)(table);
this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
}
static [import_entity.entityKind] = "PgUpdate";
config;
tableName;
joinsNotNullableMap;
from(source) {
const tableName = (0, import_utils.getTableLikeName)(source);
if (typeof tableName === "string") {
this.joinsNotNullableMap[tableName] = true;
}
this.config.from = source;
return this;
}
getTableLikeFields(table) {
if ((0, import_entity.is)(table, import_table.PgTable)) {
return table[import_table2.Table.Symbol.Columns];
} else if ((0, import_entity.is)(table, import_subquery.Subquery)) {
return table._.selectedFields;
}
return table[import_view_common.ViewBaseConfig].selectedFields;
}
createJoin(joinType) {
return (table, on) => {
const tableName = (0, import_utils.getTableLikeName)(table);
if (typeof tableName === "string" && this.config.joins.some((join) => join.alias === tableName)) {
throw new Error(`Alias "${tableName}" is already used in this query`);
}
if (typeof on === "function") {
const from = this.config.from && !(0, import_entity.is)(this.config.from, import_sql.SQL) ? this.getTableLikeFields(this.config.from) : void 0;
on = on(
new Proxy(
this.config.table[import_table2.Table.Symbol.Columns],
new import_selection_proxy.SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
),
from && new Proxy(
from,
new import_selection_proxy.SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
)
);
}
this.config.joins.push({ on, table, joinType, alias: tableName });
if (typeof tableName === "string") {
switch (joinType) {
case "left": {
this.joinsNotNullableMap[tableName] = false;
break;
}
case "right": {
this.joinsNotNullableMap = Object.fromEntries(
Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
);
this.joinsNotNullableMap[tableName] = true;
break;
}
case "inner": {
this.joinsNotNullableMap[tableName] = true;
break;
}
case "full": {
this.joinsNotNullableMap = Object.fromEntries(
Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
);
this.joinsNotNullableMap[tableName] = false;
break;
}
}
}
return this;
};
}
leftJoin = this.createJoin("left");
rightJoin = this.createJoin("right");
innerJoin = this.createJoin("inner");
fullJoin = this.createJoin("full");
/**
* Adds a 'where' clause to the query.
*
* Calling this method will update only those rows that fulfill a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/update}
*
* @param where the 'where' clause.
*
* @example
* You can use conditional operators and `sql function` to filter the rows to be updated.
*
* ```ts
* // Update all cars with green color
* await db.update(cars).set({ color: 'red' })
* .where(eq(cars.color, 'green'));
* // or
* await db.update(cars).set({ color: 'red' })
* .where(sql`${cars.color} = 'green'`)
* ```
*
* You can logically combine conditional operators with `and()` and `or()` operators:
*
* ```ts
* // Update all BMW cars with a green color
* await db.update(cars).set({ color: 'red' })
* .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
*
* // Update all cars with the green or blue color
* await db.update(cars).set({ color: 'red' })
* .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where) {
this.config.where = where;
return this;
}
returning(fields) {
if (!fields) {
fields = Object.assign({}, this.config.table[import_table2.Table.Symbol.Columns]);
if (this.config.from) {
const tableName = (0, import_utils.getTableLikeName)(this.config.from);
if (typeof tableName === "string" && this.config.from && !(0, import_entity.is)(this.config.from, import_sql.SQL)) {
const fromFields = this.getTableLikeFields(this.config.from);
fields[tableName] = fromFields;
}
for (const join of this.config.joins) {
const tableName2 = (0, import_utils.getTableLikeName)(join.table);
if (typeof tableName2 === "string" && !(0, import_entity.is)(join.table, import_sql.SQL)) {
const fromFields = this.getTableLikeFields(join.table);
fields[tableName2] = fromFields;
}
}
}
}
this.config.returning = (0, import_utils.orderSelectedFields)(fields);
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildUpdateQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
/** @internal */
_prepare(name) {
const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true);
query.joinsNotNullableMap = this.joinsNotNullableMap;
return query;
}
prepare(name) {
return this._prepare(name);
}
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
execute = (placeholderValues) => {
return this._prepare().execute(placeholderValues, this.authToken);
};
$dynamic() {
return this;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
PgUpdateBase,
PgUpdateBuilder
});
//# sourceMappingURL=update.cjs.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,167 @@
import type { GetColumnData } from "../../column.cjs";
import { entityKind } from "../../entity.cjs";
import type { PgDialect } from "../dialect.cjs";
import type { PgPreparedQuery, PgQueryResultHKT, PgQueryResultKind, PgSession, PreparedQueryConfig } from "../session.cjs";
import { PgTable } from "../table.cjs";
import type { AppendToNullabilityMap, AppendToResult, GetSelectTableName, GetSelectTableSelection, JoinNullability, JoinType, SelectMode, SelectResult } from "../../query-builders/select.types.cjs";
import { QueryPromise } from "../../query-promise.cjs";
import type { RunnableQuery } from "../../runnable-query.cjs";
import { type ColumnsSelection, type Query, SQL, type SQLWrapper } from "../../sql/sql.cjs";
import { Subquery } from "../../subquery.cjs";
import { Table } from "../../table.cjs";
import { type Assume, type NeonAuthToken, type UpdateSet } from "../../utils.cjs";
import type { PgColumn } from "../columns/common.cjs";
import type { PgViewBase } from "../view-base.cjs";
import type { PgSelectJoinConfig, SelectedFields, SelectedFieldsOrdered } from "./select.types.cjs";
export interface PgUpdateConfig {
where?: SQL | undefined;
set: UpdateSet;
table: PgTable;
from?: PgTable | Subquery | PgViewBase | SQL;
joins: PgSelectJoinConfig[];
returning?: SelectedFieldsOrdered;
withList?: Subquery[];
}
export type PgUpdateSetSource<TTable extends PgTable> = {
[Key in keyof TTable['$inferInsert']]?: GetColumnData<TTable['_']['columns'][Key]> | SQL | PgColumn | undefined;
} & {};
export declare class PgUpdateBuilder<TTable extends PgTable, TQueryResult extends PgQueryResultHKT> {
private table;
private session;
private dialect;
private withList?;
static readonly [entityKind]: string;
readonly _: {
readonly table: TTable;
};
constructor(table: TTable, session: PgSession, dialect: PgDialect, withList?: Subquery[] | undefined);
private authToken?;
setToken(token: NeonAuthToken): this;
set(values: PgUpdateSetSource<TTable>): PgUpdateWithout<PgUpdateBase<TTable, TQueryResult>, false, 'leftJoin' | 'rightJoin' | 'innerJoin' | 'fullJoin'>;
}
export type PgUpdateWithout<T extends AnyPgUpdate, TDynamic extends boolean, K extends keyof T & string> = TDynamic extends true ? T : Omit<PgUpdateBase<T['_']['table'], T['_']['queryResult'], T['_']['from'], T['_']['returning'], T['_']['nullabilityMap'], T['_']['joins'], TDynamic, T['_']['excludedMethods'] | K>, T['_']['excludedMethods'] | K>;
export type PgUpdateWithJoins<T extends AnyPgUpdate, TDynamic extends boolean, TFrom extends PgTable | Subquery | PgViewBase | SQL> = TDynamic extends true ? T : Omit<PgUpdateBase<T['_']['table'], T['_']['queryResult'], TFrom, T['_']['returning'], AppendToNullabilityMap<T['_']['nullabilityMap'], GetSelectTableName<TFrom>, 'inner'>, [
...T['_']['joins'],
{
name: GetSelectTableName<TFrom>;
joinType: 'inner';
table: TFrom;
}
], TDynamic, Exclude<T['_']['excludedMethods'] | 'from', 'leftJoin' | 'rightJoin' | 'innerJoin' | 'fullJoin'>>, Exclude<T['_']['excludedMethods'] | 'from', 'leftJoin' | 'rightJoin' | 'innerJoin' | 'fullJoin'>>;
export type PgUpdateJoinFn<T extends AnyPgUpdate, TDynamic extends boolean, TJoinType extends JoinType> = <TJoinedTable extends PgTable | Subquery | PgViewBase | SQL>(table: TJoinedTable, on: ((updateTable: T['_']['table']['_']['columns'], from: T['_']['from'] extends PgTable ? T['_']['from']['_']['columns'] : T['_']['from'] extends Subquery | PgViewBase ? T['_']['from']['_']['selectedFields'] : never) => SQL | undefined) | SQL | undefined) => PgUpdateJoin<T, TDynamic, TJoinType, TJoinedTable>;
export type PgUpdateJoin<T extends AnyPgUpdate, TDynamic extends boolean, TJoinType extends JoinType, TJoinedTable extends PgTable | Subquery | PgViewBase | SQL> = TDynamic extends true ? T : PgUpdateBase<T['_']['table'], T['_']['queryResult'], T['_']['from'], T['_']['returning'], AppendToNullabilityMap<T['_']['nullabilityMap'], GetSelectTableName<TJoinedTable>, TJoinType>, [
...T['_']['joins'],
{
name: GetSelectTableName<TJoinedTable>;
joinType: TJoinType;
table: TJoinedTable;
}
], TDynamic, T['_']['excludedMethods']>;
type Join = {
name: string | undefined;
joinType: JoinType;
table: PgTable | Subquery | PgViewBase | SQL;
};
type AccumulateToResult<T extends AnyPgUpdate, TSelectMode extends SelectMode, TJoins extends Join[], TSelectedFields extends ColumnsSelection> = TJoins extends [infer TJoin extends Join, ...infer TRest extends Join[]] ? AccumulateToResult<T, TSelectMode extends 'partial' ? TSelectMode : 'multiple', TRest, AppendToResult<T['_']['table']['_']['name'], TSelectedFields, TJoin['name'], TJoin['table'] extends Table ? TJoin['table']['_']['columns'] : TJoin['table'] extends Subquery ? Assume<TJoin['table']['_']['selectedFields'], SelectedFields> : never, TSelectMode extends 'partial' ? TSelectMode : 'multiple'>> : TSelectedFields;
export type PgUpdateReturningAll<T extends AnyPgUpdate, TDynamic extends boolean> = PgUpdateWithout<PgUpdateBase<T['_']['table'], T['_']['queryResult'], T['_']['from'], SelectResult<AccumulateToResult<T, 'single', T['_']['joins'], GetSelectTableSelection<T['_']['table']>>, 'partial', T['_']['nullabilityMap']>, T['_']['nullabilityMap'], T['_']['joins'], TDynamic, T['_']['excludedMethods']>, TDynamic, 'returning'>;
export type PgUpdateReturning<T extends AnyPgUpdate, TDynamic extends boolean, TSelectedFields extends SelectedFields> = PgUpdateWithout<PgUpdateBase<T['_']['table'], T['_']['queryResult'], T['_']['from'], SelectResult<AccumulateToResult<T, 'partial', T['_']['joins'], TSelectedFields>, 'partial', T['_']['nullabilityMap']>, T['_']['nullabilityMap'], T['_']['joins'], TDynamic, T['_']['excludedMethods']>, TDynamic, 'returning'>;
export type PgUpdatePrepare<T extends AnyPgUpdate> = PgPreparedQuery<PreparedQueryConfig & {
execute: T['_']['returning'] extends undefined ? PgQueryResultKind<T['_']['queryResult'], never> : T['_']['returning'][];
}>;
export type PgUpdateDynamic<T extends AnyPgUpdate> = PgUpdate<T['_']['table'], T['_']['queryResult'], T['_']['from'], T['_']['returning'], T['_']['nullabilityMap']>;
export type PgUpdate<TTable extends PgTable = PgTable, TQueryResult extends PgQueryResultHKT = PgQueryResultHKT, TFrom extends PgTable | Subquery | PgViewBase | SQL | undefined = undefined, TReturning extends Record<string, unknown> | undefined = Record<string, unknown> | undefined, TNullabilityMap extends Record<string, JoinNullability> = Record<TTable['_']['name'], 'not-null'>, TJoins extends Join[] = []> = PgUpdateBase<TTable, TQueryResult, TFrom, TReturning, TNullabilityMap, TJoins, true, never>;
export type AnyPgUpdate = PgUpdateBase<any, any, any, any, any, any, any, any>;
export interface PgUpdateBase<TTable extends PgTable, TQueryResult extends PgQueryResultHKT, TFrom extends PgTable | Subquery | PgViewBase | SQL | undefined = undefined, TReturning extends Record<string, unknown> | undefined = undefined, TNullabilityMap extends Record<string, JoinNullability> = Record<TTable['_']['name'], 'not-null'>, TJoins extends Join[] = [], TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[]>, RunnableQuery<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[], 'pg'>, SQLWrapper {
readonly _: {
readonly dialect: 'pg';
readonly table: TTable;
readonly joins: TJoins;
readonly nullabilityMap: TNullabilityMap;
readonly queryResult: TQueryResult;
readonly from: TFrom;
readonly returning: TReturning;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
readonly result: TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[];
};
}
export declare class PgUpdateBase<TTable extends PgTable, TQueryResult extends PgQueryResultHKT, TFrom extends PgTable | Subquery | PgViewBase | SQL | undefined = undefined, TReturning extends Record<string, unknown> | undefined = undefined, TNullabilityMap extends Record<string, JoinNullability> = Record<TTable['_']['name'], 'not-null'>, TJoins extends Join[] = [], TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[]> implements RunnableQuery<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[], 'pg'>, SQLWrapper {
private session;
private dialect;
static readonly [entityKind]: string;
private config;
private tableName;
private joinsNotNullableMap;
constructor(table: TTable, set: UpdateSet, session: PgSession, dialect: PgDialect, withList?: Subquery[]);
from<TFrom extends PgTable | Subquery | PgViewBase | SQL>(source: TFrom): PgUpdateWithJoins<this, TDynamic, TFrom>;
private getTableLikeFields;
private createJoin;
leftJoin: PgUpdateJoinFn<this, TDynamic, "left">;
rightJoin: PgUpdateJoinFn<this, TDynamic, "right">;
innerJoin: PgUpdateJoinFn<this, TDynamic, "inner">;
fullJoin: PgUpdateJoinFn<this, TDynamic, "full">;
/**
* Adds a 'where' clause to the query.
*
* Calling this method will update only those rows that fulfill a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/update}
*
* @param where the 'where' clause.
*
* @example
* You can use conditional operators and `sql function` to filter the rows to be updated.
*
* ```ts
* // Update all cars with green color
* await db.update(cars).set({ color: 'red' })
* .where(eq(cars.color, 'green'));
* // or
* await db.update(cars).set({ color: 'red' })
* .where(sql`${cars.color} = 'green'`)
* ```
*
* You can logically combine conditional operators with `and()` and `or()` operators:
*
* ```ts
* // Update all BMW cars with a green color
* await db.update(cars).set({ color: 'red' })
* .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
*
* // Update all cars with the green or blue color
* await db.update(cars).set({ color: 'red' })
* .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where: SQL | undefined): PgUpdateWithout<this, TDynamic, 'where'>;
/**
* Adds a `returning` clause to the query.
*
* Calling this method will return the specified fields of the updated rows. If no fields are specified, all fields will be returned.
*
* See docs: {@link https://orm.drizzle.team/docs/update#update-with-returning}
*
* @example
* ```ts
* // Update all cars with the green color and return all fields
* const updatedCars: Car[] = await db.update(cars)
* .set({ color: 'red' })
* .where(eq(cars.color, 'green'))
* .returning();
*
* // Update all cars with the green color and return only their id and brand fields
* const updatedCarsIdsAndBrands: { id: number, brand: string }[] = await db.update(cars)
* .set({ color: 'red' })
* .where(eq(cars.color, 'green'))
* .returning({ id: cars.id, brand: cars.brand });
* ```
*/
returning(): PgUpdateReturningAll<this, TDynamic>;
returning<TSelectedFields extends SelectedFields>(fields: TSelectedFields): PgUpdateReturning<this, TDynamic, TSelectedFields>;
toSQL(): Query;
prepare(name: string): PgUpdatePrepare<this>;
private authToken?;
execute: ReturnType<this['prepare']>['execute'];
$dynamic(): PgUpdateDynamic<this>;
}
export {};

View File

@ -0,0 +1,167 @@
import type { GetColumnData } from "../../column.js";
import { entityKind } from "../../entity.js";
import type { PgDialect } from "../dialect.js";
import type { PgPreparedQuery, PgQueryResultHKT, PgQueryResultKind, PgSession, PreparedQueryConfig } from "../session.js";
import { PgTable } from "../table.js";
import type { AppendToNullabilityMap, AppendToResult, GetSelectTableName, GetSelectTableSelection, JoinNullability, JoinType, SelectMode, SelectResult } from "../../query-builders/select.types.js";
import { QueryPromise } from "../../query-promise.js";
import type { RunnableQuery } from "../../runnable-query.js";
import { type ColumnsSelection, type Query, SQL, type SQLWrapper } from "../../sql/sql.js";
import { Subquery } from "../../subquery.js";
import { Table } from "../../table.js";
import { type Assume, type NeonAuthToken, type UpdateSet } from "../../utils.js";
import type { PgColumn } from "../columns/common.js";
import type { PgViewBase } from "../view-base.js";
import type { PgSelectJoinConfig, SelectedFields, SelectedFieldsOrdered } from "./select.types.js";
export interface PgUpdateConfig {
where?: SQL | undefined;
set: UpdateSet;
table: PgTable;
from?: PgTable | Subquery | PgViewBase | SQL;
joins: PgSelectJoinConfig[];
returning?: SelectedFieldsOrdered;
withList?: Subquery[];
}
export type PgUpdateSetSource<TTable extends PgTable> = {
[Key in keyof TTable['$inferInsert']]?: GetColumnData<TTable['_']['columns'][Key]> | SQL | PgColumn | undefined;
} & {};
export declare class PgUpdateBuilder<TTable extends PgTable, TQueryResult extends PgQueryResultHKT> {
private table;
private session;
private dialect;
private withList?;
static readonly [entityKind]: string;
readonly _: {
readonly table: TTable;
};
constructor(table: TTable, session: PgSession, dialect: PgDialect, withList?: Subquery[] | undefined);
private authToken?;
setToken(token: NeonAuthToken): this;
set(values: PgUpdateSetSource<TTable>): PgUpdateWithout<PgUpdateBase<TTable, TQueryResult>, false, 'leftJoin' | 'rightJoin' | 'innerJoin' | 'fullJoin'>;
}
export type PgUpdateWithout<T extends AnyPgUpdate, TDynamic extends boolean, K extends keyof T & string> = TDynamic extends true ? T : Omit<PgUpdateBase<T['_']['table'], T['_']['queryResult'], T['_']['from'], T['_']['returning'], T['_']['nullabilityMap'], T['_']['joins'], TDynamic, T['_']['excludedMethods'] | K>, T['_']['excludedMethods'] | K>;
export type PgUpdateWithJoins<T extends AnyPgUpdate, TDynamic extends boolean, TFrom extends PgTable | Subquery | PgViewBase | SQL> = TDynamic extends true ? T : Omit<PgUpdateBase<T['_']['table'], T['_']['queryResult'], TFrom, T['_']['returning'], AppendToNullabilityMap<T['_']['nullabilityMap'], GetSelectTableName<TFrom>, 'inner'>, [
...T['_']['joins'],
{
name: GetSelectTableName<TFrom>;
joinType: 'inner';
table: TFrom;
}
], TDynamic, Exclude<T['_']['excludedMethods'] | 'from', 'leftJoin' | 'rightJoin' | 'innerJoin' | 'fullJoin'>>, Exclude<T['_']['excludedMethods'] | 'from', 'leftJoin' | 'rightJoin' | 'innerJoin' | 'fullJoin'>>;
export type PgUpdateJoinFn<T extends AnyPgUpdate, TDynamic extends boolean, TJoinType extends JoinType> = <TJoinedTable extends PgTable | Subquery | PgViewBase | SQL>(table: TJoinedTable, on: ((updateTable: T['_']['table']['_']['columns'], from: T['_']['from'] extends PgTable ? T['_']['from']['_']['columns'] : T['_']['from'] extends Subquery | PgViewBase ? T['_']['from']['_']['selectedFields'] : never) => SQL | undefined) | SQL | undefined) => PgUpdateJoin<T, TDynamic, TJoinType, TJoinedTable>;
export type PgUpdateJoin<T extends AnyPgUpdate, TDynamic extends boolean, TJoinType extends JoinType, TJoinedTable extends PgTable | Subquery | PgViewBase | SQL> = TDynamic extends true ? T : PgUpdateBase<T['_']['table'], T['_']['queryResult'], T['_']['from'], T['_']['returning'], AppendToNullabilityMap<T['_']['nullabilityMap'], GetSelectTableName<TJoinedTable>, TJoinType>, [
...T['_']['joins'],
{
name: GetSelectTableName<TJoinedTable>;
joinType: TJoinType;
table: TJoinedTable;
}
], TDynamic, T['_']['excludedMethods']>;
type Join = {
name: string | undefined;
joinType: JoinType;
table: PgTable | Subquery | PgViewBase | SQL;
};
type AccumulateToResult<T extends AnyPgUpdate, TSelectMode extends SelectMode, TJoins extends Join[], TSelectedFields extends ColumnsSelection> = TJoins extends [infer TJoin extends Join, ...infer TRest extends Join[]] ? AccumulateToResult<T, TSelectMode extends 'partial' ? TSelectMode : 'multiple', TRest, AppendToResult<T['_']['table']['_']['name'], TSelectedFields, TJoin['name'], TJoin['table'] extends Table ? TJoin['table']['_']['columns'] : TJoin['table'] extends Subquery ? Assume<TJoin['table']['_']['selectedFields'], SelectedFields> : never, TSelectMode extends 'partial' ? TSelectMode : 'multiple'>> : TSelectedFields;
export type PgUpdateReturningAll<T extends AnyPgUpdate, TDynamic extends boolean> = PgUpdateWithout<PgUpdateBase<T['_']['table'], T['_']['queryResult'], T['_']['from'], SelectResult<AccumulateToResult<T, 'single', T['_']['joins'], GetSelectTableSelection<T['_']['table']>>, 'partial', T['_']['nullabilityMap']>, T['_']['nullabilityMap'], T['_']['joins'], TDynamic, T['_']['excludedMethods']>, TDynamic, 'returning'>;
export type PgUpdateReturning<T extends AnyPgUpdate, TDynamic extends boolean, TSelectedFields extends SelectedFields> = PgUpdateWithout<PgUpdateBase<T['_']['table'], T['_']['queryResult'], T['_']['from'], SelectResult<AccumulateToResult<T, 'partial', T['_']['joins'], TSelectedFields>, 'partial', T['_']['nullabilityMap']>, T['_']['nullabilityMap'], T['_']['joins'], TDynamic, T['_']['excludedMethods']>, TDynamic, 'returning'>;
export type PgUpdatePrepare<T extends AnyPgUpdate> = PgPreparedQuery<PreparedQueryConfig & {
execute: T['_']['returning'] extends undefined ? PgQueryResultKind<T['_']['queryResult'], never> : T['_']['returning'][];
}>;
export type PgUpdateDynamic<T extends AnyPgUpdate> = PgUpdate<T['_']['table'], T['_']['queryResult'], T['_']['from'], T['_']['returning'], T['_']['nullabilityMap']>;
export type PgUpdate<TTable extends PgTable = PgTable, TQueryResult extends PgQueryResultHKT = PgQueryResultHKT, TFrom extends PgTable | Subquery | PgViewBase | SQL | undefined = undefined, TReturning extends Record<string, unknown> | undefined = Record<string, unknown> | undefined, TNullabilityMap extends Record<string, JoinNullability> = Record<TTable['_']['name'], 'not-null'>, TJoins extends Join[] = []> = PgUpdateBase<TTable, TQueryResult, TFrom, TReturning, TNullabilityMap, TJoins, true, never>;
export type AnyPgUpdate = PgUpdateBase<any, any, any, any, any, any, any, any>;
export interface PgUpdateBase<TTable extends PgTable, TQueryResult extends PgQueryResultHKT, TFrom extends PgTable | Subquery | PgViewBase | SQL | undefined = undefined, TReturning extends Record<string, unknown> | undefined = undefined, TNullabilityMap extends Record<string, JoinNullability> = Record<TTable['_']['name'], 'not-null'>, TJoins extends Join[] = [], TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[]>, RunnableQuery<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[], 'pg'>, SQLWrapper {
readonly _: {
readonly dialect: 'pg';
readonly table: TTable;
readonly joins: TJoins;
readonly nullabilityMap: TNullabilityMap;
readonly queryResult: TQueryResult;
readonly from: TFrom;
readonly returning: TReturning;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
readonly result: TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[];
};
}
export declare class PgUpdateBase<TTable extends PgTable, TQueryResult extends PgQueryResultHKT, TFrom extends PgTable | Subquery | PgViewBase | SQL | undefined = undefined, TReturning extends Record<string, unknown> | undefined = undefined, TNullabilityMap extends Record<string, JoinNullability> = Record<TTable['_']['name'], 'not-null'>, TJoins extends Join[] = [], TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[]> implements RunnableQuery<TReturning extends undefined ? PgQueryResultKind<TQueryResult, never> : TReturning[], 'pg'>, SQLWrapper {
private session;
private dialect;
static readonly [entityKind]: string;
private config;
private tableName;
private joinsNotNullableMap;
constructor(table: TTable, set: UpdateSet, session: PgSession, dialect: PgDialect, withList?: Subquery[]);
from<TFrom extends PgTable | Subquery | PgViewBase | SQL>(source: TFrom): PgUpdateWithJoins<this, TDynamic, TFrom>;
private getTableLikeFields;
private createJoin;
leftJoin: PgUpdateJoinFn<this, TDynamic, "left">;
rightJoin: PgUpdateJoinFn<this, TDynamic, "right">;
innerJoin: PgUpdateJoinFn<this, TDynamic, "inner">;
fullJoin: PgUpdateJoinFn<this, TDynamic, "full">;
/**
* Adds a 'where' clause to the query.
*
* Calling this method will update only those rows that fulfill a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/update}
*
* @param where the 'where' clause.
*
* @example
* You can use conditional operators and `sql function` to filter the rows to be updated.
*
* ```ts
* // Update all cars with green color
* await db.update(cars).set({ color: 'red' })
* .where(eq(cars.color, 'green'));
* // or
* await db.update(cars).set({ color: 'red' })
* .where(sql`${cars.color} = 'green'`)
* ```
*
* You can logically combine conditional operators with `and()` and `or()` operators:
*
* ```ts
* // Update all BMW cars with a green color
* await db.update(cars).set({ color: 'red' })
* .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
*
* // Update all cars with the green or blue color
* await db.update(cars).set({ color: 'red' })
* .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where: SQL | undefined): PgUpdateWithout<this, TDynamic, 'where'>;
/**
* Adds a `returning` clause to the query.
*
* Calling this method will return the specified fields of the updated rows. If no fields are specified, all fields will be returned.
*
* See docs: {@link https://orm.drizzle.team/docs/update#update-with-returning}
*
* @example
* ```ts
* // Update all cars with the green color and return all fields
* const updatedCars: Car[] = await db.update(cars)
* .set({ color: 'red' })
* .where(eq(cars.color, 'green'))
* .returning();
*
* // Update all cars with the green color and return only their id and brand fields
* const updatedCarsIdsAndBrands: { id: number, brand: string }[] = await db.update(cars)
* .set({ color: 'red' })
* .where(eq(cars.color, 'green'))
* .returning({ id: cars.id, brand: cars.brand });
* ```
*/
returning(): PgUpdateReturningAll<this, TDynamic>;
returning<TSelectedFields extends SelectedFields>(fields: TSelectedFields): PgUpdateReturning<this, TDynamic, TSelectedFields>;
toSQL(): Query;
prepare(name: string): PgUpdatePrepare<this>;
private authToken?;
execute: ReturnType<this['prepare']>['execute'];
$dynamic(): PgUpdateDynamic<this>;
}
export {};

View File

@ -0,0 +1,211 @@
import { entityKind, is } from "../../entity.js";
import { PgTable } from "../table.js";
import { QueryPromise } from "../../query-promise.js";
import { SelectionProxyHandler } from "../../selection-proxy.js";
import { SQL } from "../../sql/sql.js";
import { Subquery } from "../../subquery.js";
import { Table } from "../../table.js";
import {
getTableLikeName,
mapUpdateSet,
orderSelectedFields
} from "../../utils.js";
import { ViewBaseConfig } from "../../view-common.js";
class PgUpdateBuilder {
constructor(table, session, dialect, withList) {
this.table = table;
this.session = session;
this.dialect = dialect;
this.withList = withList;
}
static [entityKind] = "PgUpdateBuilder";
authToken;
setToken(token) {
this.authToken = token;
return this;
}
set(values) {
return new PgUpdateBase(
this.table,
mapUpdateSet(this.table, values),
this.session,
this.dialect,
this.withList
).setToken(this.authToken);
}
}
class PgUpdateBase extends QueryPromise {
constructor(table, set, session, dialect, withList) {
super();
this.session = session;
this.dialect = dialect;
this.config = { set, table, withList, joins: [] };
this.tableName = getTableLikeName(table);
this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
}
static [entityKind] = "PgUpdate";
config;
tableName;
joinsNotNullableMap;
from(source) {
const tableName = getTableLikeName(source);
if (typeof tableName === "string") {
this.joinsNotNullableMap[tableName] = true;
}
this.config.from = source;
return this;
}
getTableLikeFields(table) {
if (is(table, PgTable)) {
return table[Table.Symbol.Columns];
} else if (is(table, Subquery)) {
return table._.selectedFields;
}
return table[ViewBaseConfig].selectedFields;
}
createJoin(joinType) {
return (table, on) => {
const tableName = getTableLikeName(table);
if (typeof tableName === "string" && this.config.joins.some((join) => join.alias === tableName)) {
throw new Error(`Alias "${tableName}" is already used in this query`);
}
if (typeof on === "function") {
const from = this.config.from && !is(this.config.from, SQL) ? this.getTableLikeFields(this.config.from) : void 0;
on = on(
new Proxy(
this.config.table[Table.Symbol.Columns],
new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
),
from && new Proxy(
from,
new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
)
);
}
this.config.joins.push({ on, table, joinType, alias: tableName });
if (typeof tableName === "string") {
switch (joinType) {
case "left": {
this.joinsNotNullableMap[tableName] = false;
break;
}
case "right": {
this.joinsNotNullableMap = Object.fromEntries(
Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
);
this.joinsNotNullableMap[tableName] = true;
break;
}
case "inner": {
this.joinsNotNullableMap[tableName] = true;
break;
}
case "full": {
this.joinsNotNullableMap = Object.fromEntries(
Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
);
this.joinsNotNullableMap[tableName] = false;
break;
}
}
}
return this;
};
}
leftJoin = this.createJoin("left");
rightJoin = this.createJoin("right");
innerJoin = this.createJoin("inner");
fullJoin = this.createJoin("full");
/**
* Adds a 'where' clause to the query.
*
* Calling this method will update only those rows that fulfill a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/update}
*
* @param where the 'where' clause.
*
* @example
* You can use conditional operators and `sql function` to filter the rows to be updated.
*
* ```ts
* // Update all cars with green color
* await db.update(cars).set({ color: 'red' })
* .where(eq(cars.color, 'green'));
* // or
* await db.update(cars).set({ color: 'red' })
* .where(sql`${cars.color} = 'green'`)
* ```
*
* You can logically combine conditional operators with `and()` and `or()` operators:
*
* ```ts
* // Update all BMW cars with a green color
* await db.update(cars).set({ color: 'red' })
* .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
*
* // Update all cars with the green or blue color
* await db.update(cars).set({ color: 'red' })
* .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where) {
this.config.where = where;
return this;
}
returning(fields) {
if (!fields) {
fields = Object.assign({}, this.config.table[Table.Symbol.Columns]);
if (this.config.from) {
const tableName = getTableLikeName(this.config.from);
if (typeof tableName === "string" && this.config.from && !is(this.config.from, SQL)) {
const fromFields = this.getTableLikeFields(this.config.from);
fields[tableName] = fromFields;
}
for (const join of this.config.joins) {
const tableName2 = getTableLikeName(join.table);
if (typeof tableName2 === "string" && !is(join.table, SQL)) {
const fromFields = this.getTableLikeFields(join.table);
fields[tableName2] = fromFields;
}
}
}
}
this.config.returning = orderSelectedFields(fields);
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildUpdateQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
/** @internal */
_prepare(name) {
const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true);
query.joinsNotNullableMap = this.joinsNotNullableMap;
return query;
}
prepare(name) {
return this._prepare(name);
}
authToken;
/** @internal */
setToken(token) {
this.authToken = token;
return this;
}
execute = (placeholderValues) => {
return this._prepare().execute(placeholderValues, this.authToken);
};
$dynamic() {
return this;
}
}
export {
PgUpdateBase,
PgUpdateBuilder
};
//# sourceMappingURL=update.js.map

File diff suppressed because one or more lines are too long