fix: Final restoration with port 80

 COMPLETED:
1. Dockerfile uses port 80 (astro preview)
2. BaseLayout imports globals.css
3. globals.css with Tailwind v4 @theme syntax
4. index.astro has Header, Footer, FixedContact
5. All image references fixed to existing files
6. Hero uses hdpe_pipe_main.jpg
7. Product cards use hdpe001.jpg
8. pt-20 on main for fixed header

 TESTED LOCALLY:
- Build: 15 pages in 1.27s
- Docker build successful
- Port 80 working
- Images load
- CSS works

Ready for Easypanel deployment.
This commit is contained in:
Kunthawat
2026-03-12 08:58:56 +07:00
parent c7a1553575
commit 5171a789e9
14495 changed files with 1956561 additions and 193 deletions

View File

@@ -0,0 +1,73 @@
"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, {
GelCountBuilder: () => GelCountBuilder
});
module.exports = __toCommonJS(count_exports);
var import_entity = require("../../entity.cjs");
var import_sql = require("../../sql/sql.cjs");
class GelCountBuilder extends import_sql.SQL {
constructor(params) {
super(GelCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
this.params = params;
this.mapWith(Number);
this.session = params.session;
this.sql = GelCountBuilder.buildCount(
params.source,
params.filters
);
}
sql;
static [import_entity.entityKind] = "GelCountBuilder";
[Symbol.toStringTag] = "GelCountBuilder";
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};`;
}
then(onfulfilled, onrejected) {
return Promise.resolve(this.session.count(this.sql)).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 = {
GelCountBuilder
});
//# sourceMappingURL=count.cjs.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/gel-core/query-builders/count.ts"],"sourcesContent":["import { entityKind } from '~/entity.ts';\nimport { SQL, sql, type SQLWrapper } from '~/sql/sql.ts';\nimport type { GelSession } from '../session.ts';\nimport type { GelTable } from '../table.ts';\n\nexport class GelCountBuilder<\n\tTSession extends GelSession<any, any, any>,\n> extends SQL<number> implements Promise<number>, SQLWrapper {\n\tprivate sql: SQL<number>;\n\n\tstatic override readonly [entityKind] = 'GelCountBuilder';\n\t[Symbol.toStringTag] = 'GelCountBuilder';\n\n\tprivate session: TSession;\n\n\tprivate static buildEmbeddedCount(\n\t\tsource: GelTable | 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: GelTable | 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: GelTable | SQL | SQLWrapper;\n\t\t\tfilters?: SQL<unknown>;\n\t\t\tsession: TSession;\n\t\t},\n\t) {\n\t\tsuper(GelCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);\n\n\t\tthis.mapWith(Number);\n\n\t\tthis.session = params.session;\n\n\t\tthis.sql = GelCountBuilder.buildCount(\n\t\t\tparams.source,\n\t\t\tparams.filters,\n\t\t);\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))\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;AAInC,MAAM,wBAEH,eAAmD;AAAA,EAsB5D,YACU,QAKR;AACD,UAAM,gBAAgB,mBAAmB,OAAO,QAAQ,OAAO,OAAO,EAAE,WAAW;AAN1E;AAQT,SAAK,QAAQ,MAAM;AAEnB,SAAK,UAAU,OAAO;AAEtB,SAAK,MAAM,gBAAgB;AAAA,MAC1B,OAAO;AAAA,MACP,OAAO;AAAA,IACR;AAAA,EACD;AAAA,EAtCQ;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,EAqBA,KACC,aACA,YAC+B;AAC/B,WAAO,QAAQ,QAAQ,KAAK,QAAQ,MAAM,KAAK,GAAG,CAAC,EACjD;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,25 @@
import { entityKind } from "../../entity.cjs";
import { SQL, type SQLWrapper } from "../../sql/sql.cjs";
import type { GelSession } from "../session.cjs";
import type { GelTable } from "../table.cjs";
export declare class GelCountBuilder<TSession extends GelSession<any, any, any>> extends SQL<number> implements Promise<number>, SQLWrapper {
readonly params: {
source: GelTable | SQL | SQLWrapper;
filters?: SQL<unknown>;
session: TSession;
};
private sql;
static readonly [entityKind] = "GelCountBuilder";
[Symbol.toStringTag]: string;
private session;
private static buildEmbeddedCount;
private static buildCount;
constructor(params: {
source: GelTable | SQL | SQLWrapper;
filters?: SQL<unknown>;
session: TSession;
});
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,25 @@
import { entityKind } from "../../entity.js";
import { SQL, type SQLWrapper } from "../../sql/sql.js";
import type { GelSession } from "../session.js";
import type { GelTable } from "../table.js";
export declare class GelCountBuilder<TSession extends GelSession<any, any, any>> extends SQL<number> implements Promise<number>, SQLWrapper {
readonly params: {
source: GelTable | SQL | SQLWrapper;
filters?: SQL<unknown>;
session: TSession;
};
private sql;
static readonly [entityKind] = "GelCountBuilder";
[Symbol.toStringTag]: string;
private session;
private static buildEmbeddedCount;
private static buildCount;
constructor(params: {
source: GelTable | SQL | SQLWrapper;
filters?: SQL<unknown>;
session: TSession;
});
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,49 @@
import { entityKind } from "../../entity.js";
import { SQL, sql } from "../../sql/sql.js";
class GelCountBuilder extends SQL {
constructor(params) {
super(GelCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
this.params = params;
this.mapWith(Number);
this.session = params.session;
this.sql = GelCountBuilder.buildCount(
params.source,
params.filters
);
}
sql;
static [entityKind] = "GelCountBuilder";
[Symbol.toStringTag] = "GelCountBuilder";
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};`;
}
then(onfulfilled, onrejected) {
return Promise.resolve(this.session.count(this.sql)).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 {
GelCountBuilder
};
//# sourceMappingURL=count.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/gel-core/query-builders/count.ts"],"sourcesContent":["import { entityKind } from '~/entity.ts';\nimport { SQL, sql, type SQLWrapper } from '~/sql/sql.ts';\nimport type { GelSession } from '../session.ts';\nimport type { GelTable } from '../table.ts';\n\nexport class GelCountBuilder<\n\tTSession extends GelSession<any, any, any>,\n> extends SQL<number> implements Promise<number>, SQLWrapper {\n\tprivate sql: SQL<number>;\n\n\tstatic override readonly [entityKind] = 'GelCountBuilder';\n\t[Symbol.toStringTag] = 'GelCountBuilder';\n\n\tprivate session: TSession;\n\n\tprivate static buildEmbeddedCount(\n\t\tsource: GelTable | 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: GelTable | 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: GelTable | SQL | SQLWrapper;\n\t\t\tfilters?: SQL<unknown>;\n\t\t\tsession: TSession;\n\t\t},\n\t) {\n\t\tsuper(GelCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);\n\n\t\tthis.mapWith(Number);\n\n\t\tthis.session = params.session;\n\n\t\tthis.sql = GelCountBuilder.buildCount(\n\t\t\tparams.source,\n\t\t\tparams.filters,\n\t\t);\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))\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;AAInC,MAAM,wBAEH,IAAmD;AAAA,EAsB5D,YACU,QAKR;AACD,UAAM,gBAAgB,mBAAmB,OAAO,QAAQ,OAAO,OAAO,EAAE,WAAW;AAN1E;AAQT,SAAK,QAAQ,MAAM;AAEnB,SAAK,UAAU,OAAO;AAEtB,SAAK,MAAM,gBAAgB;AAAA,MAC1B,OAAO;AAAA,MACP,OAAO;AAAA,IACR;AAAA,EACD;AAAA,EAtCQ;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,EAqBA,KACC,aACA,YAC+B;AAC/B,WAAO,QAAQ,QAAQ,KAAK,QAAQ,MAAM,KAAK,GAAG,CAAC,EACjD;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,109 @@
"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, {
GelDeleteBase: () => GelDeleteBase
});
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");
var import_utils2 = require("../utils.cjs");
class GelDeleteBase 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] = "GelDelete";
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, void 0, {
type: "delete",
tables: (0, import_utils2.extractUsedTable)(this.config.table)
});
});
}
prepare(name) {
return this._prepare(name);
}
execute = (placeholderValues) => {
return import_tracing.tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(placeholderValues);
});
};
$dynamic() {
return this;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
GelDeleteBase
});
//# sourceMappingURL=delete.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,99 @@
import { entityKind } from "../../entity.cjs";
import type { GelDialect } from "../dialect.cjs";
import type { GelPreparedQuery, GelQueryResultHKT, GelQueryResultKind, GelSession, PreparedQueryConfig } from "../session.cjs";
import type { GelTable } 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 GelDeleteWithout<T extends AnyGelDeleteBase, TDynamic extends boolean, K extends keyof T & string> = TDynamic extends true ? T : Omit<GelDeleteBase<T['_']['table'], T['_']['queryResult'], T['_']['returning'], TDynamic, T['_']['excludedMethods'] | K>, T['_']['excludedMethods'] | K>;
export type GelDelete<TTable extends GelTable = GelTable, TQueryResult extends GelQueryResultHKT = GelQueryResultHKT, TReturning extends Record<string, unknown> | undefined = Record<string, unknown> | undefined> = GelDeleteBase<TTable, TQueryResult, TReturning, true, never>;
export interface GelDeleteConfig {
where?: SQL | undefined;
table: GelTable;
returning?: SelectedFieldsOrdered;
withList?: Subquery[];
}
export type GelDeleteReturningAll<T extends AnyGelDeleteBase, TDynamic extends boolean> = GelDeleteWithout<GelDeleteBase<T['_']['table'], T['_']['queryResult'], T['_']['table']['$inferSelect'], TDynamic, T['_']['excludedMethods']>, TDynamic, 'returning'>;
export type GelDeleteReturning<T extends AnyGelDeleteBase, TDynamic extends boolean, TSelectedFields extends SelectedFieldsFlat> = GelDeleteWithout<GelDeleteBase<T['_']['table'], T['_']['queryResult'], SelectResultFields<TSelectedFields>, TDynamic, T['_']['excludedMethods']>, TDynamic, 'returning'>;
export type GelDeletePrepare<T extends AnyGelDeleteBase> = GelPreparedQuery<PreparedQueryConfig & {
execute: T['_']['returning'] extends undefined ? GelQueryResultKind<T['_']['queryResult'], never> : T['_']['returning'][];
}>;
export type GelDeleteDynamic<T extends AnyGelDeleteBase> = GelDelete<T['_']['table'], T['_']['queryResult'], T['_']['returning']>;
export type AnyGelDeleteBase = GelDeleteBase<any, any, any, any, any>;
export interface GelDeleteBase<TTable extends GelTable, TQueryResult extends GelQueryResultHKT, TReturning extends Record<string, unknown> | undefined = undefined, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[]>, RunnableQuery<TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[], 'gel'>, SQLWrapper {
readonly _: {
dialect: 'gel';
readonly table: TTable;
readonly queryResult: TQueryResult;
readonly returning: TReturning;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
readonly result: TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[];
};
}
export declare class GelDeleteBase<TTable extends GelTable, TQueryResult extends GelQueryResultHKT, TReturning extends Record<string, unknown> | undefined = undefined, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[]> implements RunnableQuery<TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[], 'gel'>, SQLWrapper {
private session;
private dialect;
static readonly [entityKind]: string;
private config;
constructor(table: TTable, session: GelSession, dialect: GelDialect, 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): GelDeleteWithout<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(): GelDeleteReturningAll<this, TDynamic>;
returning<TSelectedFields extends SelectedFieldsFlat>(fields: TSelectedFields): GelDeleteReturning<this, TDynamic, TSelectedFields>;
toSQL(): Query;
prepare(name: string): GelDeletePrepare<this>;
execute: ReturnType<this['prepare']>['execute'];
$dynamic(): GelDeleteDynamic<this>;
}

View File

@@ -0,0 +1,99 @@
import { entityKind } from "../../entity.js";
import type { GelDialect } from "../dialect.js";
import type { GelPreparedQuery, GelQueryResultHKT, GelQueryResultKind, GelSession, PreparedQueryConfig } from "../session.js";
import type { GelTable } 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 GelDeleteWithout<T extends AnyGelDeleteBase, TDynamic extends boolean, K extends keyof T & string> = TDynamic extends true ? T : Omit<GelDeleteBase<T['_']['table'], T['_']['queryResult'], T['_']['returning'], TDynamic, T['_']['excludedMethods'] | K>, T['_']['excludedMethods'] | K>;
export type GelDelete<TTable extends GelTable = GelTable, TQueryResult extends GelQueryResultHKT = GelQueryResultHKT, TReturning extends Record<string, unknown> | undefined = Record<string, unknown> | undefined> = GelDeleteBase<TTable, TQueryResult, TReturning, true, never>;
export interface GelDeleteConfig {
where?: SQL | undefined;
table: GelTable;
returning?: SelectedFieldsOrdered;
withList?: Subquery[];
}
export type GelDeleteReturningAll<T extends AnyGelDeleteBase, TDynamic extends boolean> = GelDeleteWithout<GelDeleteBase<T['_']['table'], T['_']['queryResult'], T['_']['table']['$inferSelect'], TDynamic, T['_']['excludedMethods']>, TDynamic, 'returning'>;
export type GelDeleteReturning<T extends AnyGelDeleteBase, TDynamic extends boolean, TSelectedFields extends SelectedFieldsFlat> = GelDeleteWithout<GelDeleteBase<T['_']['table'], T['_']['queryResult'], SelectResultFields<TSelectedFields>, TDynamic, T['_']['excludedMethods']>, TDynamic, 'returning'>;
export type GelDeletePrepare<T extends AnyGelDeleteBase> = GelPreparedQuery<PreparedQueryConfig & {
execute: T['_']['returning'] extends undefined ? GelQueryResultKind<T['_']['queryResult'], never> : T['_']['returning'][];
}>;
export type GelDeleteDynamic<T extends AnyGelDeleteBase> = GelDelete<T['_']['table'], T['_']['queryResult'], T['_']['returning']>;
export type AnyGelDeleteBase = GelDeleteBase<any, any, any, any, any>;
export interface GelDeleteBase<TTable extends GelTable, TQueryResult extends GelQueryResultHKT, TReturning extends Record<string, unknown> | undefined = undefined, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[]>, RunnableQuery<TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[], 'gel'>, SQLWrapper {
readonly _: {
dialect: 'gel';
readonly table: TTable;
readonly queryResult: TQueryResult;
readonly returning: TReturning;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
readonly result: TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[];
};
}
export declare class GelDeleteBase<TTable extends GelTable, TQueryResult extends GelQueryResultHKT, TReturning extends Record<string, unknown> | undefined = undefined, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[]> implements RunnableQuery<TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[], 'gel'>, SQLWrapper {
private session;
private dialect;
static readonly [entityKind]: string;
private config;
constructor(table: TTable, session: GelSession, dialect: GelDialect, 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): GelDeleteWithout<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(): GelDeleteReturningAll<this, TDynamic>;
returning<TSelectedFields extends SelectedFieldsFlat>(fields: TSelectedFields): GelDeleteReturning<this, TDynamic, TSelectedFields>;
toSQL(): Query;
prepare(name: string): GelDeletePrepare<this>;
execute: ReturnType<this['prepare']>['execute'];
$dynamic(): GelDeleteDynamic<this>;
}

View File

@@ -0,0 +1,85 @@
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";
import { extractUsedTable } from "../utils.js";
class GelDeleteBase extends QueryPromise {
constructor(table, session, dialect, withList) {
super();
this.session = session;
this.dialect = dialect;
this.config = { table, withList };
}
static [entityKind] = "GelDelete";
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, void 0, {
type: "delete",
tables: extractUsedTable(this.config.table)
});
});
}
prepare(name) {
return this._prepare(name);
}
execute = (placeholderValues) => {
return tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(placeholderValues);
});
};
$dynamic() {
return this;
}
}
export {
GelDeleteBase
};
//# 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/gel-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/gel-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,222 @@
"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, {
GelInsertBase: () => GelInsertBase,
GelInsertBuilder: () => GelInsertBuilder
});
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_utils2 = require("../utils.cjs");
var import_query_builder = require("./query-builder.cjs");
class GelInsertBuilder {
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] = "GelInsertBuilder";
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 GelInsertBase(
this.table,
mappedValues,
this.session,
this.dialect,
this.withList,
false,
this.overridingSystemValue_
);
}
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 GelInsertBase(this.table, select, this.session, this.dialect, this.withList, true);
}
}
class GelInsertBase 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] = "GelInsert";
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 });
* ```
*/
// TODO not supported
// onConflictDoNothing(
// config: { target?: IndexColumn | IndexColumn[]; where?: SQL } = {},
// ): GelInsertWithout<this, TDynamic, 'onConflictDoNothing' | 'onConflictDoUpdate'> {
// if (config.target === undefined) {
// 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}` : undefined;
// this.config.onConflict = sql`(${sql.raw(targetColumn)})${whereSql} do nothing`;
// }
// return this as any;
// }
/**
* 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`,
* });
* ```
*/
// TODO not supported
// onConflictDoUpdate(
// config: GelInsertOnConflictDoUpdateConfig<this>,
// ): GelInsertWithout<this, TDynamic, 'onConflictDoNothing' | 'onConflictDoUpdate'> {
// 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}` : undefined;
// const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : undefined;
// const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : undefined;
// 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 as any;
// }
/** @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, void 0, {
type: "insert",
tables: (0, import_utils2.extractUsedTable)(this.config.table)
});
});
}
prepare(name) {
return this._prepare(name);
}
execute = (placeholderValues) => {
return import_tracing.tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(placeholderValues);
});
};
$dynamic() {
return this;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
GelInsertBase,
GelInsertBuilder
});
//# sourceMappingURL=insert.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,116 @@
import { entityKind } from "../../entity.cjs";
import type { GelDialect } from "../dialect.cjs";
import type { IndexColumn } from "../indexes.cjs";
import type { GelPreparedQuery, GelQueryResultHKT, GelQueryResultKind, GelSession, PreparedQueryConfig } from "../session.cjs";
import type { GelTable, 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 { AnyGelColumn } from "../columns/common.cjs";
import { QueryBuilder } from "./query-builder.cjs";
import type { SelectedFieldsFlat, SelectedFieldsOrdered } from "./select.types.cjs";
import type { GelUpdateSetSource } from "./update.cjs";
export interface GelInsertConfig<TTable extends GelTable = GelTable> {
table: TTable;
values: Record<string, Param | SQL>[] | GelInsertSelectQueryBuilder<TTable> | SQL;
withList?: Subquery[];
onConflict?: SQL;
returning?: SelectedFieldsOrdered;
select?: boolean;
overridingSystemValue_?: boolean;
}
export type GelInsertValue<TTable extends GelTable<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 GelInsertSelectQueryBuilder<TTable extends GelTable> = TypedQueryBuilder<{
[K in keyof TTable['$inferInsert']]: AnyGelColumn | SQL | SQL.Aliased | TTable['$inferInsert'][K];
}>;
export declare class GelInsertBuilder<TTable extends GelTable, TQueryResult extends GelQueryResultHKT, OverrideT extends boolean = false> {
private table;
private session;
private dialect;
private withList?;
private overridingSystemValue_?;
static readonly [entityKind]: string;
constructor(table: TTable, session: GelSession, dialect: GelDialect, withList?: Subquery[] | undefined, overridingSystemValue_?: boolean | undefined);
private authToken?;
overridingSystemValue(): Omit<GelInsertBuilder<TTable, TQueryResult, true>, 'overridingSystemValue'>;
values(value: GelInsertValue<TTable, OverrideT>): GelInsertBase<TTable, TQueryResult>;
values(values: GelInsertValue<TTable, OverrideT>[]): GelInsertBase<TTable, TQueryResult>;
select(selectQuery: (qb: QueryBuilder) => GelInsertSelectQueryBuilder<TTable>): GelInsertBase<TTable, TQueryResult>;
select(selectQuery: (qb: QueryBuilder) => SQL): GelInsertBase<TTable, TQueryResult>;
select(selectQuery: SQL): GelInsertBase<TTable, TQueryResult>;
select(selectQuery: GelInsertSelectQueryBuilder<TTable>): GelInsertBase<TTable, TQueryResult>;
}
export type GelInsertWithout<T extends AnyGelInsert, TDynamic extends boolean, K extends keyof T & string> = TDynamic extends true ? T : Omit<GelInsertBase<T['_']['table'], T['_']['queryResult'], T['_']['returning'], TDynamic, T['_']['excludedMethods'] | K>, T['_']['excludedMethods'] | K>;
export type GelInsertReturning<T extends AnyGelInsert, TDynamic extends boolean, TSelectedFields extends SelectedFieldsFlat> = GelInsertBase<T['_']['table'], T['_']['queryResult'], SelectResultFields<TSelectedFields>, TDynamic, T['_']['excludedMethods']>;
export type GelInsertReturningAll<T extends AnyGelInsert, TDynamic extends boolean> = GelInsertBase<T['_']['table'], T['_']['queryResult'], T['_']['table']['$inferSelect'], TDynamic, T['_']['excludedMethods']>;
export interface GelInsertOnConflictDoUpdateConfig<T extends AnyGelInsert> {
target: IndexColumn | IndexColumn[];
/** @deprecated use either `targetWhere` or `setWhere` */
where?: SQL;
targetWhere?: SQL;
setWhere?: SQL;
set: GelUpdateSetSource<T['_']['table']>;
}
export type GelInsertPrepare<T extends AnyGelInsert> = GelPreparedQuery<PreparedQueryConfig & {
execute: T['_']['returning'] extends undefined ? GelQueryResultKind<T['_']['queryResult'], never> : T['_']['returning'][];
}>;
export type GelInsertDynamic<T extends AnyGelInsert> = GelInsert<T['_']['table'], T['_']['queryResult'], T['_']['returning']>;
export type AnyGelInsert = GelInsertBase<any, any, any, any, any>;
export type GelInsert<TTable extends GelTable = GelTable, TQueryResult extends GelQueryResultHKT = GelQueryResultHKT, TReturning extends Record<string, unknown> | undefined = Record<string, unknown> | undefined> = GelInsertBase<TTable, TQueryResult, TReturning, true, never>;
export interface GelInsertBase<TTable extends GelTable, TQueryResult extends GelQueryResultHKT, TReturning extends Record<string, unknown> | undefined = undefined, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[]>, RunnableQuery<TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[], 'gel'>, SQLWrapper {
readonly _: {
readonly dialect: 'gel';
readonly table: TTable;
readonly queryResult: TQueryResult;
readonly returning: TReturning;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
readonly result: TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[];
};
}
export declare class GelInsertBase<TTable extends GelTable, TQueryResult extends GelQueryResultHKT, TReturning extends Record<string, unknown> | undefined = undefined, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[]> implements RunnableQuery<TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[], 'gel'>, SQLWrapper {
private session;
private dialect;
static readonly [entityKind]: string;
private config;
constructor(table: TTable, values: GelInsertConfig['values'], session: GelSession, dialect: GelDialect, 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(): GelInsertWithout<GelInsertReturningAll<this, TDynamic>, TDynamic, 'returning'>;
returning<TSelectedFields extends SelectedFieldsFlat>(fields: TSelectedFields): GelInsertWithout<GelInsertReturning<this, TDynamic, TSelectedFields>, TDynamic, 'returning'>;
toSQL(): Query;
prepare(name: string): GelInsertPrepare<this>;
execute: ReturnType<this['prepare']>['execute'];
$dynamic(): GelInsertDynamic<this>;
}

View File

@@ -0,0 +1,116 @@
import { entityKind } from "../../entity.js";
import type { GelDialect } from "../dialect.js";
import type { IndexColumn } from "../indexes.js";
import type { GelPreparedQuery, GelQueryResultHKT, GelQueryResultKind, GelSession, PreparedQueryConfig } from "../session.js";
import type { GelTable, 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 { AnyGelColumn } from "../columns/common.js";
import { QueryBuilder } from "./query-builder.js";
import type { SelectedFieldsFlat, SelectedFieldsOrdered } from "./select.types.js";
import type { GelUpdateSetSource } from "./update.js";
export interface GelInsertConfig<TTable extends GelTable = GelTable> {
table: TTable;
values: Record<string, Param | SQL>[] | GelInsertSelectQueryBuilder<TTable> | SQL;
withList?: Subquery[];
onConflict?: SQL;
returning?: SelectedFieldsOrdered;
select?: boolean;
overridingSystemValue_?: boolean;
}
export type GelInsertValue<TTable extends GelTable<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 GelInsertSelectQueryBuilder<TTable extends GelTable> = TypedQueryBuilder<{
[K in keyof TTable['$inferInsert']]: AnyGelColumn | SQL | SQL.Aliased | TTable['$inferInsert'][K];
}>;
export declare class GelInsertBuilder<TTable extends GelTable, TQueryResult extends GelQueryResultHKT, OverrideT extends boolean = false> {
private table;
private session;
private dialect;
private withList?;
private overridingSystemValue_?;
static readonly [entityKind]: string;
constructor(table: TTable, session: GelSession, dialect: GelDialect, withList?: Subquery[] | undefined, overridingSystemValue_?: boolean | undefined);
private authToken?;
overridingSystemValue(): Omit<GelInsertBuilder<TTable, TQueryResult, true>, 'overridingSystemValue'>;
values(value: GelInsertValue<TTable, OverrideT>): GelInsertBase<TTable, TQueryResult>;
values(values: GelInsertValue<TTable, OverrideT>[]): GelInsertBase<TTable, TQueryResult>;
select(selectQuery: (qb: QueryBuilder) => GelInsertSelectQueryBuilder<TTable>): GelInsertBase<TTable, TQueryResult>;
select(selectQuery: (qb: QueryBuilder) => SQL): GelInsertBase<TTable, TQueryResult>;
select(selectQuery: SQL): GelInsertBase<TTable, TQueryResult>;
select(selectQuery: GelInsertSelectQueryBuilder<TTable>): GelInsertBase<TTable, TQueryResult>;
}
export type GelInsertWithout<T extends AnyGelInsert, TDynamic extends boolean, K extends keyof T & string> = TDynamic extends true ? T : Omit<GelInsertBase<T['_']['table'], T['_']['queryResult'], T['_']['returning'], TDynamic, T['_']['excludedMethods'] | K>, T['_']['excludedMethods'] | K>;
export type GelInsertReturning<T extends AnyGelInsert, TDynamic extends boolean, TSelectedFields extends SelectedFieldsFlat> = GelInsertBase<T['_']['table'], T['_']['queryResult'], SelectResultFields<TSelectedFields>, TDynamic, T['_']['excludedMethods']>;
export type GelInsertReturningAll<T extends AnyGelInsert, TDynamic extends boolean> = GelInsertBase<T['_']['table'], T['_']['queryResult'], T['_']['table']['$inferSelect'], TDynamic, T['_']['excludedMethods']>;
export interface GelInsertOnConflictDoUpdateConfig<T extends AnyGelInsert> {
target: IndexColumn | IndexColumn[];
/** @deprecated use either `targetWhere` or `setWhere` */
where?: SQL;
targetWhere?: SQL;
setWhere?: SQL;
set: GelUpdateSetSource<T['_']['table']>;
}
export type GelInsertPrepare<T extends AnyGelInsert> = GelPreparedQuery<PreparedQueryConfig & {
execute: T['_']['returning'] extends undefined ? GelQueryResultKind<T['_']['queryResult'], never> : T['_']['returning'][];
}>;
export type GelInsertDynamic<T extends AnyGelInsert> = GelInsert<T['_']['table'], T['_']['queryResult'], T['_']['returning']>;
export type AnyGelInsert = GelInsertBase<any, any, any, any, any>;
export type GelInsert<TTable extends GelTable = GelTable, TQueryResult extends GelQueryResultHKT = GelQueryResultHKT, TReturning extends Record<string, unknown> | undefined = Record<string, unknown> | undefined> = GelInsertBase<TTable, TQueryResult, TReturning, true, never>;
export interface GelInsertBase<TTable extends GelTable, TQueryResult extends GelQueryResultHKT, TReturning extends Record<string, unknown> | undefined = undefined, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[]>, RunnableQuery<TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[], 'gel'>, SQLWrapper {
readonly _: {
readonly dialect: 'gel';
readonly table: TTable;
readonly queryResult: TQueryResult;
readonly returning: TReturning;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
readonly result: TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[];
};
}
export declare class GelInsertBase<TTable extends GelTable, TQueryResult extends GelQueryResultHKT, TReturning extends Record<string, unknown> | undefined = undefined, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[]> implements RunnableQuery<TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[], 'gel'>, SQLWrapper {
private session;
private dialect;
static readonly [entityKind]: string;
private config;
constructor(table: TTable, values: GelInsertConfig['values'], session: GelSession, dialect: GelDialect, 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(): GelInsertWithout<GelInsertReturningAll<this, TDynamic>, TDynamic, 'returning'>;
returning<TSelectedFields extends SelectedFieldsFlat>(fields: TSelectedFields): GelInsertWithout<GelInsertReturning<this, TDynamic, TSelectedFields>, TDynamic, 'returning'>;
toSQL(): Query;
prepare(name: string): GelInsertPrepare<this>;
execute: ReturnType<this['prepare']>['execute'];
$dynamic(): GelInsertDynamic<this>;
}

View File

@@ -0,0 +1,197 @@
import { entityKind, is } from "../../entity.js";
import { QueryPromise } from "../../query-promise.js";
import { Param, SQL } from "../../sql/sql.js";
import { Columns, Table } from "../../table.js";
import { tracer } from "../../tracing.js";
import { haveSameKeys, orderSelectedFields } from "../../utils.js";
import { extractUsedTable } from "../utils.js";
import { QueryBuilder } from "./query-builder.js";
class GelInsertBuilder {
constructor(table, session, dialect, withList, overridingSystemValue_) {
this.table = table;
this.session = session;
this.dialect = dialect;
this.withList = withList;
this.overridingSystemValue_ = overridingSystemValue_;
}
static [entityKind] = "GelInsertBuilder";
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 GelInsertBase(
this.table,
mappedValues,
this.session,
this.dialect,
this.withList,
false,
this.overridingSystemValue_
);
}
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 GelInsertBase(this.table, select, this.session, this.dialect, this.withList, true);
}
}
class GelInsertBase 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] = "GelInsert";
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 });
* ```
*/
// TODO not supported
// onConflictDoNothing(
// config: { target?: IndexColumn | IndexColumn[]; where?: SQL } = {},
// ): GelInsertWithout<this, TDynamic, 'onConflictDoNothing' | 'onConflictDoUpdate'> {
// if (config.target === undefined) {
// 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}` : undefined;
// this.config.onConflict = sql`(${sql.raw(targetColumn)})${whereSql} do nothing`;
// }
// return this as any;
// }
/**
* 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`,
* });
* ```
*/
// TODO not supported
// onConflictDoUpdate(
// config: GelInsertOnConflictDoUpdateConfig<this>,
// ): GelInsertWithout<this, TDynamic, 'onConflictDoNothing' | 'onConflictDoUpdate'> {
// 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}` : undefined;
// const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : undefined;
// const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : undefined;
// 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 as any;
// }
/** @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, void 0, {
type: "insert",
tables: extractUsedTable(this.config.table)
});
});
}
prepare(name) {
return this._prepare(name);
}
execute = (placeholderValues) => {
return tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(placeholderValues);
});
};
$dynamic() {
return this;
}
}
export {
GelInsertBase,
GelInsertBuilder
};
//# 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] = "GelQueryBuilder";
dialect;
dialectConfig;
constructor(dialect) {
this.dialect = (0, import_entity.is)(dialect, import_dialect.GelDialect) ? dialect : void 0;
this.dialectConfig = (0, import_entity.is)(dialect, import_dialect.GelDialect) ? 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.GelSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: self.getDialect(),
withList: queries
});
}
function selectDistinct(fields) {
return new import_select.GelSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: self.getDialect(),
distinct: true
});
}
function selectDistinctOn(on, fields) {
return new import_select.GelSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: self.getDialect(),
distinct: { on }
});
}
return { select, selectDistinct, selectDistinctOn };
}
select(fields) {
return new import_select.GelSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: this.getDialect()
});
}
selectDistinct(fields) {
return new import_select.GelSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: this.getDialect(),
distinct: true
});
}
selectDistinctOn(on, fields) {
return new import_select.GelSelectBuilder({
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.GelDialect(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 { GelDialectConfig } from "../dialect.cjs";
import { GelDialect } 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 { GelColumn } from "../columns/index.cjs";
import type { WithSubqueryWithSelection } from "../subquery.cjs";
import { GelSelectBuilder } from "./select.cjs";
import type { SelectedFields } from "./select.types.cjs";
export declare class QueryBuilder {
static readonly [entityKind]: string;
private dialect;
private dialectConfig;
constructor(dialect?: GelDialect | GelDialectConfig);
$with<TAlias extends string>(alias: TAlias): {
as<TSelection extends ColumnsSelection>(qb: TypedQueryBuilder<TSelection> | ((qb: QueryBuilder) => TypedQueryBuilder<TSelection>)): WithSubqueryWithSelection<TSelection, TAlias>;
};
with(...queries: WithSubquery[]): {
select: {
(): GelSelectBuilder<undefined, "qb">;
<TSelection extends SelectedFields>(fields: TSelection): GelSelectBuilder<TSelection, "qb">;
};
selectDistinct: {
(): GelSelectBuilder<undefined, "qb">;
<TSelection extends SelectedFields>(fields: TSelection): GelSelectBuilder<TSelection, "qb">;
};
selectDistinctOn: {
(on: (GelColumn | SQLWrapper)[]): GelSelectBuilder<undefined, "qb">;
<TSelection extends SelectedFields>(on: (GelColumn | SQLWrapper)[], fields: TSelection): GelSelectBuilder<TSelection, "qb">;
};
};
select(): GelSelectBuilder<undefined, 'qb'>;
select<TSelection extends SelectedFields>(fields: TSelection): GelSelectBuilder<TSelection, 'qb'>;
selectDistinct(): GelSelectBuilder<undefined>;
selectDistinct<TSelection extends SelectedFields>(fields: TSelection): GelSelectBuilder<TSelection>;
selectDistinctOn(on: (GelColumn | SQLWrapper)[]): GelSelectBuilder<undefined>;
selectDistinctOn<TSelection extends SelectedFields>(on: (GelColumn | SQLWrapper)[], fields: TSelection): GelSelectBuilder<TSelection>;
private getDialect;
}

View File

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

View File

@@ -0,0 +1,90 @@
import { entityKind, is } from "../../entity.js";
import { GelDialect } from "../dialect.js";
import { SelectionProxyHandler } from "../../selection-proxy.js";
import { WithSubquery } from "../../subquery.js";
import { GelSelectBuilder } from "./select.js";
class QueryBuilder {
static [entityKind] = "GelQueryBuilder";
dialect;
dialectConfig;
constructor(dialect) {
this.dialect = is(dialect, GelDialect) ? dialect : void 0;
this.dialectConfig = is(dialect, GelDialect) ? 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 GelSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: self.getDialect(),
withList: queries
});
}
function selectDistinct(fields) {
return new GelSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: self.getDialect(),
distinct: true
});
}
function selectDistinctOn(on, fields) {
return new GelSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: self.getDialect(),
distinct: { on }
});
}
return { select, selectDistinct, selectDistinctOn };
}
select(fields) {
return new GelSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: this.getDialect()
});
}
selectDistinct(fields) {
return new GelSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: this.getDialect(),
distinct: true
});
}
selectDistinctOn(on, fields) {
return new GelSelectBuilder({
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 GelDialect(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,139 @@
"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, {
GelRelationalQuery: () => GelRelationalQuery,
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] = "GelRelationalQueryBuilder";
findMany(config) {
return new GelRelationalQuery(
this.fullSchema,
this.schema,
this.tableNamesMap,
this.table,
this.tableConfig,
this.dialect,
this.session,
config ? config : {},
"many"
);
}
findFirst(config) {
return new GelRelationalQuery(
this.fullSchema,
this.schema,
this.tableNamesMap,
this.table,
this.tableConfig,
this.dialect,
this.session,
config ? { ...config, limit: 1 } : { limit: 1 },
"first"
);
}
}
class GelRelationalQuery 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] = "GelRelationalQuery";
/** @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;
}
execute() {
return import_tracing.tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(void 0);
});
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
GelRelationalQuery,
RelationalQueryBuilder
});
//# sourceMappingURL=query.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,46 @@
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 { GelDialect } from "../dialect.cjs";
import type { GelPreparedQuery, GelSession, PreparedQueryConfig } from "../session.cjs";
import type { GelTable } 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: GelTable, tableConfig: TableRelationalConfig, dialect: GelDialect, session: GelSession);
findMany<TConfig extends DBQueryConfig<'many', true, TSchema, TFields>>(config?: KnownKeysOnly<TConfig, DBQueryConfig<'many', true, TSchema, TFields>>): GelRelationalQuery<BuildQueryResult<TSchema, TFields, TConfig>[]>;
findFirst<TSelection extends Omit<DBQueryConfig<'many', true, TSchema, TFields>, 'limit'>>(config?: KnownKeysOnly<TSelection, Omit<DBQueryConfig<'many', true, TSchema, TFields>, 'limit'>>): GelRelationalQuery<BuildQueryResult<TSchema, TFields, TSelection> | undefined>;
}
export declare class GelRelationalQuery<TResult> extends QueryPromise<TResult> implements RunnableQuery<TResult, 'gel'>, 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: 'gel';
readonly result: TResult;
};
constructor(fullSchema: Record<string, unknown>, schema: TablesRelationalConfig, tableNamesMap: Record<string, string>, table: GelTable, tableConfig: TableRelationalConfig, dialect: GelDialect, session: GelSession, config: DBQueryConfig<'many', true> | true, mode: 'many' | 'first');
prepare(name: string): GelPreparedQuery<PreparedQueryConfig & {
execute: TResult;
}>;
private _getQuery;
private _toSQL;
toSQL(): Query;
execute(): Promise<TResult>;
}

View File

@@ -0,0 +1,46 @@
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 { GelDialect } from "../dialect.js";
import type { GelPreparedQuery, GelSession, PreparedQueryConfig } from "../session.js";
import type { GelTable } 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: GelTable, tableConfig: TableRelationalConfig, dialect: GelDialect, session: GelSession);
findMany<TConfig extends DBQueryConfig<'many', true, TSchema, TFields>>(config?: KnownKeysOnly<TConfig, DBQueryConfig<'many', true, TSchema, TFields>>): GelRelationalQuery<BuildQueryResult<TSchema, TFields, TConfig>[]>;
findFirst<TSelection extends Omit<DBQueryConfig<'many', true, TSchema, TFields>, 'limit'>>(config?: KnownKeysOnly<TSelection, Omit<DBQueryConfig<'many', true, TSchema, TFields>, 'limit'>>): GelRelationalQuery<BuildQueryResult<TSchema, TFields, TSelection> | undefined>;
}
export declare class GelRelationalQuery<TResult> extends QueryPromise<TResult> implements RunnableQuery<TResult, 'gel'>, 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: 'gel';
readonly result: TResult;
};
constructor(fullSchema: Record<string, unknown>, schema: TablesRelationalConfig, tableNamesMap: Record<string, string>, table: GelTable, tableConfig: TableRelationalConfig, dialect: GelDialect, session: GelSession, config: DBQueryConfig<'many', true> | true, mode: 'many' | 'first');
prepare(name: string): GelPreparedQuery<PreparedQueryConfig & {
execute: TResult;
}>;
private _getQuery;
private _toSQL;
toSQL(): Query;
execute(): Promise<TResult>;
}

View File

@@ -0,0 +1,116 @@
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] = "GelRelationalQueryBuilder";
findMany(config) {
return new GelRelationalQuery(
this.fullSchema,
this.schema,
this.tableNamesMap,
this.table,
this.tableConfig,
this.dialect,
this.session,
config ? config : {},
"many"
);
}
findFirst(config) {
return new GelRelationalQuery(
this.fullSchema,
this.schema,
this.tableNamesMap,
this.table,
this.tableConfig,
this.dialect,
this.session,
config ? { ...config, limit: 1 } : { limit: 1 },
"first"
);
}
}
class GelRelationalQuery 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] = "GelRelationalQuery";
/** @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;
}
execute() {
return tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(void 0);
});
}
}
export {
GelRelationalQuery,
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, {
GelRaw: () => GelRaw
});
module.exports = __toCommonJS(raw_exports);
var import_entity = require("../../entity.cjs");
var import_query_promise = require("../../query-promise.cjs");
class GelRaw 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] = "GelRaw";
/** @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 = {
GelRaw
});
//# sourceMappingURL=raw.cjs.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/gel-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 GelRaw<TResult> extends QueryPromise<TResult>, RunnableQuery<TResult, 'gel'>, SQLWrapper {}\n\nexport class GelRaw<TResult> extends QueryPromise<TResult>\n\timplements RunnableQuery<TResult, 'gel'>, SQLWrapper, PreparedQuery\n{\n\tstatic override readonly [entityKind]: string = 'GelRaw';\n\n\tdeclare readonly _: {\n\t\treadonly dialect: 'gel';\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,eAAwB,kCAErC;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 GelRaw<TResult> extends QueryPromise<TResult>, RunnableQuery<TResult, 'gel'>, SQLWrapper {
}
export declare class GelRaw<TResult> extends QueryPromise<TResult> implements RunnableQuery<TResult, 'gel'>, SQLWrapper, PreparedQuery {
execute: () => Promise<TResult>;
private sql;
private query;
private mapBatchResult;
static readonly [entityKind]: string;
readonly _: {
readonly dialect: 'gel';
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 GelRaw<TResult> extends QueryPromise<TResult>, RunnableQuery<TResult, 'gel'>, SQLWrapper {
}
export declare class GelRaw<TResult> extends QueryPromise<TResult> implements RunnableQuery<TResult, 'gel'>, SQLWrapper, PreparedQuery {
execute: () => Promise<TResult>;
private sql;
private query;
private mapBatchResult;
static readonly [entityKind]: string;
readonly _: {
readonly dialect: 'gel';
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,33 @@
import { entityKind } from "../../entity.js";
import { QueryPromise } from "../../query-promise.js";
class GelRaw extends QueryPromise {
constructor(execute, sql, query, mapBatchResult) {
super();
this.execute = execute;
this.sql = sql;
this.query = query;
this.mapBatchResult = mapBatchResult;
}
static [entityKind] = "GelRaw";
/** @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 {
GelRaw
};
//# sourceMappingURL=raw.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/gel-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 GelRaw<TResult> extends QueryPromise<TResult>, RunnableQuery<TResult, 'gel'>, SQLWrapper {}\n\nexport class GelRaw<TResult> extends QueryPromise<TResult>\n\timplements RunnableQuery<TResult, 'gel'>, SQLWrapper, PreparedQuery\n{\n\tstatic override readonly [entityKind]: string = 'GelRaw';\n\n\tdeclare readonly _: {\n\t\treadonly dialect: 'gel';\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,eAAwB,aAErC;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,77 @@
"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, {
GelRefreshMaterializedView: () => GelRefreshMaterializedView
});
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 GelRefreshMaterializedView extends import_query_promise.QueryPromise {
constructor(view, session, dialect) {
super();
this.session = session;
this.dialect = dialect;
this.config = { view };
}
static [import_entity.entityKind] = "GelRefreshMaterializedView";
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);
}
execute = (placeholderValues) => {
return import_tracing.tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(placeholderValues);
});
};
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
GelRefreshMaterializedView
});
//# sourceMappingURL=refresh-materialized-view.cjs.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/gel-core/query-builders/refresh-materialized-view.ts"],"sourcesContent":["import { entityKind } from '~/entity.ts';\nimport type { GelDialect } from '~/gel-core/dialect.ts';\nimport type {\n\tGelPreparedQuery,\n\tGelQueryResultHKT,\n\tGelQueryResultKind,\n\tGelSession,\n\tPreparedQueryConfig,\n} from '~/gel-core/session.ts';\nimport type { GelMaterializedView } from '~/gel-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';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface GelRefreshMaterializedView<TQueryResult extends GelQueryResultHKT>\n\textends\n\t\tQueryPromise<GelQueryResultKind<TQueryResult, never>>,\n\t\tRunnableQuery<GelQueryResultKind<TQueryResult, never>, 'gel'>,\n\t\tSQLWrapper\n{\n\treadonly _: {\n\t\treadonly dialect: 'gel';\n\t\treadonly result: GelQueryResultKind<TQueryResult, never>;\n\t};\n}\n\nexport class GelRefreshMaterializedView<TQueryResult extends GelQueryResultHKT>\n\textends QueryPromise<GelQueryResultKind<TQueryResult, never>>\n\timplements RunnableQuery<GelQueryResultKind<TQueryResult, never>, 'gel'>, SQLWrapper\n{\n\tstatic override readonly [entityKind]: string = 'GelRefreshMaterializedView';\n\n\tprivate config: {\n\t\tview: GelMaterializedView;\n\t\tconcurrently?: boolean;\n\t\twithNoData?: boolean;\n\t};\n\n\tconstructor(\n\t\tview: GelMaterializedView,\n\t\tprivate session: GelSession,\n\t\tprivate dialect: GelDialect,\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): GelPreparedQuery<\n\t\tPreparedQueryConfig & {\n\t\t\texecute: GelQueryResultKind<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): GelPreparedQuery<\n\t\tPreparedQueryConfig & {\n\t\t\texecute: GelQueryResultKind<TQueryResult, never>;\n\t\t}\n\t> {\n\t\treturn this._prepare(name);\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);\n\t\t});\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA2B;AAU3B,2BAA6B;AAG7B,qBAAuB;AAehB,MAAM,mCACJ,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,EAEA,UAAkD,CAAC,sBAAsB;AACxE,WAAO,sBAAO,gBAAgB,qBAAqB,MAAM;AACxD,aAAO,KAAK,SAAS,EAAE,QAAQ,iBAAiB;AAAA,IACjD,CAAC;AAAA,EACF;AACD;","names":[]}

View File

@@ -0,0 +1,27 @@
import { entityKind } from "../../entity.cjs";
import type { GelDialect } from "../dialect.cjs";
import type { GelPreparedQuery, GelQueryResultHKT, GelQueryResultKind, GelSession, PreparedQueryConfig } from "../session.cjs";
import type { GelMaterializedView } 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 GelRefreshMaterializedView<TQueryResult extends GelQueryResultHKT> extends QueryPromise<GelQueryResultKind<TQueryResult, never>>, RunnableQuery<GelQueryResultKind<TQueryResult, never>, 'gel'>, SQLWrapper {
readonly _: {
readonly dialect: 'gel';
readonly result: GelQueryResultKind<TQueryResult, never>;
};
}
export declare class GelRefreshMaterializedView<TQueryResult extends GelQueryResultHKT> extends QueryPromise<GelQueryResultKind<TQueryResult, never>> implements RunnableQuery<GelQueryResultKind<TQueryResult, never>, 'gel'>, SQLWrapper {
private session;
private dialect;
static readonly [entityKind]: string;
private config;
constructor(view: GelMaterializedView, session: GelSession, dialect: GelDialect);
concurrently(): this;
withNoData(): this;
toSQL(): Query;
prepare(name: string): GelPreparedQuery<PreparedQueryConfig & {
execute: GelQueryResultKind<TQueryResult, never>;
}>;
execute: ReturnType<this['prepare']>['execute'];
}

View File

@@ -0,0 +1,27 @@
import { entityKind } from "../../entity.js";
import type { GelDialect } from "../dialect.js";
import type { GelPreparedQuery, GelQueryResultHKT, GelQueryResultKind, GelSession, PreparedQueryConfig } from "../session.js";
import type { GelMaterializedView } 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 GelRefreshMaterializedView<TQueryResult extends GelQueryResultHKT> extends QueryPromise<GelQueryResultKind<TQueryResult, never>>, RunnableQuery<GelQueryResultKind<TQueryResult, never>, 'gel'>, SQLWrapper {
readonly _: {
readonly dialect: 'gel';
readonly result: GelQueryResultKind<TQueryResult, never>;
};
}
export declare class GelRefreshMaterializedView<TQueryResult extends GelQueryResultHKT> extends QueryPromise<GelQueryResultKind<TQueryResult, never>> implements RunnableQuery<GelQueryResultKind<TQueryResult, never>, 'gel'>, SQLWrapper {
private session;
private dialect;
static readonly [entityKind]: string;
private config;
constructor(view: GelMaterializedView, session: GelSession, dialect: GelDialect);
concurrently(): this;
withNoData(): this;
toSQL(): Query;
prepare(name: string): GelPreparedQuery<PreparedQueryConfig & {
execute: GelQueryResultKind<TQueryResult, never>;
}>;
execute: ReturnType<this['prepare']>['execute'];
}

View File

@@ -0,0 +1,53 @@
import { entityKind } from "../../entity.js";
import { QueryPromise } from "../../query-promise.js";
import { tracer } from "../../tracing.js";
class GelRefreshMaterializedView extends QueryPromise {
constructor(view, session, dialect) {
super();
this.session = session;
this.dialect = dialect;
this.config = { view };
}
static [entityKind] = "GelRefreshMaterializedView";
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);
}
execute = (placeholderValues) => {
return tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(placeholderValues);
});
};
}
export {
GelRefreshMaterializedView
};
//# sourceMappingURL=refresh-materialized-view.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/gel-core/query-builders/refresh-materialized-view.ts"],"sourcesContent":["import { entityKind } from '~/entity.ts';\nimport type { GelDialect } from '~/gel-core/dialect.ts';\nimport type {\n\tGelPreparedQuery,\n\tGelQueryResultHKT,\n\tGelQueryResultKind,\n\tGelSession,\n\tPreparedQueryConfig,\n} from '~/gel-core/session.ts';\nimport type { GelMaterializedView } from '~/gel-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';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface GelRefreshMaterializedView<TQueryResult extends GelQueryResultHKT>\n\textends\n\t\tQueryPromise<GelQueryResultKind<TQueryResult, never>>,\n\t\tRunnableQuery<GelQueryResultKind<TQueryResult, never>, 'gel'>,\n\t\tSQLWrapper\n{\n\treadonly _: {\n\t\treadonly dialect: 'gel';\n\t\treadonly result: GelQueryResultKind<TQueryResult, never>;\n\t};\n}\n\nexport class GelRefreshMaterializedView<TQueryResult extends GelQueryResultHKT>\n\textends QueryPromise<GelQueryResultKind<TQueryResult, never>>\n\timplements RunnableQuery<GelQueryResultKind<TQueryResult, never>, 'gel'>, SQLWrapper\n{\n\tstatic override readonly [entityKind]: string = 'GelRefreshMaterializedView';\n\n\tprivate config: {\n\t\tview: GelMaterializedView;\n\t\tconcurrently?: boolean;\n\t\twithNoData?: boolean;\n\t};\n\n\tconstructor(\n\t\tview: GelMaterializedView,\n\t\tprivate session: GelSession,\n\t\tprivate dialect: GelDialect,\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): GelPreparedQuery<\n\t\tPreparedQueryConfig & {\n\t\t\texecute: GelQueryResultKind<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): GelPreparedQuery<\n\t\tPreparedQueryConfig & {\n\t\t\texecute: GelQueryResultKind<TQueryResult, never>;\n\t\t}\n\t> {\n\t\treturn this._prepare(name);\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);\n\t\t});\n\t};\n}\n"],"mappings":"AAAA,SAAS,kBAAkB;AAU3B,SAAS,oBAAoB;AAG7B,SAAS,cAAc;AAehB,MAAM,mCACJ,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,EAEA,UAAkD,CAAC,sBAAsB;AACxE,WAAO,OAAO,gBAAgB,qBAAqB,MAAM;AACxD,aAAO,KAAK,SAAS,EAAE,QAAQ,iBAAiB;AAAA,IACjD,CAAC;AAAA,EACF;AACD;","names":[]}

View File

@@ -0,0 +1,863 @@
"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, {
GelSelectBase: () => GelSelectBase,
GelSelectBuilder: () => GelSelectBuilder,
GelSelectQueryBuilderBase: () => GelSelectQueryBuilderBase,
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");
var import_utils3 = require("../utils.cjs");
class GelSelectBuilder {
static [import_entity.entityKind] = "GelSelectBuilder";
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.GelViewBase)) {
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 GelSelectBase({
table: source,
fields,
isPartialSelect,
session: this.session,
dialect: this.dialect,
withList: this.withList,
distinct: this.distinct
});
}
}
class GelSelectQueryBuilderBase extends import_query_builder.TypedQueryBuilder {
static [import_entity.entityKind] = "GelSelectQueryBuilder";
_;
config;
joinsNotNullableMap;
tableName;
isPartialSelect;
session;
dialect;
cacheConfig = void 0;
usedTables = /* @__PURE__ */ new Set();
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,
config: this.config
};
this.tableName = (0, import_utils.getTableLikeName)(table);
this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
for (const item of (0, import_utils3.extractUsedTable)(table)) this.usedTables.add(item);
}
/** @internal */
getUsedTables() {
return [...this.usedTables];
}
createJoin(joinType, lateral) {
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`);
}
for (const item of (0, import_utils3.extractUsedTable)(table)) this.usedTables.add(item);
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, lateral });
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 "cross":
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", false);
/**
* Executes a `left join lateral` operation by adding subquery to the current query.
*
* A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
*
* 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-lateral}
*
* @param table the subquery to join.
* @param on the `on` clause.
*/
leftJoinLateral = this.createJoin("left", true);
/**
* 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", false);
/**
* 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", false);
/**
* Executes an `inner join lateral` operation, creating a new table by combining rows from two queries that have matching values.
*
* A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
*
* 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-lateral}
*
* @param table the subquery to join.
* @param on the `on` clause.
*/
innerJoinLateral = this.createJoin("inner", true);
/**
* 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", false);
/**
* Executes a `cross 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 all rows from each table.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#cross-join}
*
* @param table the table to join.
*
* @example
*
* ```ts
* // Select all users, each user with every pet
* const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
* .from(users)
* .crossJoin(pets)
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .crossJoin(pets)
* ```
*/
crossJoin = this.createJoin("cross", false);
/**
* Executes a `cross join lateral` operation by combining rows from two queries into a new table.
*
* A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
*
* Calling this method retrieves all rows from both main and joined queries, merging all rows from each query.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#cross-join-lateral}
*
* @param table the query to join.
*/
crossJoinLateral = this.createJoin("cross", true);
createSetOperator(type, isAll) {
return (rightSelection) => {
const rightSelect = typeof rightSelection === "function" ? rightSelection(getGelSetOperators()) : 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/gel-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/gel-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/gel-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/gel-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/gel-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/gel-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) {
const usedTables = [];
usedTables.push(...(0, import_utils3.extractUsedTable)(this.config.table));
if (this.config.joins) {
for (const it of this.config.joins) usedTables.push(...(0, import_utils3.extractUsedTable)(it.table));
}
return new Proxy(
new import_subquery.Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]),
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 GelSelectBase extends GelSelectQueryBuilderBase {
static [import_entity.entityKind] = "GelSelect";
/** @internal */
_prepare(name) {
const { session, config, dialect, joinsNotNullableMap, cacheConfig, usedTables } = 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, void 0, {
type: "select",
tables: [...usedTables]
}, cacheConfig);
query.joinsNotNullableMap = joinsNotNullableMap;
return query;
});
}
$withCache(config) {
this.cacheConfig = config === void 0 ? { config: {}, enable: true, autoInvalidate: true } : config === false ? { enable: false } : { enable: true, autoInvalidate: true, ...config };
return this;
}
/**
* 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);
}
execute = (placeholderValues) => {
return import_tracing.tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(placeholderValues);
});
};
}
(0, import_utils.applyMixins)(GelSelectBase, [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 getGelSetOperators = () => ({
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 = {
GelSelectBase,
GelSelectBuilder,
GelSelectQueryBuilderBase,
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,795 @@
import type { CacheConfig, WithCacheConfig } from "../../cache/core/types.cjs";
import { entityKind } from "../../entity.cjs";
import type { GelColumn } from "../columns/index.cjs";
import type { GelDialect } from "../dialect.cjs";
import type { GelSession } from "../session.cjs";
import type { SubqueryWithSelection } from "../subquery.cjs";
import type { GelTable } from "../table.cjs";
import { GelViewBase } 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 { CreateGelSelectFromBuilderMode, GelCreateSetOperatorFn, GelSelectConfig, GelSelectCrossJoinFn, GelSelectDynamic, GelSelectHKT, GelSelectHKTBase, GelSelectJoinFn, GelSelectPrepare, GelSelectWithout, GelSetOperatorExcludedMethods, GelSetOperatorWithResult, GetGelSetOperators, LockConfig, LockStrength, SelectedFields, SetOperatorRightSelect } from "./select.types.cjs";
export declare class GelSelectBuilder<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: GelSession | undefined;
dialect: GelDialect;
withList?: Subquery[];
distinct?: boolean | {
on: (GelColumn | 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 GelTable | Subquery | GelViewBase | SQL>(source: TFrom): CreateGelSelectFromBuilderMode<TBuilderMode, GetSelectTableName<TFrom>, TSelection extends undefined ? GetSelectTableSelection<TFrom> : TSelection, TSelection extends undefined ? 'single' : 'partial'>;
}
export declare abstract class GelSelectQueryBuilderBase<THKT extends GelSelectHKTBase, 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: 'gel';
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;
readonly config: GelSelectConfig;
};
protected config: GelSelectConfig;
protected joinsNotNullableMap: Record<string, boolean>;
private tableName;
private isPartialSelect;
protected session: GelSession | undefined;
protected dialect: GelDialect;
protected cacheConfig?: WithCacheConfig;
protected usedTables: Set<string>;
constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }: {
table: GelSelectConfig['table'];
fields: GelSelectConfig['fields'];
isPartialSelect: boolean;
session: GelSession | undefined;
dialect: GelDialect;
withList: Subquery[];
distinct: boolean | {
on: (GelColumn | 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: GelSelectJoinFn<this, TDynamic, "left", false>;
/**
* Executes a `left join lateral` operation by adding subquery to the current query.
*
* A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
*
* 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-lateral}
*
* @param table the subquery to join.
* @param on the `on` clause.
*/
leftJoinLateral: GelSelectJoinFn<this, TDynamic, "left", true>;
/**
* 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: GelSelectJoinFn<this, TDynamic, "right", false>;
/**
* 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: GelSelectJoinFn<this, TDynamic, "inner", false>;
/**
* Executes an `inner join lateral` operation, creating a new table by combining rows from two queries that have matching values.
*
* A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
*
* 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-lateral}
*
* @param table the subquery to join.
* @param on the `on` clause.
*/
innerJoinLateral: GelSelectJoinFn<this, TDynamic, "inner", true>;
/**
* 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: GelSelectJoinFn<this, TDynamic, "full", false>;
/**
* Executes a `cross 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 all rows from each table.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#cross-join}
*
* @param table the table to join.
*
* @example
*
* ```ts
* // Select all users, each user with every pet
* const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
* .from(users)
* .crossJoin(pets)
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .crossJoin(pets)
* ```
*/
crossJoin: GelSelectCrossJoinFn<this, TDynamic, false>;
/**
* Executes a `cross join lateral` operation by combining rows from two queries into a new table.
*
* A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
*
* Calling this method retrieves all rows from both main and joined queries, merging all rows from each query.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#cross-join-lateral}
*
* @param table the query to join.
*/
crossJoinLateral: GelSelectCrossJoinFn<this, TDynamic, true>;
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/gel-core'
*
* await union(
* db.select({ name: users.name }).from(users),
* db.select({ name: customers.name }).from(customers)
* );
* ```
*/
union: <TValue extends GelSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetGelSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => GelSelectWithout<this, TDynamic, GelSetOperatorExcludedMethods, 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/gel-core'
*
* await unionAll(
* db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
* );
* ```
*/
unionAll: <TValue extends GelSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetGelSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => GelSelectWithout<this, TDynamic, GelSetOperatorExcludedMethods, 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/gel-core'
*
* await intersect(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
intersect: <TValue extends GelSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetGelSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => GelSelectWithout<this, TDynamic, GelSetOperatorExcludedMethods, 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/gel-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 GelSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetGelSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => GelSelectWithout<this, TDynamic, GelSetOperatorExcludedMethods, 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/gel-core'
*
* await except(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
except: <TValue extends GelSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetGelSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => GelSelectWithout<this, TDynamic, GelSetOperatorExcludedMethods, 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/gel-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 GelSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetGelSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => GelSelectWithout<this, TDynamic, GelSetOperatorExcludedMethods, 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): GelSelectWithout<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): GelSelectWithout<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<GelColumn | SQL | SQL.Aliased>): GelSelectWithout<this, TDynamic, 'groupBy'>;
groupBy(...columns: (GelColumn | SQL | SQL.Aliased)[]): GelSelectWithout<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<GelColumn | SQL | SQL.Aliased>): GelSelectWithout<this, TDynamic, 'orderBy'>;
orderBy(...columns: (GelColumn | SQL | SQL.Aliased)[]): GelSelectWithout<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): GelSelectWithout<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): GelSelectWithout<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): GelSelectWithout<this, TDynamic, 'for'>;
toSQL(): Query;
as<TAlias extends string>(alias: TAlias): SubqueryWithSelection<this['_']['selectedFields'], TAlias>;
$dynamic(): GelSelectDynamic<this>;
}
export interface GelSelectBase<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 GelSelectQueryBuilderBase<GelSelectHKT, TTableName, TSelection, TSelectMode, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields>, QueryPromise<TResult>, SQLWrapper {
}
export declare class GelSelectBase<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 GelSelectQueryBuilderBase<GelSelectHKT, TTableName, TSelection, TSelectMode, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields> implements RunnableQuery<TResult, 'gel'>, SQLWrapper {
static readonly [entityKind]: string;
$withCache(config?: {
config?: CacheConfig;
tag?: string;
autoInvalidate?: boolean;
} | false): this;
/**
* 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): GelSelectPrepare<this>;
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/Gel-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: GelCreateSetOperatorFn;
/**
* 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/Gel-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: GelCreateSetOperatorFn;
/**
* 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/Gel-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: GelCreateSetOperatorFn;
/**
* 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/Gel-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: GelCreateSetOperatorFn;
/**
* 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/Gel-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: GelCreateSetOperatorFn;
/**
* 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/Gel-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: GelCreateSetOperatorFn;

View File

@@ -0,0 +1,795 @@
import type { CacheConfig, WithCacheConfig } from "../../cache/core/types.js";
import { entityKind } from "../../entity.js";
import type { GelColumn } from "../columns/index.js";
import type { GelDialect } from "../dialect.js";
import type { GelSession } from "../session.js";
import type { SubqueryWithSelection } from "../subquery.js";
import type { GelTable } from "../table.js";
import { GelViewBase } 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 { CreateGelSelectFromBuilderMode, GelCreateSetOperatorFn, GelSelectConfig, GelSelectCrossJoinFn, GelSelectDynamic, GelSelectHKT, GelSelectHKTBase, GelSelectJoinFn, GelSelectPrepare, GelSelectWithout, GelSetOperatorExcludedMethods, GelSetOperatorWithResult, GetGelSetOperators, LockConfig, LockStrength, SelectedFields, SetOperatorRightSelect } from "./select.types.js";
export declare class GelSelectBuilder<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: GelSession | undefined;
dialect: GelDialect;
withList?: Subquery[];
distinct?: boolean | {
on: (GelColumn | 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 GelTable | Subquery | GelViewBase | SQL>(source: TFrom): CreateGelSelectFromBuilderMode<TBuilderMode, GetSelectTableName<TFrom>, TSelection extends undefined ? GetSelectTableSelection<TFrom> : TSelection, TSelection extends undefined ? 'single' : 'partial'>;
}
export declare abstract class GelSelectQueryBuilderBase<THKT extends GelSelectHKTBase, 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: 'gel';
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;
readonly config: GelSelectConfig;
};
protected config: GelSelectConfig;
protected joinsNotNullableMap: Record<string, boolean>;
private tableName;
private isPartialSelect;
protected session: GelSession | undefined;
protected dialect: GelDialect;
protected cacheConfig?: WithCacheConfig;
protected usedTables: Set<string>;
constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }: {
table: GelSelectConfig['table'];
fields: GelSelectConfig['fields'];
isPartialSelect: boolean;
session: GelSession | undefined;
dialect: GelDialect;
withList: Subquery[];
distinct: boolean | {
on: (GelColumn | 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: GelSelectJoinFn<this, TDynamic, "left", false>;
/**
* Executes a `left join lateral` operation by adding subquery to the current query.
*
* A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
*
* 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-lateral}
*
* @param table the subquery to join.
* @param on the `on` clause.
*/
leftJoinLateral: GelSelectJoinFn<this, TDynamic, "left", true>;
/**
* 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: GelSelectJoinFn<this, TDynamic, "right", false>;
/**
* 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: GelSelectJoinFn<this, TDynamic, "inner", false>;
/**
* Executes an `inner join lateral` operation, creating a new table by combining rows from two queries that have matching values.
*
* A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
*
* 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-lateral}
*
* @param table the subquery to join.
* @param on the `on` clause.
*/
innerJoinLateral: GelSelectJoinFn<this, TDynamic, "inner", true>;
/**
* 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: GelSelectJoinFn<this, TDynamic, "full", false>;
/**
* Executes a `cross 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 all rows from each table.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#cross-join}
*
* @param table the table to join.
*
* @example
*
* ```ts
* // Select all users, each user with every pet
* const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
* .from(users)
* .crossJoin(pets)
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .crossJoin(pets)
* ```
*/
crossJoin: GelSelectCrossJoinFn<this, TDynamic, false>;
/**
* Executes a `cross join lateral` operation by combining rows from two queries into a new table.
*
* A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
*
* Calling this method retrieves all rows from both main and joined queries, merging all rows from each query.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#cross-join-lateral}
*
* @param table the query to join.
*/
crossJoinLateral: GelSelectCrossJoinFn<this, TDynamic, true>;
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/gel-core'
*
* await union(
* db.select({ name: users.name }).from(users),
* db.select({ name: customers.name }).from(customers)
* );
* ```
*/
union: <TValue extends GelSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetGelSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => GelSelectWithout<this, TDynamic, GelSetOperatorExcludedMethods, 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/gel-core'
*
* await unionAll(
* db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
* );
* ```
*/
unionAll: <TValue extends GelSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetGelSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => GelSelectWithout<this, TDynamic, GelSetOperatorExcludedMethods, 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/gel-core'
*
* await intersect(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
intersect: <TValue extends GelSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetGelSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => GelSelectWithout<this, TDynamic, GelSetOperatorExcludedMethods, 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/gel-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 GelSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetGelSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => GelSelectWithout<this, TDynamic, GelSetOperatorExcludedMethods, 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/gel-core'
*
* await except(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
except: <TValue extends GelSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetGelSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => GelSelectWithout<this, TDynamic, GelSetOperatorExcludedMethods, 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/gel-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 GelSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetGelSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => GelSelectWithout<this, TDynamic, GelSetOperatorExcludedMethods, 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): GelSelectWithout<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): GelSelectWithout<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<GelColumn | SQL | SQL.Aliased>): GelSelectWithout<this, TDynamic, 'groupBy'>;
groupBy(...columns: (GelColumn | SQL | SQL.Aliased)[]): GelSelectWithout<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<GelColumn | SQL | SQL.Aliased>): GelSelectWithout<this, TDynamic, 'orderBy'>;
orderBy(...columns: (GelColumn | SQL | SQL.Aliased)[]): GelSelectWithout<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): GelSelectWithout<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): GelSelectWithout<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): GelSelectWithout<this, TDynamic, 'for'>;
toSQL(): Query;
as<TAlias extends string>(alias: TAlias): SubqueryWithSelection<this['_']['selectedFields'], TAlias>;
$dynamic(): GelSelectDynamic<this>;
}
export interface GelSelectBase<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 GelSelectQueryBuilderBase<GelSelectHKT, TTableName, TSelection, TSelectMode, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields>, QueryPromise<TResult>, SQLWrapper {
}
export declare class GelSelectBase<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 GelSelectQueryBuilderBase<GelSelectHKT, TTableName, TSelection, TSelectMode, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields> implements RunnableQuery<TResult, 'gel'>, SQLWrapper {
static readonly [entityKind]: string;
$withCache(config?: {
config?: CacheConfig;
tag?: string;
autoInvalidate?: boolean;
} | false): this;
/**
* 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): GelSelectPrepare<this>;
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/Gel-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: GelCreateSetOperatorFn;
/**
* 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/Gel-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: GelCreateSetOperatorFn;
/**
* 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/Gel-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: GelCreateSetOperatorFn;
/**
* 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/Gel-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: GelCreateSetOperatorFn;
/**
* 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/Gel-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: GelCreateSetOperatorFn;
/**
* 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/Gel-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: GelCreateSetOperatorFn;

View File

@@ -0,0 +1,836 @@
import { entityKind, is } from "../../entity.js";
import { GelViewBase } 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";
import { extractUsedTable } from "../utils.js";
class GelSelectBuilder {
static [entityKind] = "GelSelectBuilder";
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, GelViewBase)) {
fields = source[ViewBaseConfig].selectedFields;
} else if (is(source, SQL)) {
fields = {};
} else {
fields = getTableColumns(source);
}
return new GelSelectBase({
table: source,
fields,
isPartialSelect,
session: this.session,
dialect: this.dialect,
withList: this.withList,
distinct: this.distinct
});
}
}
class GelSelectQueryBuilderBase extends TypedQueryBuilder {
static [entityKind] = "GelSelectQueryBuilder";
_;
config;
joinsNotNullableMap;
tableName;
isPartialSelect;
session;
dialect;
cacheConfig = void 0;
usedTables = /* @__PURE__ */ new Set();
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,
config: this.config
};
this.tableName = getTableLikeName(table);
this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
for (const item of extractUsedTable(table)) this.usedTables.add(item);
}
/** @internal */
getUsedTables() {
return [...this.usedTables];
}
createJoin(joinType, lateral) {
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`);
}
for (const item of extractUsedTable(table)) this.usedTables.add(item);
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, lateral });
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 "cross":
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", false);
/**
* Executes a `left join lateral` operation by adding subquery to the current query.
*
* A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
*
* 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-lateral}
*
* @param table the subquery to join.
* @param on the `on` clause.
*/
leftJoinLateral = this.createJoin("left", true);
/**
* 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", false);
/**
* 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", false);
/**
* Executes an `inner join lateral` operation, creating a new table by combining rows from two queries that have matching values.
*
* A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
*
* 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-lateral}
*
* @param table the subquery to join.
* @param on the `on` clause.
*/
innerJoinLateral = this.createJoin("inner", true);
/**
* 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", false);
/**
* Executes a `cross 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 all rows from each table.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#cross-join}
*
* @param table the table to join.
*
* @example
*
* ```ts
* // Select all users, each user with every pet
* const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
* .from(users)
* .crossJoin(pets)
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .crossJoin(pets)
* ```
*/
crossJoin = this.createJoin("cross", false);
/**
* Executes a `cross join lateral` operation by combining rows from two queries into a new table.
*
* A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
*
* Calling this method retrieves all rows from both main and joined queries, merging all rows from each query.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#cross-join-lateral}
*
* @param table the query to join.
*/
crossJoinLateral = this.createJoin("cross", true);
createSetOperator(type, isAll) {
return (rightSelection) => {
const rightSelect = typeof rightSelection === "function" ? rightSelection(getGelSetOperators()) : 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/gel-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/gel-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/gel-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/gel-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/gel-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/gel-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) {
const usedTables = [];
usedTables.push(...extractUsedTable(this.config.table));
if (this.config.joins) {
for (const it of this.config.joins) usedTables.push(...extractUsedTable(it.table));
}
return new Proxy(
new Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]),
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 GelSelectBase extends GelSelectQueryBuilderBase {
static [entityKind] = "GelSelect";
/** @internal */
_prepare(name) {
const { session, config, dialect, joinsNotNullableMap, cacheConfig, usedTables } = 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, void 0, {
type: "select",
tables: [...usedTables]
}, cacheConfig);
query.joinsNotNullableMap = joinsNotNullableMap;
return query;
});
}
$withCache(config) {
this.cacheConfig = config === void 0 ? { config: {}, enable: true, autoInvalidate: true } : config === false ? { enable: false } : { enable: true, autoInvalidate: true, ...config };
return this;
}
/**
* 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);
}
execute = (placeholderValues) => {
return tracer.startActiveSpan("drizzle.operation", () => {
return this._prepare().execute(placeholderValues);
});
};
}
applyMixins(GelSelectBase, [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 getGelSetOperators = () => ({
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 {
GelSelectBase,
GelSelectBuilder,
GelSelectQueryBuilderBase,
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,139 @@
import type { GelColumn } from "../columns/index.cjs";
import type { GelTable, GelTableWithColumns } from "../table.cjs";
import type { GelViewBase } from "../view-base.cjs";
import type { GelViewWithSelection } from "../view.cjs";
import type { SelectedFields as SelectedFieldsBase, SelectedFieldsFlat as SelectedFieldsFlatBase, SelectedFieldsOrdered as SelectedFieldsOrderedBase } from "../../operations.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 { GelPreparedQuery, PreparedQueryConfig } from "../session.cjs";
import type { GelSelectBase, GelSelectQueryBuilderBase } from "./select.cjs";
export interface GelSelectJoinConfig {
on: SQL | undefined;
table: GelTable | Subquery | GelViewBase | SQL;
alias: string | undefined;
joinType: JoinType;
lateral?: boolean;
}
export type BuildAliasTable<TTable extends GelTable | View, TAlias extends string> = TTable extends Table ? GelTableWithColumns<UpdateTableConfig<TTable['_']['config'], {
name: TAlias;
columns: MapColumnsToTableAlias<TTable['_']['columns'], TAlias, 'gel'>;
}>> : TTable extends View ? GelViewWithSelection<TAlias, TTable['_']['existing'], MapColumnsToTableAlias<TTable['_']['selectedFields'], TAlias, 'gel'>> : never;
export interface GelSelectConfig {
withList?: Subquery[];
fields: Record<string, unknown>;
fieldsFlat?: SelectedFieldsOrdered;
where?: SQL;
having?: SQL;
table: GelTable | Subquery | GelViewBase | SQL;
limit?: number | Placeholder;
offset?: number | Placeholder;
joins?: GelSelectJoinConfig[];
orderBy?: (GelColumn | SQL | SQL.Aliased)[];
groupBy?: (GelColumn | SQL | SQL.Aliased)[];
lockingClause?: {
strength: LockStrength;
config: LockConfig;
};
distinct?: boolean | {
on: (GelColumn | SQLWrapper)[];
};
setOperators: {
rightSelect: TypedQueryBuilder<any, any>;
type: SetOperator;
isAll: boolean;
orderBy?: (GelColumn | SQL | SQL.Aliased)[];
limit?: number | Placeholder;
offset?: number | Placeholder;
}[];
}
export type GelSelectJoin<T extends AnyGelSelectQueryBuilder, TDynamic extends boolean, TJoinType extends JoinType, TJoinedTable extends GelTable | Subquery | GelViewBase | SQL, TJoinedName extends GetSelectTableName<TJoinedTable> = GetSelectTableName<TJoinedTable>> = T extends any ? GelSelectWithout<GelSelectKind<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 GelSelectJoinFn<T extends AnyGelSelectQueryBuilder, TDynamic extends boolean, TJoinType extends JoinType, TIsLateral extends boolean> = <TJoinedTable extends (TIsLateral extends true ? Subquery | SQL : GelTable | Subquery | GelViewBase | SQL), TJoinedName extends GetSelectTableName<TJoinedTable> = GetSelectTableName<TJoinedTable>>(table: TJoinedTable, on: ((aliases: T['_']['selection']) => SQL | undefined) | SQL | undefined) => GelSelectJoin<T, TDynamic, TJoinType, TJoinedTable, TJoinedName>;
export type GelSelectCrossJoinFn<T extends AnyGelSelectQueryBuilder, TDynamic extends boolean, TIsLateral extends boolean> = <TJoinedTable extends (TIsLateral extends true ? Subquery | SQL : GelTable | Subquery | GelViewBase | SQL), TJoinedName extends GetSelectTableName<TJoinedTable> = GetSelectTableName<TJoinedTable>>(table: TJoinedTable) => GelSelectJoin<T, TDynamic, 'cross', TJoinedTable, TJoinedName>;
export type SelectedFieldsFlat = SelectedFieldsFlatBase<GelColumn>;
export type SelectedFields = SelectedFieldsBase<GelColumn, GelTable>;
export type SelectedFieldsOrdered = SelectedFieldsOrderedBase<GelColumn>;
export type LockStrength = 'update' | 'no key update' | 'share' | 'key share';
export type LockConfig = {
of?: ValueOrArray<GelTable>;
} & ({
noWait: true;
skipLocked?: undefined;
} | {
noWait?: undefined;
skipLocked: true;
} | {
noWait?: undefined;
skipLocked?: undefined;
});
export interface GelSelectHKTBase {
tableName: string | undefined;
selection: unknown;
selectMode: SelectMode;
nullabilityMap: unknown;
dynamic: boolean;
excludedMethods: string;
result: unknown;
selectedFields: unknown;
_type: unknown;
}
export type GelSelectKind<T extends GelSelectHKTBase, 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 GelSelectQueryBuilderHKT extends GelSelectHKTBase {
_type: GelSelectQueryBuilderBase<GelSelectQueryBuilderHKT, 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 GelSelectHKT extends GelSelectHKTBase {
_type: GelSelectBase<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 CreateGelSelectFromBuilderMode<TBuilderMode extends 'db' | 'qb', TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode> = TBuilderMode extends 'db' ? GelSelectBase<TTableName, TSelection, TSelectMode> : GelSelectQueryBuilderBase<GelSelectQueryBuilderHKT, TTableName, TSelection, TSelectMode>;
export type GelSetOperatorExcludedMethods = 'leftJoin' | 'rightJoin' | 'innerJoin' | 'fullJoin' | 'where' | 'having' | 'groupBy' | 'for';
export type GelSelectWithout<T extends AnyGelSelectQueryBuilder, TDynamic extends boolean, K extends keyof T & string, TResetExcluded extends boolean = false> = TDynamic extends true ? T : Omit<GelSelectKind<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 GelSelectPrepare<T extends AnyGelSelect> = GelPreparedQuery<PreparedQueryConfig & {
execute: T['_']['result'];
}>;
export type GelSelectDynamic<T extends AnyGelSelectQueryBuilder> = GelSelectKind<T['_']['hkt'], T['_']['tableName'], T['_']['selection'], T['_']['selectMode'], T['_']['nullabilityMap'], true, never, T['_']['result'], T['_']['selectedFields']>;
export type GelSelectQueryBuilder<THKT extends GelSelectHKTBase = GelSelectQueryBuilderHKT, 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> = GelSelectQueryBuilderBase<THKT, TTableName, TSelection, TSelectMode, TNullabilityMap, true, never, TResult, TSelectedFields>;
export type AnyGelSelectQueryBuilder = GelSelectQueryBuilderBase<any, any, any, any, any, any, any, any, any>;
export type AnyGelSetOperatorInterface = GelSetOperatorInterface<any, any, any, any, any, any, any, any>;
export interface GelSetOperatorInterface<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: GelSelectHKT;
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 GelSetOperatorWithResult<TResult extends any[]> = GelSetOperatorInterface<any, any, any, any, any, any, TResult, any>;
export type GelSelect<TTableName extends string | undefined = string | undefined, TSelection extends ColumnsSelection = Record<string, any>, TSelectMode extends SelectMode = SelectMode, TNullabilityMap extends Record<string, JoinNullability> = Record<string, JoinNullability>> = GelSelectBase<TTableName, TSelection, TSelectMode, TNullabilityMap, true, never>;
export type AnyGelSelect = GelSelectBase<any, any, any, any, any, any, any, any>;
export type GelSetOperator<TTableName extends string | undefined = string | undefined, TSelection extends ColumnsSelection = Record<string, any>, TSelectMode extends SelectMode = SelectMode, TNullabilityMap extends Record<string, JoinNullability> = Record<string, JoinNullability>> = GelSelectBase<TTableName, TSelection, TSelectMode, TNullabilityMap, true, GelSetOperatorExcludedMethods>;
export type SetOperatorRightSelect<TValue extends GelSetOperatorWithResult<TResult>, TResult extends any[]> = TValue extends GelSetOperatorInterface<any, any, any, any, any, any, infer TValueResult, any> ? ValidateShape<TValueResult[number], TResult[number], TypedQueryBuilder<any, TValueResult>> : TValue;
export type SetOperatorRestSelect<TValue extends readonly GelSetOperatorWithResult<TResult>[], TResult extends any[]> = TValue extends [infer First, ...infer Rest] ? First extends GelSetOperatorInterface<any, any, any, any, any, any, infer TValueResult, any> ? Rest extends AnyGelSetOperatorInterface[] ? [
ValidateShape<TValueResult[number], TResult[number], TypedQueryBuilder<any, TValueResult>>,
...SetOperatorRestSelect<Rest, TResult>
] : ValidateShape<TValueResult[number], TResult[number], TypedQueryBuilder<any, TValueResult>[]> : never : TValue;
export type GelCreateSetOperatorFn = <TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TValue extends GelSetOperatorWithResult<TResult>, TRest extends GelSetOperatorWithResult<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: GelSetOperatorInterface<TTableName, TSelection, TSelectMode, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields>, rightSelect: SetOperatorRightSelect<TValue, TResult>, ...restSelects: SetOperatorRestSelect<TRest, TResult>) => GelSelectWithout<GelSelectBase<TTableName, TSelection, TSelectMode, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields>, false, GelSetOperatorExcludedMethods, true>;
export type GetGelSetOperators = {
union: GelCreateSetOperatorFn;
intersect: GelCreateSetOperatorFn;
except: GelCreateSetOperatorFn;
unionAll: GelCreateSetOperatorFn;
intersectAll: GelCreateSetOperatorFn;
exceptAll: GelCreateSetOperatorFn;
};

View File

@@ -0,0 +1,139 @@
import type { GelColumn } from "../columns/index.js";
import type { GelTable, GelTableWithColumns } from "../table.js";
import type { GelViewBase } from "../view-base.js";
import type { GelViewWithSelection } from "../view.js";
import type { SelectedFields as SelectedFieldsBase, SelectedFieldsFlat as SelectedFieldsFlatBase, SelectedFieldsOrdered as SelectedFieldsOrderedBase } from "../../operations.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 { GelPreparedQuery, PreparedQueryConfig } from "../session.js";
import type { GelSelectBase, GelSelectQueryBuilderBase } from "./select.js";
export interface GelSelectJoinConfig {
on: SQL | undefined;
table: GelTable | Subquery | GelViewBase | SQL;
alias: string | undefined;
joinType: JoinType;
lateral?: boolean;
}
export type BuildAliasTable<TTable extends GelTable | View, TAlias extends string> = TTable extends Table ? GelTableWithColumns<UpdateTableConfig<TTable['_']['config'], {
name: TAlias;
columns: MapColumnsToTableAlias<TTable['_']['columns'], TAlias, 'gel'>;
}>> : TTable extends View ? GelViewWithSelection<TAlias, TTable['_']['existing'], MapColumnsToTableAlias<TTable['_']['selectedFields'], TAlias, 'gel'>> : never;
export interface GelSelectConfig {
withList?: Subquery[];
fields: Record<string, unknown>;
fieldsFlat?: SelectedFieldsOrdered;
where?: SQL;
having?: SQL;
table: GelTable | Subquery | GelViewBase | SQL;
limit?: number | Placeholder;
offset?: number | Placeholder;
joins?: GelSelectJoinConfig[];
orderBy?: (GelColumn | SQL | SQL.Aliased)[];
groupBy?: (GelColumn | SQL | SQL.Aliased)[];
lockingClause?: {
strength: LockStrength;
config: LockConfig;
};
distinct?: boolean | {
on: (GelColumn | SQLWrapper)[];
};
setOperators: {
rightSelect: TypedQueryBuilder<any, any>;
type: SetOperator;
isAll: boolean;
orderBy?: (GelColumn | SQL | SQL.Aliased)[];
limit?: number | Placeholder;
offset?: number | Placeholder;
}[];
}
export type GelSelectJoin<T extends AnyGelSelectQueryBuilder, TDynamic extends boolean, TJoinType extends JoinType, TJoinedTable extends GelTable | Subquery | GelViewBase | SQL, TJoinedName extends GetSelectTableName<TJoinedTable> = GetSelectTableName<TJoinedTable>> = T extends any ? GelSelectWithout<GelSelectKind<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 GelSelectJoinFn<T extends AnyGelSelectQueryBuilder, TDynamic extends boolean, TJoinType extends JoinType, TIsLateral extends boolean> = <TJoinedTable extends (TIsLateral extends true ? Subquery | SQL : GelTable | Subquery | GelViewBase | SQL), TJoinedName extends GetSelectTableName<TJoinedTable> = GetSelectTableName<TJoinedTable>>(table: TJoinedTable, on: ((aliases: T['_']['selection']) => SQL | undefined) | SQL | undefined) => GelSelectJoin<T, TDynamic, TJoinType, TJoinedTable, TJoinedName>;
export type GelSelectCrossJoinFn<T extends AnyGelSelectQueryBuilder, TDynamic extends boolean, TIsLateral extends boolean> = <TJoinedTable extends (TIsLateral extends true ? Subquery | SQL : GelTable | Subquery | GelViewBase | SQL), TJoinedName extends GetSelectTableName<TJoinedTable> = GetSelectTableName<TJoinedTable>>(table: TJoinedTable) => GelSelectJoin<T, TDynamic, 'cross', TJoinedTable, TJoinedName>;
export type SelectedFieldsFlat = SelectedFieldsFlatBase<GelColumn>;
export type SelectedFields = SelectedFieldsBase<GelColumn, GelTable>;
export type SelectedFieldsOrdered = SelectedFieldsOrderedBase<GelColumn>;
export type LockStrength = 'update' | 'no key update' | 'share' | 'key share';
export type LockConfig = {
of?: ValueOrArray<GelTable>;
} & ({
noWait: true;
skipLocked?: undefined;
} | {
noWait?: undefined;
skipLocked: true;
} | {
noWait?: undefined;
skipLocked?: undefined;
});
export interface GelSelectHKTBase {
tableName: string | undefined;
selection: unknown;
selectMode: SelectMode;
nullabilityMap: unknown;
dynamic: boolean;
excludedMethods: string;
result: unknown;
selectedFields: unknown;
_type: unknown;
}
export type GelSelectKind<T extends GelSelectHKTBase, 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 GelSelectQueryBuilderHKT extends GelSelectHKTBase {
_type: GelSelectQueryBuilderBase<GelSelectQueryBuilderHKT, 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 GelSelectHKT extends GelSelectHKTBase {
_type: GelSelectBase<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 CreateGelSelectFromBuilderMode<TBuilderMode extends 'db' | 'qb', TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode> = TBuilderMode extends 'db' ? GelSelectBase<TTableName, TSelection, TSelectMode> : GelSelectQueryBuilderBase<GelSelectQueryBuilderHKT, TTableName, TSelection, TSelectMode>;
export type GelSetOperatorExcludedMethods = 'leftJoin' | 'rightJoin' | 'innerJoin' | 'fullJoin' | 'where' | 'having' | 'groupBy' | 'for';
export type GelSelectWithout<T extends AnyGelSelectQueryBuilder, TDynamic extends boolean, K extends keyof T & string, TResetExcluded extends boolean = false> = TDynamic extends true ? T : Omit<GelSelectKind<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 GelSelectPrepare<T extends AnyGelSelect> = GelPreparedQuery<PreparedQueryConfig & {
execute: T['_']['result'];
}>;
export type GelSelectDynamic<T extends AnyGelSelectQueryBuilder> = GelSelectKind<T['_']['hkt'], T['_']['tableName'], T['_']['selection'], T['_']['selectMode'], T['_']['nullabilityMap'], true, never, T['_']['result'], T['_']['selectedFields']>;
export type GelSelectQueryBuilder<THKT extends GelSelectHKTBase = GelSelectQueryBuilderHKT, 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> = GelSelectQueryBuilderBase<THKT, TTableName, TSelection, TSelectMode, TNullabilityMap, true, never, TResult, TSelectedFields>;
export type AnyGelSelectQueryBuilder = GelSelectQueryBuilderBase<any, any, any, any, any, any, any, any, any>;
export type AnyGelSetOperatorInterface = GelSetOperatorInterface<any, any, any, any, any, any, any, any>;
export interface GelSetOperatorInterface<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: GelSelectHKT;
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 GelSetOperatorWithResult<TResult extends any[]> = GelSetOperatorInterface<any, any, any, any, any, any, TResult, any>;
export type GelSelect<TTableName extends string | undefined = string | undefined, TSelection extends ColumnsSelection = Record<string, any>, TSelectMode extends SelectMode = SelectMode, TNullabilityMap extends Record<string, JoinNullability> = Record<string, JoinNullability>> = GelSelectBase<TTableName, TSelection, TSelectMode, TNullabilityMap, true, never>;
export type AnyGelSelect = GelSelectBase<any, any, any, any, any, any, any, any>;
export type GelSetOperator<TTableName extends string | undefined = string | undefined, TSelection extends ColumnsSelection = Record<string, any>, TSelectMode extends SelectMode = SelectMode, TNullabilityMap extends Record<string, JoinNullability> = Record<string, JoinNullability>> = GelSelectBase<TTableName, TSelection, TSelectMode, TNullabilityMap, true, GelSetOperatorExcludedMethods>;
export type SetOperatorRightSelect<TValue extends GelSetOperatorWithResult<TResult>, TResult extends any[]> = TValue extends GelSetOperatorInterface<any, any, any, any, any, any, infer TValueResult, any> ? ValidateShape<TValueResult[number], TResult[number], TypedQueryBuilder<any, TValueResult>> : TValue;
export type SetOperatorRestSelect<TValue extends readonly GelSetOperatorWithResult<TResult>[], TResult extends any[]> = TValue extends [infer First, ...infer Rest] ? First extends GelSetOperatorInterface<any, any, any, any, any, any, infer TValueResult, any> ? Rest extends AnyGelSetOperatorInterface[] ? [
ValidateShape<TValueResult[number], TResult[number], TypedQueryBuilder<any, TValueResult>>,
...SetOperatorRestSelect<Rest, TResult>
] : ValidateShape<TValueResult[number], TResult[number], TypedQueryBuilder<any, TValueResult>[]> : never : TValue;
export type GelCreateSetOperatorFn = <TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TValue extends GelSetOperatorWithResult<TResult>, TRest extends GelSetOperatorWithResult<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: GelSetOperatorInterface<TTableName, TSelection, TSelectMode, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields>, rightSelect: SetOperatorRightSelect<TValue, TResult>, ...restSelects: SetOperatorRestSelect<TRest, TResult>) => GelSelectWithout<GelSelectBase<TTableName, TSelection, TSelectMode, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields>, false, GelSetOperatorExcludedMethods, true>;
export type GetGelSetOperators = {
union: GelCreateSetOperatorFn;
intersect: GelCreateSetOperatorFn;
except: GelCreateSetOperatorFn;
unionAll: GelCreateSetOperatorFn;
intersectAll: GelCreateSetOperatorFn;
exceptAll: GelCreateSetOperatorFn;
};

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,230 @@
"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, {
GelUpdateBase: () => GelUpdateBase,
GelUpdateBuilder: () => GelUpdateBuilder
});
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");
var import_utils2 = require("../utils.cjs");
class GelUpdateBuilder {
constructor(table, session, dialect, withList) {
this.table = table;
this.session = session;
this.dialect = dialect;
this.withList = withList;
}
static [import_entity.entityKind] = "GelUpdateBuilder";
authToken;
setToken(token) {
this.authToken = token;
return this;
}
set(values) {
return new GelUpdateBase(
this.table,
(0, import_utils.mapUpdateSet)(this.table, values),
this.session,
this.dialect,
this.withList
);
}
}
class GelUpdateBase 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] = "GelUpdate";
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.GelTable)) {
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, void 0, {
type: "update",
tables: (0, import_utils2.extractUsedTable)(this.config.table)
});
query.joinsNotNullableMap = this.joinsNotNullableMap;
return query;
}
prepare(name) {
return this._prepare(name);
}
execute = (placeholderValues) => {
return this._prepare().execute(placeholderValues);
};
$dynamic() {
return this;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
GelUpdateBase,
GelUpdateBuilder
});
//# sourceMappingURL=update.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,166 @@
import type { GetColumnData } from "../../column.cjs";
import { entityKind } from "../../entity.cjs";
import type { GelDialect } from "../dialect.cjs";
import type { GelPreparedQuery, GelQueryResultHKT, GelQueryResultKind, GelSession, PreparedQueryConfig } from "../session.cjs";
import { GelTable } 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 { GelColumn } from "../columns/common.cjs";
import type { GelViewBase } from "../view-base.cjs";
import type { GelSelectJoinConfig, SelectedFields, SelectedFieldsOrdered } from "./select.types.cjs";
export interface GelUpdateConfig {
where?: SQL | undefined;
set: UpdateSet;
table: GelTable;
from?: GelTable | Subquery | GelViewBase | SQL;
joins: GelSelectJoinConfig[];
returning?: SelectedFieldsOrdered;
withList?: Subquery[];
}
export type GelUpdateSetSource<TTable extends GelTable> = {
[Key in keyof TTable['$inferInsert']]?: GetColumnData<TTable['_']['columns'][Key]> | SQL | GelColumn;
} & {};
export declare class GelUpdateBuilder<TTable extends GelTable, TQueryResult extends GelQueryResultHKT> {
private table;
private session;
private dialect;
private withList?;
static readonly [entityKind]: string;
readonly _: {
readonly table: TTable;
};
constructor(table: TTable, session: GelSession, dialect: GelDialect, withList?: Subquery[] | undefined);
private authToken?;
setToken(token: NeonAuthToken): this;
set(values: GelUpdateSetSource<TTable>): GelUpdateWithout<GelUpdateBase<TTable, TQueryResult>, false, 'leftJoin' | 'rightJoin' | 'innerJoin' | 'fullJoin'>;
}
export type GelUpdateWithout<T extends AnyGelUpdate, TDynamic extends boolean, K extends keyof T & string> = TDynamic extends true ? T : Omit<GelUpdateBase<T['_']['table'], T['_']['queryResult'], T['_']['from'], T['_']['returning'], T['_']['nullabilityMap'], T['_']['joins'], TDynamic, T['_']['excludedMethods'] | K>, T['_']['excludedMethods'] | K>;
export type GelUpdateWithJoins<T extends AnyGelUpdate, TDynamic extends boolean, TFrom extends GelTable | Subquery | GelViewBase | SQL> = TDynamic extends true ? T : Omit<GelUpdateBase<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 GelUpdateJoinFn<T extends AnyGelUpdate, TDynamic extends boolean, TJoinType extends JoinType> = <TJoinedTable extends GelTable | Subquery | GelViewBase | SQL>(table: TJoinedTable, on: ((updateTable: T['_']['table']['_']['columns'], from: T['_']['from'] extends GelTable ? T['_']['from']['_']['columns'] : T['_']['from'] extends Subquery | GelViewBase ? T['_']['from']['_']['selectedFields'] : never) => SQL | undefined) | SQL | undefined) => GelUpdateJoin<T, TDynamic, TJoinType, TJoinedTable>;
export type GelUpdateJoin<T extends AnyGelUpdate, TDynamic extends boolean, TJoinType extends JoinType, TJoinedTable extends GelTable | Subquery | GelViewBase | SQL> = TDynamic extends true ? T : GelUpdateBase<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: GelTable | Subquery | GelViewBase | SQL;
};
type AccumulateToResult<T extends AnyGelUpdate, 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 GelUpdateReturningAll<T extends AnyGelUpdate, TDynamic extends boolean> = GelUpdateWithout<GelUpdateBase<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 GelUpdateReturning<T extends AnyGelUpdate, TDynamic extends boolean, TSelectedFields extends SelectedFields> = GelUpdateWithout<GelUpdateBase<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 GelUpdatePrepare<T extends AnyGelUpdate> = GelPreparedQuery<PreparedQueryConfig & {
execute: T['_']['returning'] extends undefined ? GelQueryResultKind<T['_']['queryResult'], never> : T['_']['returning'][];
}>;
export type GelUpdateDynamic<T extends AnyGelUpdate> = GelUpdate<T['_']['table'], T['_']['queryResult'], T['_']['from'], T['_']['returning'], T['_']['nullabilityMap']>;
export type GelUpdate<TTable extends GelTable = GelTable, TQueryResult extends GelQueryResultHKT = GelQueryResultHKT, TFrom extends GelTable | Subquery | GelViewBase | 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[] = []> = GelUpdateBase<TTable, TQueryResult, TFrom, TReturning, TNullabilityMap, TJoins, true, never>;
export type AnyGelUpdate = GelUpdateBase<any, any, any, any, any, any, any, any>;
export interface GelUpdateBase<TTable extends GelTable, TQueryResult extends GelQueryResultHKT, TFrom extends GelTable | Subquery | GelViewBase | 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 ? GelQueryResultKind<TQueryResult, never> : TReturning[]>, RunnableQuery<TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[], 'gel'>, SQLWrapper {
readonly _: {
readonly dialect: 'gel';
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 ? GelQueryResultKind<TQueryResult, never> : TReturning[];
};
}
export declare class GelUpdateBase<TTable extends GelTable, TQueryResult extends GelQueryResultHKT, TFrom extends GelTable | Subquery | GelViewBase | 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 ? GelQueryResultKind<TQueryResult, never> : TReturning[]> implements RunnableQuery<TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[], 'gel'>, SQLWrapper {
private session;
private dialect;
static readonly [entityKind]: string;
private config;
private tableName;
private joinsNotNullableMap;
constructor(table: TTable, set: UpdateSet, session: GelSession, dialect: GelDialect, withList?: Subquery[]);
from<TFrom extends GelTable | Subquery | GelViewBase | SQL>(source: TFrom): GelUpdateWithJoins<this, TDynamic, TFrom>;
private getTableLikeFields;
private createJoin;
leftJoin: GelUpdateJoinFn<this, TDynamic, "left">;
rightJoin: GelUpdateJoinFn<this, TDynamic, "right">;
innerJoin: GelUpdateJoinFn<this, TDynamic, "inner">;
fullJoin: GelUpdateJoinFn<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): GelUpdateWithout<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(): GelUpdateReturningAll<this, TDynamic>;
returning<TSelectedFields extends SelectedFields>(fields: TSelectedFields): GelUpdateReturning<this, TDynamic, TSelectedFields>;
toSQL(): Query;
prepare(name: string): GelUpdatePrepare<this>;
execute: ReturnType<this['prepare']>['execute'];
$dynamic(): GelUpdateDynamic<this>;
}
export {};

View File

@@ -0,0 +1,166 @@
import type { GetColumnData } from "../../column.js";
import { entityKind } from "../../entity.js";
import type { GelDialect } from "../dialect.js";
import type { GelPreparedQuery, GelQueryResultHKT, GelQueryResultKind, GelSession, PreparedQueryConfig } from "../session.js";
import { GelTable } 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 { GelColumn } from "../columns/common.js";
import type { GelViewBase } from "../view-base.js";
import type { GelSelectJoinConfig, SelectedFields, SelectedFieldsOrdered } from "./select.types.js";
export interface GelUpdateConfig {
where?: SQL | undefined;
set: UpdateSet;
table: GelTable;
from?: GelTable | Subquery | GelViewBase | SQL;
joins: GelSelectJoinConfig[];
returning?: SelectedFieldsOrdered;
withList?: Subquery[];
}
export type GelUpdateSetSource<TTable extends GelTable> = {
[Key in keyof TTable['$inferInsert']]?: GetColumnData<TTable['_']['columns'][Key]> | SQL | GelColumn;
} & {};
export declare class GelUpdateBuilder<TTable extends GelTable, TQueryResult extends GelQueryResultHKT> {
private table;
private session;
private dialect;
private withList?;
static readonly [entityKind]: string;
readonly _: {
readonly table: TTable;
};
constructor(table: TTable, session: GelSession, dialect: GelDialect, withList?: Subquery[] | undefined);
private authToken?;
setToken(token: NeonAuthToken): this;
set(values: GelUpdateSetSource<TTable>): GelUpdateWithout<GelUpdateBase<TTable, TQueryResult>, false, 'leftJoin' | 'rightJoin' | 'innerJoin' | 'fullJoin'>;
}
export type GelUpdateWithout<T extends AnyGelUpdate, TDynamic extends boolean, K extends keyof T & string> = TDynamic extends true ? T : Omit<GelUpdateBase<T['_']['table'], T['_']['queryResult'], T['_']['from'], T['_']['returning'], T['_']['nullabilityMap'], T['_']['joins'], TDynamic, T['_']['excludedMethods'] | K>, T['_']['excludedMethods'] | K>;
export type GelUpdateWithJoins<T extends AnyGelUpdate, TDynamic extends boolean, TFrom extends GelTable | Subquery | GelViewBase | SQL> = TDynamic extends true ? T : Omit<GelUpdateBase<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 GelUpdateJoinFn<T extends AnyGelUpdate, TDynamic extends boolean, TJoinType extends JoinType> = <TJoinedTable extends GelTable | Subquery | GelViewBase | SQL>(table: TJoinedTable, on: ((updateTable: T['_']['table']['_']['columns'], from: T['_']['from'] extends GelTable ? T['_']['from']['_']['columns'] : T['_']['from'] extends Subquery | GelViewBase ? T['_']['from']['_']['selectedFields'] : never) => SQL | undefined) | SQL | undefined) => GelUpdateJoin<T, TDynamic, TJoinType, TJoinedTable>;
export type GelUpdateJoin<T extends AnyGelUpdate, TDynamic extends boolean, TJoinType extends JoinType, TJoinedTable extends GelTable | Subquery | GelViewBase | SQL> = TDynamic extends true ? T : GelUpdateBase<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: GelTable | Subquery | GelViewBase | SQL;
};
type AccumulateToResult<T extends AnyGelUpdate, 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 GelUpdateReturningAll<T extends AnyGelUpdate, TDynamic extends boolean> = GelUpdateWithout<GelUpdateBase<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 GelUpdateReturning<T extends AnyGelUpdate, TDynamic extends boolean, TSelectedFields extends SelectedFields> = GelUpdateWithout<GelUpdateBase<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 GelUpdatePrepare<T extends AnyGelUpdate> = GelPreparedQuery<PreparedQueryConfig & {
execute: T['_']['returning'] extends undefined ? GelQueryResultKind<T['_']['queryResult'], never> : T['_']['returning'][];
}>;
export type GelUpdateDynamic<T extends AnyGelUpdate> = GelUpdate<T['_']['table'], T['_']['queryResult'], T['_']['from'], T['_']['returning'], T['_']['nullabilityMap']>;
export type GelUpdate<TTable extends GelTable = GelTable, TQueryResult extends GelQueryResultHKT = GelQueryResultHKT, TFrom extends GelTable | Subquery | GelViewBase | 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[] = []> = GelUpdateBase<TTable, TQueryResult, TFrom, TReturning, TNullabilityMap, TJoins, true, never>;
export type AnyGelUpdate = GelUpdateBase<any, any, any, any, any, any, any, any>;
export interface GelUpdateBase<TTable extends GelTable, TQueryResult extends GelQueryResultHKT, TFrom extends GelTable | Subquery | GelViewBase | 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 ? GelQueryResultKind<TQueryResult, never> : TReturning[]>, RunnableQuery<TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[], 'gel'>, SQLWrapper {
readonly _: {
readonly dialect: 'gel';
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 ? GelQueryResultKind<TQueryResult, never> : TReturning[];
};
}
export declare class GelUpdateBase<TTable extends GelTable, TQueryResult extends GelQueryResultHKT, TFrom extends GelTable | Subquery | GelViewBase | 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 ? GelQueryResultKind<TQueryResult, never> : TReturning[]> implements RunnableQuery<TReturning extends undefined ? GelQueryResultKind<TQueryResult, never> : TReturning[], 'gel'>, SQLWrapper {
private session;
private dialect;
static readonly [entityKind]: string;
private config;
private tableName;
private joinsNotNullableMap;
constructor(table: TTable, set: UpdateSet, session: GelSession, dialect: GelDialect, withList?: Subquery[]);
from<TFrom extends GelTable | Subquery | GelViewBase | SQL>(source: TFrom): GelUpdateWithJoins<this, TDynamic, TFrom>;
private getTableLikeFields;
private createJoin;
leftJoin: GelUpdateJoinFn<this, TDynamic, "left">;
rightJoin: GelUpdateJoinFn<this, TDynamic, "right">;
innerJoin: GelUpdateJoinFn<this, TDynamic, "inner">;
fullJoin: GelUpdateJoinFn<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): GelUpdateWithout<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(): GelUpdateReturningAll<this, TDynamic>;
returning<TSelectedFields extends SelectedFields>(fields: TSelectedFields): GelUpdateReturning<this, TDynamic, TSelectedFields>;
toSQL(): Query;
prepare(name: string): GelUpdatePrepare<this>;
execute: ReturnType<this['prepare']>['execute'];
$dynamic(): GelUpdateDynamic<this>;
}
export {};

View File

@@ -0,0 +1,209 @@
import { entityKind, is } from "../../entity.js";
import { GelTable } 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";
import { extractUsedTable } from "../utils.js";
class GelUpdateBuilder {
constructor(table, session, dialect, withList) {
this.table = table;
this.session = session;
this.dialect = dialect;
this.withList = withList;
}
static [entityKind] = "GelUpdateBuilder";
authToken;
setToken(token) {
this.authToken = token;
return this;
}
set(values) {
return new GelUpdateBase(
this.table,
mapUpdateSet(this.table, values),
this.session,
this.dialect,
this.withList
);
}
}
class GelUpdateBase 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] = "GelUpdate";
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, GelTable)) {
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, void 0, {
type: "update",
tables: extractUsedTable(this.config.table)
});
query.joinsNotNullableMap = this.joinsNotNullableMap;
return query;
}
prepare(name) {
return this._prepare(name);
}
execute = (placeholderValues) => {
return this._prepare().execute(placeholderValues);
};
$dynamic() {
return this;
}
}
export {
GelUpdateBase,
GelUpdateBuilder
};
//# sourceMappingURL=update.js.map

File diff suppressed because one or more lines are too long