Initial commit

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

View File

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

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/mysql-core/query-builders/count.ts"],"sourcesContent":["import { entityKind } from '~/entity.ts';\nimport { SQL, sql, type SQLWrapper } from '~/sql/sql.ts';\nimport type { MySqlSession } from '../session.ts';\nimport type { MySqlTable } from '../table.ts';\nimport type { MySqlViewBase } from '../view-base.ts';\n\nexport class MySqlCountBuilder<\n\tTSession extends MySqlSession<any, any, any>,\n> extends SQL<number> implements Promise<number>, SQLWrapper {\n\tprivate sql: SQL<number>;\n\n\tstatic override readonly [entityKind] = 'MySqlCountBuilder';\n\t[Symbol.toStringTag] = 'MySqlCountBuilder';\n\n\tprivate session: TSession;\n\n\tprivate static buildEmbeddedCount(\n\t\tsource: MySqlTable | MySqlViewBase | 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: MySqlTable | MySqlViewBase | 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: MySqlTable | MySqlViewBase | SQL | SQLWrapper;\n\t\t\tfilters?: SQL<unknown>;\n\t\t\tsession: TSession;\n\t\t},\n\t) {\n\t\tsuper(MySqlCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);\n\n\t\tthis.mapWith(Number);\n\n\t\tthis.session = params.session;\n\n\t\tthis.sql = MySqlCountBuilder.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) => never | PromiseLike<never>) | null | undefined,\n\t): Promise<number> {\n\t\treturn this.then(undefined, onRejected);\n\t}\n\n\tfinally(onFinally?: (() => void) | null | undefined): Promise<number> {\n\t\treturn this.then(\n\t\t\t(value) => {\n\t\t\t\tonFinally?.();\n\t\t\t\treturn value;\n\t\t\t},\n\t\t\t(reason) => {\n\t\t\t\tonFinally?.();\n\t\t\t\tthrow reason;\n\t\t\t},\n\t\t);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA2B;AAC3B,iBAA0C;AAKnC,MAAM,0BAEH,eAAmD;AAAA,EAsB5D,YACU,QAKR;AACD,UAAM,kBAAkB,mBAAmB,OAAO,QAAQ,OAAO,OAAO,EAAE,WAAW;AAN5E;AAQT,SAAK,QAAQ,MAAM;AAEnB,SAAK,UAAU,OAAO;AAEtB,SAAK,MAAM,kBAAkB;AAAA,MAC5B,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,26 @@
import { entityKind } from "../../entity.cjs";
import { SQL, type SQLWrapper } from "../../sql/sql.cjs";
import type { MySqlSession } from "../session.cjs";
import type { MySqlTable } from "../table.cjs";
import type { MySqlViewBase } from "../view-base.cjs";
export declare class MySqlCountBuilder<TSession extends MySqlSession<any, any, any>> extends SQL<number> implements Promise<number>, SQLWrapper {
readonly params: {
source: MySqlTable | MySqlViewBase | SQL | SQLWrapper;
filters?: SQL<unknown>;
session: TSession;
};
private sql;
static readonly [entityKind] = "MySqlCountBuilder";
[Symbol.toStringTag]: string;
private session;
private static buildEmbeddedCount;
private static buildCount;
constructor(params: {
source: MySqlTable | MySqlViewBase | 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) => never | PromiseLike<never>) | null | undefined): Promise<number>;
finally(onFinally?: (() => void) | null | undefined): Promise<number>;
}

View File

@ -0,0 +1,26 @@
import { entityKind } from "../../entity.js";
import { SQL, type SQLWrapper } from "../../sql/sql.js";
import type { MySqlSession } from "../session.js";
import type { MySqlTable } from "../table.js";
import type { MySqlViewBase } from "../view-base.js";
export declare class MySqlCountBuilder<TSession extends MySqlSession<any, any, any>> extends SQL<number> implements Promise<number>, SQLWrapper {
readonly params: {
source: MySqlTable | MySqlViewBase | SQL | SQLWrapper;
filters?: SQL<unknown>;
session: TSession;
};
private sql;
static readonly [entityKind] = "MySqlCountBuilder";
[Symbol.toStringTag]: string;
private session;
private static buildEmbeddedCount;
private static buildCount;
constructor(params: {
source: MySqlTable | MySqlViewBase | 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) => never | PromiseLike<never>) | 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 MySqlCountBuilder extends SQL {
constructor(params) {
super(MySqlCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
this.params = params;
this.mapWith(Number);
this.session = params.session;
this.sql = MySqlCountBuilder.buildCount(
params.source,
params.filters
);
}
sql;
static [entityKind] = "MySqlCountBuilder";
[Symbol.toStringTag] = "MySqlCountBuilder";
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 {
MySqlCountBuilder
};
//# sourceMappingURL=count.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/mysql-core/query-builders/count.ts"],"sourcesContent":["import { entityKind } from '~/entity.ts';\nimport { SQL, sql, type SQLWrapper } from '~/sql/sql.ts';\nimport type { MySqlSession } from '../session.ts';\nimport type { MySqlTable } from '../table.ts';\nimport type { MySqlViewBase } from '../view-base.ts';\n\nexport class MySqlCountBuilder<\n\tTSession extends MySqlSession<any, any, any>,\n> extends SQL<number> implements Promise<number>, SQLWrapper {\n\tprivate sql: SQL<number>;\n\n\tstatic override readonly [entityKind] = 'MySqlCountBuilder';\n\t[Symbol.toStringTag] = 'MySqlCountBuilder';\n\n\tprivate session: TSession;\n\n\tprivate static buildEmbeddedCount(\n\t\tsource: MySqlTable | MySqlViewBase | 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: MySqlTable | MySqlViewBase | 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: MySqlTable | MySqlViewBase | SQL | SQLWrapper;\n\t\t\tfilters?: SQL<unknown>;\n\t\t\tsession: TSession;\n\t\t},\n\t) {\n\t\tsuper(MySqlCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);\n\n\t\tthis.mapWith(Number);\n\n\t\tthis.session = params.session;\n\n\t\tthis.sql = MySqlCountBuilder.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) => never | PromiseLike<never>) | null | undefined,\n\t): Promise<number> {\n\t\treturn this.then(undefined, onRejected);\n\t}\n\n\tfinally(onFinally?: (() => void) | null | undefined): Promise<number> {\n\t\treturn this.then(\n\t\t\t(value) => {\n\t\t\t\tonFinally?.();\n\t\t\t\treturn value;\n\t\t\t},\n\t\t\t(reason) => {\n\t\t\t\tonFinally?.();\n\t\t\t\tthrow reason;\n\t\t\t},\n\t\t);\n\t}\n}\n"],"mappings":"AAAA,SAAS,kBAAkB;AAC3B,SAAS,KAAK,WAA4B;AAKnC,MAAM,0BAEH,IAAmD;AAAA,EAsB5D,YACU,QAKR;AACD,UAAM,kBAAkB,mBAAmB,OAAO,QAAQ,OAAO,OAAO,EAAE,WAAW;AAN5E;AAQT,SAAK,QAAQ,MAAM;AAEnB,SAAK,UAAU,OAAO;AAEtB,SAAK,MAAM,kBAAkB;AAAA,MAC5B,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,123 @@
"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, {
MySqlDeleteBase: () => MySqlDeleteBase
});
module.exports = __toCommonJS(delete_exports);
var import_entity = require("../../entity.cjs");
var import_query_promise = require("../../query-promise.cjs");
var import_selection_proxy = require("../../selection-proxy.cjs");
var import_table = require("../../table.cjs");
class MySqlDeleteBase extends import_query_promise.QueryPromise {
constructor(table, session, dialect, withList) {
super();
this.table = table;
this.session = session;
this.dialect = dialect;
this.config = { table, withList };
}
static [import_entity.entityKind] = "MySqlDelete";
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
* db.delete(cars).where(eq(cars.color, 'green'));
* // or
* 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
* db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
*
* // Delete all cars with the green or blue color
* db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where) {
this.config.where = where;
return this;
}
orderBy(...columns) {
if (typeof columns[0] === "function") {
const orderBy = columns[0](
new Proxy(
this.config.table[import_table.Table.Symbol.Columns],
new import_selection_proxy.SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
)
);
const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
this.config.orderBy = orderByArray;
} else {
const orderByArray = columns;
this.config.orderBy = orderByArray;
}
return this;
}
limit(limit) {
this.config.limit = limit;
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildDeleteQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
prepare() {
return this.session.prepareQuery(
this.dialect.sqlToQuery(this.getSQL()),
this.config.returning
);
}
execute = (placeholderValues) => {
return this.prepare().execute(placeholderValues);
};
createIterator = () => {
const self = this;
return async function* (placeholderValues) {
yield* self.prepare().iterator(placeholderValues);
};
};
iterator = this.createIterator();
$dynamic() {
return this;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
MySqlDeleteBase
});
//# sourceMappingURL=delete.cjs.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,83 @@
import { entityKind } from "../../entity.cjs";
import type { MySqlDialect } from "../dialect.cjs";
import type { AnyMySqlQueryResultHKT, MySqlPreparedQueryConfig, MySqlQueryResultHKT, MySqlQueryResultKind, MySqlSession, PreparedQueryHKTBase, PreparedQueryKind } from "../session.cjs";
import type { MySqlTable } from "../table.cjs";
import { QueryPromise } from "../../query-promise.cjs";
import type { Placeholder, Query, SQL, SQLWrapper } from "../../sql/sql.cjs";
import type { Subquery } from "../../subquery.cjs";
import type { ValueOrArray } from "../../utils.cjs";
import type { MySqlColumn } from "../columns/common.cjs";
import type { SelectedFieldsOrdered } from "./select.types.cjs";
export type MySqlDeleteWithout<T extends AnyMySqlDeleteBase, TDynamic extends boolean, K extends keyof T & string> = TDynamic extends true ? T : Omit<MySqlDeleteBase<T['_']['table'], T['_']['queryResult'], T['_']['preparedQueryHKT'], TDynamic, T['_']['excludedMethods'] | K>, T['_']['excludedMethods'] | K>;
export type MySqlDelete<TTable extends MySqlTable = MySqlTable, TQueryResult extends MySqlQueryResultHKT = AnyMySqlQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase = PreparedQueryHKTBase> = MySqlDeleteBase<TTable, TQueryResult, TPreparedQueryHKT, true, never>;
export interface MySqlDeleteConfig {
where?: SQL | undefined;
limit?: number | Placeholder;
orderBy?: (MySqlColumn | SQL | SQL.Aliased)[];
table: MySqlTable;
returning?: SelectedFieldsOrdered;
withList?: Subquery[];
}
export type MySqlDeletePrepare<T extends AnyMySqlDeleteBase> = PreparedQueryKind<T['_']['preparedQueryHKT'], MySqlPreparedQueryConfig & {
execute: MySqlQueryResultKind<T['_']['queryResult'], never>;
iterator: never;
}, true>;
type MySqlDeleteDynamic<T extends AnyMySqlDeleteBase> = MySqlDelete<T['_']['table'], T['_']['queryResult'], T['_']['preparedQueryHKT']>;
type AnyMySqlDeleteBase = MySqlDeleteBase<any, any, any, any, any>;
export interface MySqlDeleteBase<TTable extends MySqlTable, TQueryResult extends MySqlQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<MySqlQueryResultKind<TQueryResult, never>> {
readonly _: {
readonly table: TTable;
readonly queryResult: TQueryResult;
readonly preparedQueryHKT: TPreparedQueryHKT;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
};
}
export declare class MySqlDeleteBase<TTable extends MySqlTable, TQueryResult extends MySqlQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<MySqlQueryResultKind<TQueryResult, never>> implements SQLWrapper {
private table;
private session;
private dialect;
static readonly [entityKind]: string;
private config;
constructor(table: TTable, session: MySqlSession, dialect: MySqlDialect, 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
* db.delete(cars).where(eq(cars.color, 'green'));
* // or
* 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
* db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
*
* // Delete all cars with the green or blue color
* db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where: SQL | undefined): MySqlDeleteWithout<this, TDynamic, 'where'>;
orderBy(builder: (deleteTable: TTable) => ValueOrArray<MySqlColumn | SQL | SQL.Aliased>): MySqlDeleteWithout<this, TDynamic, 'orderBy'>;
orderBy(...columns: (MySqlColumn | SQL | SQL.Aliased)[]): MySqlDeleteWithout<this, TDynamic, 'orderBy'>;
limit(limit: number | Placeholder): MySqlDeleteWithout<this, TDynamic, 'limit'>;
toSQL(): Query;
prepare(): MySqlDeletePrepare<this>;
execute: ReturnType<this['prepare']>['execute'];
private createIterator;
iterator: ReturnType<this["prepare"]>["iterator"];
$dynamic(): MySqlDeleteDynamic<this>;
}
export {};

View File

@ -0,0 +1,83 @@
import { entityKind } from "../../entity.js";
import type { MySqlDialect } from "../dialect.js";
import type { AnyMySqlQueryResultHKT, MySqlPreparedQueryConfig, MySqlQueryResultHKT, MySqlQueryResultKind, MySqlSession, PreparedQueryHKTBase, PreparedQueryKind } from "../session.js";
import type { MySqlTable } from "../table.js";
import { QueryPromise } from "../../query-promise.js";
import type { Placeholder, Query, SQL, SQLWrapper } from "../../sql/sql.js";
import type { Subquery } from "../../subquery.js";
import type { ValueOrArray } from "../../utils.js";
import type { MySqlColumn } from "../columns/common.js";
import type { SelectedFieldsOrdered } from "./select.types.js";
export type MySqlDeleteWithout<T extends AnyMySqlDeleteBase, TDynamic extends boolean, K extends keyof T & string> = TDynamic extends true ? T : Omit<MySqlDeleteBase<T['_']['table'], T['_']['queryResult'], T['_']['preparedQueryHKT'], TDynamic, T['_']['excludedMethods'] | K>, T['_']['excludedMethods'] | K>;
export type MySqlDelete<TTable extends MySqlTable = MySqlTable, TQueryResult extends MySqlQueryResultHKT = AnyMySqlQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase = PreparedQueryHKTBase> = MySqlDeleteBase<TTable, TQueryResult, TPreparedQueryHKT, true, never>;
export interface MySqlDeleteConfig {
where?: SQL | undefined;
limit?: number | Placeholder;
orderBy?: (MySqlColumn | SQL | SQL.Aliased)[];
table: MySqlTable;
returning?: SelectedFieldsOrdered;
withList?: Subquery[];
}
export type MySqlDeletePrepare<T extends AnyMySqlDeleteBase> = PreparedQueryKind<T['_']['preparedQueryHKT'], MySqlPreparedQueryConfig & {
execute: MySqlQueryResultKind<T['_']['queryResult'], never>;
iterator: never;
}, true>;
type MySqlDeleteDynamic<T extends AnyMySqlDeleteBase> = MySqlDelete<T['_']['table'], T['_']['queryResult'], T['_']['preparedQueryHKT']>;
type AnyMySqlDeleteBase = MySqlDeleteBase<any, any, any, any, any>;
export interface MySqlDeleteBase<TTable extends MySqlTable, TQueryResult extends MySqlQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<MySqlQueryResultKind<TQueryResult, never>> {
readonly _: {
readonly table: TTable;
readonly queryResult: TQueryResult;
readonly preparedQueryHKT: TPreparedQueryHKT;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
};
}
export declare class MySqlDeleteBase<TTable extends MySqlTable, TQueryResult extends MySqlQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<MySqlQueryResultKind<TQueryResult, never>> implements SQLWrapper {
private table;
private session;
private dialect;
static readonly [entityKind]: string;
private config;
constructor(table: TTable, session: MySqlSession, dialect: MySqlDialect, 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
* db.delete(cars).where(eq(cars.color, 'green'));
* // or
* 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
* db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
*
* // Delete all cars with the green or blue color
* db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where: SQL | undefined): MySqlDeleteWithout<this, TDynamic, 'where'>;
orderBy(builder: (deleteTable: TTable) => ValueOrArray<MySqlColumn | SQL | SQL.Aliased>): MySqlDeleteWithout<this, TDynamic, 'orderBy'>;
orderBy(...columns: (MySqlColumn | SQL | SQL.Aliased)[]): MySqlDeleteWithout<this, TDynamic, 'orderBy'>;
limit(limit: number | Placeholder): MySqlDeleteWithout<this, TDynamic, 'limit'>;
toSQL(): Query;
prepare(): MySqlDeletePrepare<this>;
execute: ReturnType<this['prepare']>['execute'];
private createIterator;
iterator: ReturnType<this["prepare"]>["iterator"];
$dynamic(): MySqlDeleteDynamic<this>;
}
export {};

View File

@ -0,0 +1,99 @@
import { entityKind } from "../../entity.js";
import { QueryPromise } from "../../query-promise.js";
import { SelectionProxyHandler } from "../../selection-proxy.js";
import { Table } from "../../table.js";
class MySqlDeleteBase extends QueryPromise {
constructor(table, session, dialect, withList) {
super();
this.table = table;
this.session = session;
this.dialect = dialect;
this.config = { table, withList };
}
static [entityKind] = "MySqlDelete";
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
* db.delete(cars).where(eq(cars.color, 'green'));
* // or
* 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
* db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
*
* // Delete all cars with the green or blue color
* db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where) {
this.config.where = where;
return this;
}
orderBy(...columns) {
if (typeof columns[0] === "function") {
const orderBy = columns[0](
new Proxy(
this.config.table[Table.Symbol.Columns],
new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
)
);
const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
this.config.orderBy = orderByArray;
} else {
const orderByArray = columns;
this.config.orderBy = orderByArray;
}
return this;
}
limit(limit) {
this.config.limit = limit;
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildDeleteQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
prepare() {
return this.session.prepareQuery(
this.dialect.sqlToQuery(this.getSQL()),
this.config.returning
);
}
execute = (placeholderValues) => {
return this.prepare().execute(placeholderValues);
};
createIterator = () => {
const self = this;
return async function* (placeholderValues) {
yield* self.prepare().iterator(placeholderValues);
};
};
iterator = this.createIterator();
$dynamic() {
return this;
}
}
export {
MySqlDeleteBase
};
//# sourceMappingURL=delete.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,33 @@
"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("./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("./select.cjs"),
...require("./select.types.cjs"),
...require("./update.cjs")
});
//# sourceMappingURL=index.cjs.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/mysql-core/query-builders/index.ts"],"sourcesContent":["export * from './delete.ts';\nexport * from './insert.ts';\nexport * from './query-builder.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,wBAHd;AAIA,mCAAc,8BAJd;AAKA,mCAAc,wBALd;","names":[]}

View File

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

View File

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

View File

@ -0,0 +1,7 @@
export * from "./delete.js";
export * from "./insert.js";
export * from "./query-builder.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/mysql-core/query-builders/index.ts"],"sourcesContent":["export * from './delete.ts';\nexport * from './insert.ts';\nexport * from './query-builder.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;","names":[]}

View File

@ -0,0 +1,156 @@
"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, {
MySqlInsertBase: () => MySqlInsertBase,
MySqlInsertBuilder: () => MySqlInsertBuilder
});
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_utils = require("../../utils.cjs");
var import_query_builder = require("./query-builder.cjs");
class MySqlInsertBuilder {
constructor(table, session, dialect) {
this.table = table;
this.session = session;
this.dialect = dialect;
}
static [import_entity.entityKind] = "MySqlInsertBuilder";
shouldIgnore = false;
ignore() {
this.shouldIgnore = 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 MySqlInsertBase(this.table, mappedValues, this.shouldIgnore, this.session, this.dialect);
}
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 MySqlInsertBase(this.table, select, this.shouldIgnore, this.session, this.dialect, true);
}
}
class MySqlInsertBase extends import_query_promise.QueryPromise {
constructor(table, values, ignore, session, dialect, select) {
super();
this.session = session;
this.dialect = dialect;
this.config = { table, values, select, ignore };
}
static [import_entity.entityKind] = "MySqlInsert";
config;
/**
* Adds an `on duplicate key update` clause to the query.
*
* Calling this method will update the row if any unique index conflicts. MySQL will automatically determine the conflict target based on the primary key and unique indexes.
*
* See docs: {@link https://orm.drizzle.team/docs/insert#on-duplicate-key-update}
*
* @param config The `set` clause
*
* @example
* ```ts
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW'})
* .onDuplicateKeyUpdate({ set: { brand: 'Porsche' }});
* ```
*
* While MySQL does not directly support doing nothing on conflict, you can perform a no-op by setting any column's value to itself and achieve the same effect:
*
* ```ts
* import { sql } from 'drizzle-orm';
*
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onDuplicateKeyUpdate({ set: { id: sql`id` } });
* ```
*/
onDuplicateKeyUpdate(config) {
const setSql = this.dialect.buildUpdateSet(this.config.table, (0, import_utils.mapUpdateSet)(this.config.table, config.set));
this.config.onConflict = import_sql.sql`update ${setSql}`;
return this;
}
$returningId() {
const returning = [];
for (const [key, value] of Object.entries(this.config.table[import_table.Table.Symbol.Columns])) {
if (value.primary) {
returning.push({ field: value, path: [key] });
}
}
this.config.returning = returning;
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildInsertQuery(this.config).sql;
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
prepare() {
const { sql: sql2, generatedIds } = this.dialect.buildInsertQuery(this.config);
return this.session.prepareQuery(
this.dialect.sqlToQuery(sql2),
void 0,
void 0,
generatedIds,
this.config.returning
);
}
execute = (placeholderValues) => {
return this.prepare().execute(placeholderValues);
};
createIterator = () => {
const self = this;
return async function* (placeholderValues) {
yield* self.prepare().iterator(placeholderValues);
};
};
iterator = this.createIterator();
$dynamic() {
return this;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
MySqlInsertBase,
MySqlInsertBuilder
});
//# 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 { MySqlDialect } from "../dialect.cjs";
import type { AnyMySqlQueryResultHKT, MySqlPreparedQueryConfig, MySqlQueryResultHKT, MySqlQueryResultKind, MySqlSession, PreparedQueryHKTBase, PreparedQueryKind } from "../session.cjs";
import type { MySqlTable } from "../table.cjs";
import type { TypedQueryBuilder } from "../../query-builders/query-builder.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 { InferModelFromColumns } from "../../table.cjs";
import type { AnyMySqlColumn } from "../columns/common.cjs";
import { QueryBuilder } from "./query-builder.cjs";
import type { SelectedFieldsOrdered } from "./select.types.cjs";
import type { MySqlUpdateSetSource } from "./update.cjs";
export interface MySqlInsertConfig<TTable extends MySqlTable = MySqlTable> {
table: TTable;
values: Record<string, Param | SQL>[] | MySqlInsertSelectQueryBuilder<TTable> | SQL;
ignore: boolean;
onConflict?: SQL;
returning?: SelectedFieldsOrdered;
select?: boolean;
}
export type AnyMySqlInsertConfig = MySqlInsertConfig<MySqlTable>;
export type MySqlInsertValue<TTable extends MySqlTable> = {
[Key in keyof TTable['$inferInsert']]: TTable['$inferInsert'][Key] | SQL | Placeholder;
} & {};
export type MySqlInsertSelectQueryBuilder<TTable extends MySqlTable> = TypedQueryBuilder<{
[K in keyof TTable['$inferInsert']]: AnyMySqlColumn | SQL | SQL.Aliased | TTable['$inferInsert'][K];
}>;
export declare class MySqlInsertBuilder<TTable extends MySqlTable, TQueryResult extends MySqlQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase> {
private table;
private session;
private dialect;
static readonly [entityKind]: string;
private shouldIgnore;
constructor(table: TTable, session: MySqlSession, dialect: MySqlDialect);
ignore(): this;
values(value: MySqlInsertValue<TTable>): MySqlInsertBase<TTable, TQueryResult, TPreparedQueryHKT>;
values(values: MySqlInsertValue<TTable>[]): MySqlInsertBase<TTable, TQueryResult, TPreparedQueryHKT>;
select(selectQuery: (qb: QueryBuilder) => MySqlInsertSelectQueryBuilder<TTable>): MySqlInsertBase<TTable, TQueryResult, TPreparedQueryHKT>;
select(selectQuery: (qb: QueryBuilder) => SQL): MySqlInsertBase<TTable, TQueryResult, TPreparedQueryHKT>;
select(selectQuery: SQL): MySqlInsertBase<TTable, TQueryResult, TPreparedQueryHKT>;
select(selectQuery: MySqlInsertSelectQueryBuilder<TTable>): MySqlInsertBase<TTable, TQueryResult, TPreparedQueryHKT>;
}
export type MySqlInsertWithout<T extends AnyMySqlInsert, TDynamic extends boolean, K extends keyof T & string> = TDynamic extends true ? T : Omit<MySqlInsertBase<T['_']['table'], T['_']['queryResult'], T['_']['preparedQueryHKT'], T['_']['returning'], TDynamic, T['_']['excludedMethods'] | '$returning'>, T['_']['excludedMethods'] | K>;
export type MySqlInsertDynamic<T extends AnyMySqlInsert> = MySqlInsert<T['_']['table'], T['_']['queryResult'], T['_']['preparedQueryHKT'], T['_']['returning']>;
export type MySqlInsertPrepare<T extends AnyMySqlInsert, TReturning extends Record<string, unknown> | undefined = undefined> = PreparedQueryKind<T['_']['preparedQueryHKT'], MySqlPreparedQueryConfig & {
execute: TReturning extends undefined ? MySqlQueryResultKind<T['_']['queryResult'], never> : TReturning[];
iterator: never;
}, true>;
export type MySqlInsertOnDuplicateKeyUpdateConfig<T extends AnyMySqlInsert> = {
set: MySqlUpdateSetSource<T['_']['table']>;
};
export type MySqlInsert<TTable extends MySqlTable = MySqlTable, TQueryResult extends MySqlQueryResultHKT = AnyMySqlQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase = PreparedQueryHKTBase, TReturning extends Record<string, unknown> | undefined = Record<string, unknown> | undefined> = MySqlInsertBase<TTable, TQueryResult, TPreparedQueryHKT, TReturning, true, never>;
export type MySqlInsertReturning<T extends AnyMySqlInsert, TDynamic extends boolean> = MySqlInsertBase<T['_']['table'], T['_']['queryResult'], T['_']['preparedQueryHKT'], InferModelFromColumns<GetPrimarySerialOrDefaultKeys<T['_']['table']['_']['columns']>>, TDynamic, T['_']['excludedMethods'] | '$returning'>;
export type AnyMySqlInsert = MySqlInsertBase<any, any, any, any, any, any>;
export interface MySqlInsertBase<TTable extends MySqlTable, TQueryResult extends MySqlQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase, TReturning extends Record<string, unknown> | undefined = undefined, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? MySqlQueryResultKind<TQueryResult, never> : TReturning[]>, RunnableQuery<TReturning extends undefined ? MySqlQueryResultKind<TQueryResult, never> : TReturning[], 'mysql'>, SQLWrapper {
readonly _: {
readonly dialect: 'mysql';
readonly table: TTable;
readonly queryResult: TQueryResult;
readonly preparedQueryHKT: TPreparedQueryHKT;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
readonly returning: TReturning;
readonly result: TReturning extends undefined ? MySqlQueryResultKind<TQueryResult, never> : TReturning[];
};
}
export type PrimaryKeyKeys<T extends Record<string, AnyMySqlColumn>> = {
[K in keyof T]: T[K]['_']['isPrimaryKey'] extends true ? T[K]['_']['isAutoincrement'] extends true ? K : T[K]['_']['hasRuntimeDefault'] extends true ? T[K]['_']['isPrimaryKey'] extends true ? K : never : never : T[K]['_']['hasRuntimeDefault'] extends true ? T[K]['_']['isPrimaryKey'] extends true ? K : never : never;
}[keyof T];
export type GetPrimarySerialOrDefaultKeys<T extends Record<string, AnyMySqlColumn>> = {
[K in PrimaryKeyKeys<T>]: T[K];
};
export declare class MySqlInsertBase<TTable extends MySqlTable, TQueryResult extends MySqlQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase, TReturning extends Record<string, unknown> | undefined = undefined, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? MySqlQueryResultKind<TQueryResult, never> : TReturning[]> implements RunnableQuery<TReturning extends undefined ? MySqlQueryResultKind<TQueryResult, never> : TReturning[], 'mysql'>, SQLWrapper {
private session;
private dialect;
static readonly [entityKind]: string;
protected $table: TTable;
private config;
constructor(table: TTable, values: MySqlInsertConfig['values'], ignore: boolean, session: MySqlSession, dialect: MySqlDialect, select?: boolean);
/**
* Adds an `on duplicate key update` clause to the query.
*
* Calling this method will update the row if any unique index conflicts. MySQL will automatically determine the conflict target based on the primary key and unique indexes.
*
* See docs: {@link https://orm.drizzle.team/docs/insert#on-duplicate-key-update}
*
* @param config The `set` clause
*
* @example
* ```ts
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW'})
* .onDuplicateKeyUpdate({ set: { brand: 'Porsche' }});
* ```
*
* While MySQL does not directly support doing nothing on conflict, you can perform a no-op by setting any column's value to itself and achieve the same effect:
*
* ```ts
* import { sql } from 'drizzle-orm';
*
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onDuplicateKeyUpdate({ set: { id: sql`id` } });
* ```
*/
onDuplicateKeyUpdate(config: MySqlInsertOnDuplicateKeyUpdateConfig<this>): MySqlInsertWithout<this, TDynamic, 'onDuplicateKeyUpdate'>;
$returningId(): MySqlInsertWithout<MySqlInsertReturning<this, TDynamic>, TDynamic, '$returningId'>;
toSQL(): Query;
prepare(): MySqlInsertPrepare<this, TReturning>;
execute: ReturnType<this['prepare']>['execute'];
private createIterator;
iterator: ReturnType<this["prepare"]>["iterator"];
$dynamic(): MySqlInsertDynamic<this>;
}

View File

@ -0,0 +1,116 @@
import { entityKind } from "../../entity.js";
import type { MySqlDialect } from "../dialect.js";
import type { AnyMySqlQueryResultHKT, MySqlPreparedQueryConfig, MySqlQueryResultHKT, MySqlQueryResultKind, MySqlSession, PreparedQueryHKTBase, PreparedQueryKind } from "../session.js";
import type { MySqlTable } from "../table.js";
import type { TypedQueryBuilder } from "../../query-builders/query-builder.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 { InferModelFromColumns } from "../../table.js";
import type { AnyMySqlColumn } from "../columns/common.js";
import { QueryBuilder } from "./query-builder.js";
import type { SelectedFieldsOrdered } from "./select.types.js";
import type { MySqlUpdateSetSource } from "./update.js";
export interface MySqlInsertConfig<TTable extends MySqlTable = MySqlTable> {
table: TTable;
values: Record<string, Param | SQL>[] | MySqlInsertSelectQueryBuilder<TTable> | SQL;
ignore: boolean;
onConflict?: SQL;
returning?: SelectedFieldsOrdered;
select?: boolean;
}
export type AnyMySqlInsertConfig = MySqlInsertConfig<MySqlTable>;
export type MySqlInsertValue<TTable extends MySqlTable> = {
[Key in keyof TTable['$inferInsert']]: TTable['$inferInsert'][Key] | SQL | Placeholder;
} & {};
export type MySqlInsertSelectQueryBuilder<TTable extends MySqlTable> = TypedQueryBuilder<{
[K in keyof TTable['$inferInsert']]: AnyMySqlColumn | SQL | SQL.Aliased | TTable['$inferInsert'][K];
}>;
export declare class MySqlInsertBuilder<TTable extends MySqlTable, TQueryResult extends MySqlQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase> {
private table;
private session;
private dialect;
static readonly [entityKind]: string;
private shouldIgnore;
constructor(table: TTable, session: MySqlSession, dialect: MySqlDialect);
ignore(): this;
values(value: MySqlInsertValue<TTable>): MySqlInsertBase<TTable, TQueryResult, TPreparedQueryHKT>;
values(values: MySqlInsertValue<TTable>[]): MySqlInsertBase<TTable, TQueryResult, TPreparedQueryHKT>;
select(selectQuery: (qb: QueryBuilder) => MySqlInsertSelectQueryBuilder<TTable>): MySqlInsertBase<TTable, TQueryResult, TPreparedQueryHKT>;
select(selectQuery: (qb: QueryBuilder) => SQL): MySqlInsertBase<TTable, TQueryResult, TPreparedQueryHKT>;
select(selectQuery: SQL): MySqlInsertBase<TTable, TQueryResult, TPreparedQueryHKT>;
select(selectQuery: MySqlInsertSelectQueryBuilder<TTable>): MySqlInsertBase<TTable, TQueryResult, TPreparedQueryHKT>;
}
export type MySqlInsertWithout<T extends AnyMySqlInsert, TDynamic extends boolean, K extends keyof T & string> = TDynamic extends true ? T : Omit<MySqlInsertBase<T['_']['table'], T['_']['queryResult'], T['_']['preparedQueryHKT'], T['_']['returning'], TDynamic, T['_']['excludedMethods'] | '$returning'>, T['_']['excludedMethods'] | K>;
export type MySqlInsertDynamic<T extends AnyMySqlInsert> = MySqlInsert<T['_']['table'], T['_']['queryResult'], T['_']['preparedQueryHKT'], T['_']['returning']>;
export type MySqlInsertPrepare<T extends AnyMySqlInsert, TReturning extends Record<string, unknown> | undefined = undefined> = PreparedQueryKind<T['_']['preparedQueryHKT'], MySqlPreparedQueryConfig & {
execute: TReturning extends undefined ? MySqlQueryResultKind<T['_']['queryResult'], never> : TReturning[];
iterator: never;
}, true>;
export type MySqlInsertOnDuplicateKeyUpdateConfig<T extends AnyMySqlInsert> = {
set: MySqlUpdateSetSource<T['_']['table']>;
};
export type MySqlInsert<TTable extends MySqlTable = MySqlTable, TQueryResult extends MySqlQueryResultHKT = AnyMySqlQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase = PreparedQueryHKTBase, TReturning extends Record<string, unknown> | undefined = Record<string, unknown> | undefined> = MySqlInsertBase<TTable, TQueryResult, TPreparedQueryHKT, TReturning, true, never>;
export type MySqlInsertReturning<T extends AnyMySqlInsert, TDynamic extends boolean> = MySqlInsertBase<T['_']['table'], T['_']['queryResult'], T['_']['preparedQueryHKT'], InferModelFromColumns<GetPrimarySerialOrDefaultKeys<T['_']['table']['_']['columns']>>, TDynamic, T['_']['excludedMethods'] | '$returning'>;
export type AnyMySqlInsert = MySqlInsertBase<any, any, any, any, any, any>;
export interface MySqlInsertBase<TTable extends MySqlTable, TQueryResult extends MySqlQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase, TReturning extends Record<string, unknown> | undefined = undefined, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? MySqlQueryResultKind<TQueryResult, never> : TReturning[]>, RunnableQuery<TReturning extends undefined ? MySqlQueryResultKind<TQueryResult, never> : TReturning[], 'mysql'>, SQLWrapper {
readonly _: {
readonly dialect: 'mysql';
readonly table: TTable;
readonly queryResult: TQueryResult;
readonly preparedQueryHKT: TPreparedQueryHKT;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
readonly returning: TReturning;
readonly result: TReturning extends undefined ? MySqlQueryResultKind<TQueryResult, never> : TReturning[];
};
}
export type PrimaryKeyKeys<T extends Record<string, AnyMySqlColumn>> = {
[K in keyof T]: T[K]['_']['isPrimaryKey'] extends true ? T[K]['_']['isAutoincrement'] extends true ? K : T[K]['_']['hasRuntimeDefault'] extends true ? T[K]['_']['isPrimaryKey'] extends true ? K : never : never : T[K]['_']['hasRuntimeDefault'] extends true ? T[K]['_']['isPrimaryKey'] extends true ? K : never : never;
}[keyof T];
export type GetPrimarySerialOrDefaultKeys<T extends Record<string, AnyMySqlColumn>> = {
[K in PrimaryKeyKeys<T>]: T[K];
};
export declare class MySqlInsertBase<TTable extends MySqlTable, TQueryResult extends MySqlQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase, TReturning extends Record<string, unknown> | undefined = undefined, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<TReturning extends undefined ? MySqlQueryResultKind<TQueryResult, never> : TReturning[]> implements RunnableQuery<TReturning extends undefined ? MySqlQueryResultKind<TQueryResult, never> : TReturning[], 'mysql'>, SQLWrapper {
private session;
private dialect;
static readonly [entityKind]: string;
protected $table: TTable;
private config;
constructor(table: TTable, values: MySqlInsertConfig['values'], ignore: boolean, session: MySqlSession, dialect: MySqlDialect, select?: boolean);
/**
* Adds an `on duplicate key update` clause to the query.
*
* Calling this method will update the row if any unique index conflicts. MySQL will automatically determine the conflict target based on the primary key and unique indexes.
*
* See docs: {@link https://orm.drizzle.team/docs/insert#on-duplicate-key-update}
*
* @param config The `set` clause
*
* @example
* ```ts
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW'})
* .onDuplicateKeyUpdate({ set: { brand: 'Porsche' }});
* ```
*
* While MySQL does not directly support doing nothing on conflict, you can perform a no-op by setting any column's value to itself and achieve the same effect:
*
* ```ts
* import { sql } from 'drizzle-orm';
*
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onDuplicateKeyUpdate({ set: { id: sql`id` } });
* ```
*/
onDuplicateKeyUpdate(config: MySqlInsertOnDuplicateKeyUpdateConfig<this>): MySqlInsertWithout<this, TDynamic, 'onDuplicateKeyUpdate'>;
$returningId(): MySqlInsertWithout<MySqlInsertReturning<this, TDynamic>, TDynamic, '$returningId'>;
toSQL(): Query;
prepare(): MySqlInsertPrepare<this, TReturning>;
execute: ReturnType<this['prepare']>['execute'];
private createIterator;
iterator: ReturnType<this["prepare"]>["iterator"];
$dynamic(): MySqlInsertDynamic<this>;
}

View File

@ -0,0 +1,131 @@
import { entityKind, is } from "../../entity.js";
import { QueryPromise } from "../../query-promise.js";
import { Param, SQL, sql } from "../../sql/sql.js";
import { Columns, Table } from "../../table.js";
import { haveSameKeys, mapUpdateSet } from "../../utils.js";
import { QueryBuilder } from "./query-builder.js";
class MySqlInsertBuilder {
constructor(table, session, dialect) {
this.table = table;
this.session = session;
this.dialect = dialect;
}
static [entityKind] = "MySqlInsertBuilder";
shouldIgnore = false;
ignore() {
this.shouldIgnore = 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 MySqlInsertBase(this.table, mappedValues, this.shouldIgnore, this.session, this.dialect);
}
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 MySqlInsertBase(this.table, select, this.shouldIgnore, this.session, this.dialect, true);
}
}
class MySqlInsertBase extends QueryPromise {
constructor(table, values, ignore, session, dialect, select) {
super();
this.session = session;
this.dialect = dialect;
this.config = { table, values, select, ignore };
}
static [entityKind] = "MySqlInsert";
config;
/**
* Adds an `on duplicate key update` clause to the query.
*
* Calling this method will update the row if any unique index conflicts. MySQL will automatically determine the conflict target based on the primary key and unique indexes.
*
* See docs: {@link https://orm.drizzle.team/docs/insert#on-duplicate-key-update}
*
* @param config The `set` clause
*
* @example
* ```ts
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW'})
* .onDuplicateKeyUpdate({ set: { brand: 'Porsche' }});
* ```
*
* While MySQL does not directly support doing nothing on conflict, you can perform a no-op by setting any column's value to itself and achieve the same effect:
*
* ```ts
* import { sql } from 'drizzle-orm';
*
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onDuplicateKeyUpdate({ set: { id: sql`id` } });
* ```
*/
onDuplicateKeyUpdate(config) {
const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
this.config.onConflict = sql`update ${setSql}`;
return this;
}
$returningId() {
const returning = [];
for (const [key, value] of Object.entries(this.config.table[Table.Symbol.Columns])) {
if (value.primary) {
returning.push({ field: value, path: [key] });
}
}
this.config.returning = returning;
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildInsertQuery(this.config).sql;
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
prepare() {
const { sql: sql2, generatedIds } = this.dialect.buildInsertQuery(this.config);
return this.session.prepareQuery(
this.dialect.sqlToQuery(sql2),
void 0,
void 0,
generatedIds,
this.config.returning
);
}
execute = (placeholderValues) => {
return this.prepare().execute(placeholderValues);
};
createIterator = () => {
const self = this;
return async function* (placeholderValues) {
yield* self.prepare().iterator(placeholderValues);
};
};
iterator = this.createIterator();
$dynamic() {
return this;
}
}
export {
MySqlInsertBase,
MySqlInsertBuilder
};
//# sourceMappingURL=insert.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,95 @@
"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] = "MySqlQueryBuilder";
dialect;
dialectConfig;
constructor(dialect) {
this.dialect = (0, import_entity.is)(dialect, import_dialect.MySqlDialect) ? dialect : void 0;
this.dialectConfig = (0, import_entity.is)(dialect, import_dialect.MySqlDialect) ? 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.MySqlSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: self.getDialect(),
withList: queries
});
}
function selectDistinct(fields) {
return new import_select.MySqlSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: self.getDialect(),
withList: queries,
distinct: true
});
}
return { select, selectDistinct };
}
select(fields) {
return new import_select.MySqlSelectBuilder({ fields: fields ?? void 0, session: void 0, dialect: this.getDialect() });
}
selectDistinct(fields) {
return new import_select.MySqlSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: this.getDialect(),
distinct: true
});
}
// Lazy load dialect to avoid circular dependency
getDialect() {
if (!this.dialect) {
this.dialect = new import_dialect.MySqlDialect(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,33 @@
import { entityKind } from "../../entity.cjs";
import type { MySqlDialectConfig } from "../dialect.cjs";
import { MySqlDialect } from "../dialect.cjs";
import type { WithSubqueryWithSelection } from "../subquery.cjs";
import type { TypedQueryBuilder } from "../../query-builders/query-builder.cjs";
import type { ColumnsSelection } from "../../sql/sql.cjs";
import { WithSubquery } from "../../subquery.cjs";
import { MySqlSelectBuilder } from "./select.cjs";
import type { SelectedFields } from "./select.types.cjs";
export declare class QueryBuilder {
static readonly [entityKind]: string;
private dialect;
private dialectConfig;
constructor(dialect?: MySqlDialect | MySqlDialectConfig);
$with<TAlias extends string>(alias: TAlias): {
as<TSelection extends ColumnsSelection>(qb: TypedQueryBuilder<TSelection> | ((qb: QueryBuilder) => TypedQueryBuilder<TSelection>)): WithSubqueryWithSelection<TSelection, TAlias>;
};
with(...queries: WithSubquery[]): {
select: {
(): MySqlSelectBuilder<undefined, never, "qb">;
<TSelection extends SelectedFields>(fields: TSelection): MySqlSelectBuilder<TSelection, never, "qb">;
};
selectDistinct: {
(): MySqlSelectBuilder<undefined, never, "qb">;
<TSelection extends SelectedFields>(fields: TSelection): MySqlSelectBuilder<TSelection, never, "qb">;
};
};
select(): MySqlSelectBuilder<undefined, never, 'qb'>;
select<TSelection extends SelectedFields>(fields: TSelection): MySqlSelectBuilder<TSelection, never, 'qb'>;
selectDistinct(): MySqlSelectBuilder<undefined, never, 'qb'>;
selectDistinct<TSelection extends SelectedFields>(fields: TSelection): MySqlSelectBuilder<TSelection, never, 'qb'>;
private getDialect;
}

View File

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

View File

@ -0,0 +1,71 @@
import { entityKind, is } from "../../entity.js";
import { MySqlDialect } from "../dialect.js";
import { SelectionProxyHandler } from "../../selection-proxy.js";
import { WithSubquery } from "../../subquery.js";
import { MySqlSelectBuilder } from "./select.js";
class QueryBuilder {
static [entityKind] = "MySqlQueryBuilder";
dialect;
dialectConfig;
constructor(dialect) {
this.dialect = is(dialect, MySqlDialect) ? dialect : void 0;
this.dialectConfig = is(dialect, MySqlDialect) ? 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 MySqlSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: self.getDialect(),
withList: queries
});
}
function selectDistinct(fields) {
return new MySqlSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: self.getDialect(),
withList: queries,
distinct: true
});
}
return { select, selectDistinct };
}
select(fields) {
return new MySqlSelectBuilder({ fields: fields ?? void 0, session: void 0, dialect: this.getDialect() });
}
selectDistinct(fields) {
return new MySqlSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: this.getDialect(),
distinct: true
});
}
// Lazy load dialect to avoid circular dependency
getDialect() {
if (!this.dialect) {
this.dialect = new MySqlDialect(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, {
MySqlRelationalQuery: () => MySqlRelationalQuery,
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");
class RelationalQueryBuilder {
constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session, mode) {
this.fullSchema = fullSchema;
this.schema = schema;
this.tableNamesMap = tableNamesMap;
this.table = table;
this.tableConfig = tableConfig;
this.dialect = dialect;
this.session = session;
this.mode = mode;
}
static [import_entity.entityKind] = "MySqlRelationalQueryBuilder";
findMany(config) {
return new MySqlRelationalQuery(
this.fullSchema,
this.schema,
this.tableNamesMap,
this.table,
this.tableConfig,
this.dialect,
this.session,
config ? config : {},
"many",
this.mode
);
}
findFirst(config) {
return new MySqlRelationalQuery(
this.fullSchema,
this.schema,
this.tableNamesMap,
this.table,
this.tableConfig,
this.dialect,
this.session,
config ? { ...config, limit: 1 } : { limit: 1 },
"first",
this.mode
);
}
}
class MySqlRelationalQuery extends import_query_promise.QueryPromise {
constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session, config, queryMode, 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.queryMode = queryMode;
this.mode = mode;
}
static [import_entity.entityKind] = "MySqlRelationalQuery";
prepare() {
const { query, builtQuery } = this._toSQL();
return this.session.prepareQuery(
builtQuery,
void 0,
(rawRows) => {
const rows = rawRows.map((row) => (0, import_relations.mapRelationalRow)(this.schema, this.tableConfig, row, query.selection));
if (this.queryMode === "first") {
return rows[0];
}
return rows;
}
);
}
_getQuery() {
const query = this.mode === "planetscale" ? this.dialect.buildRelationalQueryWithoutLateralSubqueries({
fullSchema: this.fullSchema,
schema: this.schema,
tableNamesMap: this.tableNamesMap,
table: this.table,
tableConfig: this.tableConfig,
queryConfig: this.config,
tableAlias: this.tableConfig.tsName
}) : this.dialect.buildRelationalQuery({
fullSchema: this.fullSchema,
schema: this.schema,
tableNamesMap: this.tableNamesMap,
table: this.table,
tableConfig: this.tableConfig,
queryConfig: this.config,
tableAlias: this.tableConfig.tsName
});
return query;
}
_toSQL() {
const query = this._getQuery();
const builtQuery = this.dialect.sqlToQuery(query.sql);
return { builtQuery, query };
}
/** @internal */
getSQL() {
return this._getQuery().sql;
}
toSQL() {
return this._toSQL().builtQuery;
}
execute() {
return this.prepare().execute();
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
MySqlRelationalQuery,
RelationalQueryBuilder
});
//# sourceMappingURL=query.cjs.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,44 @@
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 { Query } from "../../sql/sql.cjs";
import type { KnownKeysOnly } from "../../utils.cjs";
import type { MySqlDialect } from "../dialect.cjs";
import type { Mode, MySqlPreparedQueryConfig, MySqlSession, PreparedQueryHKTBase, PreparedQueryKind } from "../session.cjs";
import type { MySqlTable } from "../table.cjs";
export declare class RelationalQueryBuilder<TPreparedQueryHKT extends PreparedQueryHKTBase, TSchema extends TablesRelationalConfig, TFields extends TableRelationalConfig> {
private fullSchema;
private schema;
private tableNamesMap;
private table;
private tableConfig;
private dialect;
private session;
private mode;
static readonly [entityKind]: string;
constructor(fullSchema: Record<string, unknown>, schema: TSchema, tableNamesMap: Record<string, string>, table: MySqlTable, tableConfig: TableRelationalConfig, dialect: MySqlDialect, session: MySqlSession, mode: Mode);
findMany<TConfig extends DBQueryConfig<'many', true, TSchema, TFields>>(config?: KnownKeysOnly<TConfig, DBQueryConfig<'many', true, TSchema, TFields>>): MySqlRelationalQuery<TPreparedQueryHKT, BuildQueryResult<TSchema, TFields, TConfig>[]>;
findFirst<TSelection extends Omit<DBQueryConfig<'many', true, TSchema, TFields>, 'limit'>>(config?: KnownKeysOnly<TSelection, Omit<DBQueryConfig<'many', true, TSchema, TFields>, 'limit'>>): MySqlRelationalQuery<TPreparedQueryHKT, BuildQueryResult<TSchema, TFields, TSelection> | undefined>;
}
export declare class MySqlRelationalQuery<TPreparedQueryHKT extends PreparedQueryHKTBase, TResult> extends QueryPromise<TResult> {
private fullSchema;
private schema;
private tableNamesMap;
private table;
private tableConfig;
private dialect;
private session;
private config;
private queryMode;
private mode?;
static readonly [entityKind]: string;
protected $brand: 'MySqlRelationalQuery';
constructor(fullSchema: Record<string, unknown>, schema: TablesRelationalConfig, tableNamesMap: Record<string, string>, table: MySqlTable, tableConfig: TableRelationalConfig, dialect: MySqlDialect, session: MySqlSession, config: DBQueryConfig<'many', true> | true, queryMode: 'many' | 'first', mode?: Mode | undefined);
prepare(): PreparedQueryKind<TPreparedQueryHKT, MySqlPreparedQueryConfig & {
execute: TResult;
}, true>;
private _getQuery;
private _toSQL;
toSQL(): Query;
execute(): Promise<TResult>;
}

View File

@ -0,0 +1,44 @@
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 { Query } from "../../sql/sql.js";
import type { KnownKeysOnly } from "../../utils.js";
import type { MySqlDialect } from "../dialect.js";
import type { Mode, MySqlPreparedQueryConfig, MySqlSession, PreparedQueryHKTBase, PreparedQueryKind } from "../session.js";
import type { MySqlTable } from "../table.js";
export declare class RelationalQueryBuilder<TPreparedQueryHKT extends PreparedQueryHKTBase, TSchema extends TablesRelationalConfig, TFields extends TableRelationalConfig> {
private fullSchema;
private schema;
private tableNamesMap;
private table;
private tableConfig;
private dialect;
private session;
private mode;
static readonly [entityKind]: string;
constructor(fullSchema: Record<string, unknown>, schema: TSchema, tableNamesMap: Record<string, string>, table: MySqlTable, tableConfig: TableRelationalConfig, dialect: MySqlDialect, session: MySqlSession, mode: Mode);
findMany<TConfig extends DBQueryConfig<'many', true, TSchema, TFields>>(config?: KnownKeysOnly<TConfig, DBQueryConfig<'many', true, TSchema, TFields>>): MySqlRelationalQuery<TPreparedQueryHKT, BuildQueryResult<TSchema, TFields, TConfig>[]>;
findFirst<TSelection extends Omit<DBQueryConfig<'many', true, TSchema, TFields>, 'limit'>>(config?: KnownKeysOnly<TSelection, Omit<DBQueryConfig<'many', true, TSchema, TFields>, 'limit'>>): MySqlRelationalQuery<TPreparedQueryHKT, BuildQueryResult<TSchema, TFields, TSelection> | undefined>;
}
export declare class MySqlRelationalQuery<TPreparedQueryHKT extends PreparedQueryHKTBase, TResult> extends QueryPromise<TResult> {
private fullSchema;
private schema;
private tableNamesMap;
private table;
private tableConfig;
private dialect;
private session;
private config;
private queryMode;
private mode?;
static readonly [entityKind]: string;
protected $brand: 'MySqlRelationalQuery';
constructor(fullSchema: Record<string, unknown>, schema: TablesRelationalConfig, tableNamesMap: Record<string, string>, table: MySqlTable, tableConfig: TableRelationalConfig, dialect: MySqlDialect, session: MySqlSession, config: DBQueryConfig<'many', true> | true, queryMode: 'many' | 'first', mode?: Mode | undefined);
prepare(): PreparedQueryKind<TPreparedQueryHKT, MySqlPreparedQueryConfig & {
execute: TResult;
}, true>;
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";
class RelationalQueryBuilder {
constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session, mode) {
this.fullSchema = fullSchema;
this.schema = schema;
this.tableNamesMap = tableNamesMap;
this.table = table;
this.tableConfig = tableConfig;
this.dialect = dialect;
this.session = session;
this.mode = mode;
}
static [entityKind] = "MySqlRelationalQueryBuilder";
findMany(config) {
return new MySqlRelationalQuery(
this.fullSchema,
this.schema,
this.tableNamesMap,
this.table,
this.tableConfig,
this.dialect,
this.session,
config ? config : {},
"many",
this.mode
);
}
findFirst(config) {
return new MySqlRelationalQuery(
this.fullSchema,
this.schema,
this.tableNamesMap,
this.table,
this.tableConfig,
this.dialect,
this.session,
config ? { ...config, limit: 1 } : { limit: 1 },
"first",
this.mode
);
}
}
class MySqlRelationalQuery extends QueryPromise {
constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session, config, queryMode, 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.queryMode = queryMode;
this.mode = mode;
}
static [entityKind] = "MySqlRelationalQuery";
prepare() {
const { query, builtQuery } = this._toSQL();
return this.session.prepareQuery(
builtQuery,
void 0,
(rawRows) => {
const rows = rawRows.map((row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection));
if (this.queryMode === "first") {
return rows[0];
}
return rows;
}
);
}
_getQuery() {
const query = this.mode === "planetscale" ? this.dialect.buildRelationalQueryWithoutLateralSubqueries({
fullSchema: this.fullSchema,
schema: this.schema,
tableNamesMap: this.tableNamesMap,
table: this.table,
tableConfig: this.tableConfig,
queryConfig: this.config,
tableAlias: this.tableConfig.tsName
}) : this.dialect.buildRelationalQuery({
fullSchema: this.fullSchema,
schema: this.schema,
tableNamesMap: this.tableNamesMap,
table: this.table,
tableConfig: this.tableConfig,
queryConfig: this.config,
tableAlias: this.tableConfig.tsName
});
return query;
}
_toSQL() {
const query = this._getQuery();
const builtQuery = this.dialect.sqlToQuery(query.sql);
return { builtQuery, query };
}
/** @internal */
getSQL() {
return this._getQuery().sql;
}
toSQL() {
return this._toSQL().builtQuery;
}
execute() {
return this.prepare().execute();
}
}
export {
MySqlRelationalQuery,
RelationalQueryBuilder
};
//# sourceMappingURL=query.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,831 @@
"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, {
MySqlSelectBase: () => MySqlSelectBase,
MySqlSelectBuilder: () => MySqlSelectBuilder,
MySqlSelectQueryBuilderBase: () => MySqlSelectQueryBuilderBase,
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_table = require("../table.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_table2 = require("../../table.cjs");
var import_utils = require("../../utils.cjs");
var import_view_common = require("../../view-common.cjs");
var import_utils2 = require("../utils.cjs");
var import_view_base = require("../view-base.cjs");
class MySqlSelectBuilder {
static [import_entity.entityKind] = "MySqlSelectBuilder";
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;
}
from(source, onIndex) {
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.MySqlViewBase)) {
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);
}
let useIndex = [];
let forceIndex = [];
let ignoreIndex = [];
if ((0, import_entity.is)(source, import_table.MySqlTable) && onIndex && typeof onIndex !== "string") {
if (onIndex.useIndex) {
useIndex = (0, import_utils2.convertIndexToString)((0, import_utils2.toArray)(onIndex.useIndex));
}
if (onIndex.forceIndex) {
forceIndex = (0, import_utils2.convertIndexToString)((0, import_utils2.toArray)(onIndex.forceIndex));
}
if (onIndex.ignoreIndex) {
ignoreIndex = (0, import_utils2.convertIndexToString)((0, import_utils2.toArray)(onIndex.ignoreIndex));
}
}
return new MySqlSelectBase(
{
table: source,
fields,
isPartialSelect,
session: this.session,
dialect: this.dialect,
withList: this.withList,
distinct: this.distinct,
useIndex,
forceIndex,
ignoreIndex
}
);
}
}
class MySqlSelectQueryBuilderBase extends import_query_builder.TypedQueryBuilder {
static [import_entity.entityKind] = "MySqlSelectQueryBuilder";
_;
config;
joinsNotNullableMap;
tableName;
isPartialSelect;
/** @internal */
session;
dialect;
constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct, useIndex, forceIndex, ignoreIndex }) {
super();
this.config = {
withList,
table,
fields: { ...fields },
distinct,
setOperators: [],
useIndex,
forceIndex,
ignoreIndex
};
this.isPartialSelect = isPartialSelect;
this.session = session;
this.dialect = dialect;
this._ = {
selectedFields: fields
};
this.tableName = (0, import_utils.getTableLikeName)(table);
this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
}
createJoin(joinType) {
return (table, on, onIndex) => {
const baseTableName = this.tableName;
const tableName = (0, import_utils.getTableLikeName)(table);
if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) {
throw new Error(`Alias "${tableName}" is already used in this query`);
}
if (!this.isPartialSelect) {
if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") {
this.config.fields = {
[baseTableName]: this.config.fields
};
}
if (typeof tableName === "string" && !(0, import_entity.is)(table, import_sql.SQL)) {
const selection = (0, import_entity.is)(table, import_subquery.Subquery) ? table._.selectedFields : (0, import_entity.is)(table, import_sql.View) ? table[import_view_common.ViewBaseConfig].selectedFields : table[import_table2.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 = [];
}
let useIndex = [];
let forceIndex = [];
let ignoreIndex = [];
if ((0, import_entity.is)(table, import_table.MySqlTable) && onIndex && typeof onIndex !== "string") {
if (onIndex.useIndex) {
useIndex = (0, import_utils2.convertIndexToString)((0, import_utils2.toArray)(onIndex.useIndex));
}
if (onIndex.forceIndex) {
forceIndex = (0, import_utils2.convertIndexToString)((0, import_utils2.toArray)(onIndex.forceIndex));
}
if (onIndex.ignoreIndex) {
ignoreIndex = (0, import_utils2.convertIndexToString)((0, import_utils2.toArray)(onIndex.ignoreIndex));
}
}
this.config.joins.push({ on, table, joinType, alias: tableName, useIndex, forceIndex, ignoreIndex });
if (typeof tableName === "string") {
switch (joinType) {
case "left": {
this.joinsNotNullableMap[tableName] = false;
break;
}
case "right": {
this.joinsNotNullableMap = Object.fromEntries(
Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
);
this.joinsNotNullableMap[tableName] = true;
break;
}
case "inner": {
this.joinsNotNullableMap[tableName] = true;
break;
}
case "full": {
this.joinsNotNullableMap = Object.fromEntries(
Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
);
this.joinsNotNullableMap[tableName] = false;
break;
}
}
}
return this;
};
}
/**
* Executes a `left join` operation by adding another table to the current query.
*
* Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User; pets: Pet | null }[] = await db.select()
* .from(users)
* .leftJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number | null }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .leftJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId with use index hint
* 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), {
* useIndex: ['pets_owner_id_index']
* })
* ```
*/
leftJoin = this.createJoin("left");
/**
* Executes a `right join` operation by adding another table to the current query.
*
* Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User | null; pets: Pet }[] = await db.select()
* .from(users)
* .rightJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number | null; petId: number }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .rightJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId with use index hint
* 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), {
* useIndex: ['pets_owner_id_index']
* })
* ```
*/
rightJoin = this.createJoin("right");
/**
* Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
*
* Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User; pets: Pet }[] = await db.select()
* .from(users)
* .innerJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .innerJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId with use index hint
* 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), {
* useIndex: ['pets_owner_id_index']
* })
* ```
*/
innerJoin = this.createJoin("inner");
/**
* Executes a `full join` operation by combining rows from two tables into a new table.
*
* Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User | null; pets: Pet | null }[] = await db.select()
* .from(users)
* .fullJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number | null; petId: number | null }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .fullJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId with use index hint
* 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), {
* useIndex: ['pets_owner_id_index']
* })
* ```
*/
fullJoin = this.createJoin("full");
createSetOperator(type, isAll) {
return (rightSelection) => {
const rightSelect = typeof rightSelection === "function" ? rightSelection(getMySqlSetOperators()) : 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/mysql-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/mysql-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/mysql-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/mysql-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/mysql-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/mysql-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://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html}
*
* @param strength the lock strength.
* @param config the lock configuration.
*/
for(strength, config = {}) {
this.config.lockingClause = { strength, config };
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildSelectQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
as(alias) {
return new Proxy(
new import_subquery.Subquery(this.getSQL(), this.config.fields, alias),
new import_selection_proxy.SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
);
}
/** @internal */
getSelectedFields() {
return new Proxy(
this.config.fields,
new import_selection_proxy.SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
);
}
$dynamic() {
return this;
}
}
class MySqlSelectBase extends MySqlSelectQueryBuilderBase {
static [import_entity.entityKind] = "MySqlSelect";
prepare() {
if (!this.session) {
throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
}
const fieldsList = (0, import_utils.orderSelectedFields)(this.config.fields);
const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), fieldsList);
query.joinsNotNullableMap = this.joinsNotNullableMap;
return query;
}
execute = (placeholderValues) => {
return this.prepare().execute(placeholderValues);
};
createIterator = () => {
const self = this;
return async function* (placeholderValues) {
yield* self.prepare().iterator(placeholderValues);
};
};
iterator = this.createIterator();
}
(0, import_utils.applyMixins)(MySqlSelectBase, [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 getMySqlSetOperators = () => ({
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 = {
MySqlSelectBase,
MySqlSelectBuilder,
MySqlSelectQueryBuilderBase,
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,753 @@
import { entityKind } from "../../entity.cjs";
import type { MySqlColumn } from "../columns/index.cjs";
import type { MySqlDialect } from "../dialect.cjs";
import type { MySqlSession, PreparedQueryHKTBase } from "../session.cjs";
import type { SubqueryWithSelection } from "../subquery.cjs";
import { MySqlTable } from "../table.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 { ColumnsSelection, Placeholder, Query } from "../../sql/sql.cjs";
import { SQL } from "../../sql/sql.cjs";
import { Subquery } from "../../subquery.cjs";
import type { ValueOrArray } from "../../utils.cjs";
import type { IndexBuilder } from "../indexes.cjs";
import { MySqlViewBase } from "../view-base.cjs";
import type { CreateMySqlSelectFromBuilderMode, GetMySqlSetOperators, LockConfig, LockStrength, MySqlCreateSetOperatorFn, MySqlJoinFn, MySqlSelectConfig, MySqlSelectDynamic, MySqlSelectHKT, MySqlSelectHKTBase, MySqlSelectPrepare, MySqlSelectWithout, MySqlSetOperatorExcludedMethods, MySqlSetOperatorWithResult, SelectedFields, SetOperatorRightSelect } from "./select.types.cjs";
export type IndexForHint = IndexBuilder | string;
export type IndexConfig = {
useIndex?: IndexForHint | IndexForHint[];
forceIndex?: IndexForHint | IndexForHint[];
ignoreIndex?: IndexForHint | IndexForHint[];
};
export declare class MySqlSelectBuilder<TSelection extends SelectedFields | undefined, TPreparedQueryHKT extends PreparedQueryHKTBase, TBuilderMode extends 'db' | 'qb' = 'db'> {
static readonly [entityKind]: string;
private fields;
private session;
private dialect;
private withList;
private distinct;
constructor(config: {
fields: TSelection;
session: MySqlSession | undefined;
dialect: MySqlDialect;
withList?: Subquery[];
distinct?: boolean;
});
from<TFrom extends MySqlTable | Subquery | MySqlViewBase | SQL>(source: TFrom, onIndex?: TFrom extends MySqlTable ? IndexConfig : 'Index hint configuration is allowed only for MySqlTable and not for subqueries or views'): CreateMySqlSelectFromBuilderMode<TBuilderMode, GetSelectTableName<TFrom>, TSelection extends undefined ? GetSelectTableSelection<TFrom> : TSelection, TSelection extends undefined ? 'single' : 'partial', TPreparedQueryHKT>;
}
export declare abstract class MySqlSelectQueryBuilderBase<THKT extends MySqlSelectHKTBase, TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TPreparedQueryHKT extends PreparedQueryHKTBase, 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 hkt: THKT;
readonly tableName: TTableName;
readonly selection: TSelection;
readonly selectMode: TSelectMode;
readonly preparedQueryHKT: TPreparedQueryHKT;
readonly nullabilityMap: TNullabilityMap;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
readonly result: TResult;
readonly selectedFields: TSelectedFields;
};
protected config: MySqlSelectConfig;
protected joinsNotNullableMap: Record<string, boolean>;
private tableName;
private isPartialSelect;
protected dialect: MySqlDialect;
constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct, useIndex, forceIndex, ignoreIndex }: {
table: MySqlSelectConfig['table'];
fields: MySqlSelectConfig['fields'];
isPartialSelect: boolean;
session: MySqlSession | undefined;
dialect: MySqlDialect;
withList: Subquery[];
distinct: boolean | undefined;
useIndex?: string[];
forceIndex?: string[];
ignoreIndex?: string[];
});
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))
*
* // Select userId and petId with use index hint
* 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), {
* useIndex: ['pets_owner_id_index']
* })
* ```
*/
leftJoin: MySqlJoinFn<this, TDynamic, "left">;
/**
* Executes a `right join` operation by adding another table to the current query.
*
* Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User | null; pets: Pet }[] = await db.select()
* .from(users)
* .rightJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number | null; petId: number }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .rightJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId with use index hint
* 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), {
* useIndex: ['pets_owner_id_index']
* })
* ```
*/
rightJoin: MySqlJoinFn<this, TDynamic, "right">;
/**
* Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
*
* Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User; pets: Pet }[] = await db.select()
* .from(users)
* .innerJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .innerJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId with use index hint
* 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), {
* useIndex: ['pets_owner_id_index']
* })
* ```
*/
innerJoin: MySqlJoinFn<this, TDynamic, "inner">;
/**
* Executes a `full join` operation by combining rows from two tables into a new table.
*
* Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User | null; pets: Pet | null }[] = await db.select()
* .from(users)
* .fullJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number | null; petId: number | null }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .fullJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId with use index hint
* 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), {
* useIndex: ['pets_owner_id_index']
* })
* ```
*/
fullJoin: MySqlJoinFn<this, TDynamic, "full">;
private createSetOperator;
/**
* Adds `union` set operator to the query.
*
* Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
*
* @example
*
* ```ts
* // Select all unique names from customers and users tables
* await db.select({ name: users.name })
* .from(users)
* .union(
* db.select({ name: customers.name }).from(customers)
* );
* // or
* import { union } from 'drizzle-orm/mysql-core'
*
* await union(
* db.select({ name: users.name }).from(users),
* db.select({ name: customers.name }).from(customers)
* );
* ```
*/
union: <TValue extends MySqlSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetMySqlSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => MySqlSelectWithout<this, TDynamic, MySqlSetOperatorExcludedMethods, 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/mysql-core'
*
* await unionAll(
* db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
* );
* ```
*/
unionAll: <TValue extends MySqlSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetMySqlSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => MySqlSelectWithout<this, TDynamic, MySqlSetOperatorExcludedMethods, 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/mysql-core'
*
* await intersect(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
intersect: <TValue extends MySqlSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetMySqlSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => MySqlSelectWithout<this, TDynamic, MySqlSetOperatorExcludedMethods, 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/mysql-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 MySqlSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetMySqlSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => MySqlSelectWithout<this, TDynamic, MySqlSetOperatorExcludedMethods, 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/mysql-core'
*
* await except(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
except: <TValue extends MySqlSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetMySqlSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => MySqlSelectWithout<this, TDynamic, MySqlSetOperatorExcludedMethods, 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/mysql-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 MySqlSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetMySqlSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => MySqlSelectWithout<this, TDynamic, MySqlSetOperatorExcludedMethods, 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): MySqlSelectWithout<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): MySqlSelectWithout<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<MySqlColumn | SQL | SQL.Aliased>): MySqlSelectWithout<this, TDynamic, 'groupBy'>;
groupBy(...columns: (MySqlColumn | SQL | SQL.Aliased)[]): MySqlSelectWithout<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<MySqlColumn | SQL | SQL.Aliased>): MySqlSelectWithout<this, TDynamic, 'orderBy'>;
orderBy(...columns: (MySqlColumn | SQL | SQL.Aliased)[]): MySqlSelectWithout<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): MySqlSelectWithout<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): MySqlSelectWithout<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://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html}
*
* @param strength the lock strength.
* @param config the lock configuration.
*/
for(strength: LockStrength, config?: LockConfig): MySqlSelectWithout<this, TDynamic, 'for'>;
toSQL(): Query;
as<TAlias extends string>(alias: TAlias): SubqueryWithSelection<this['_']['selectedFields'], TAlias>;
$dynamic(): MySqlSelectDynamic<this>;
}
export interface MySqlSelectBase<TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TPreparedQueryHKT extends PreparedQueryHKTBase, 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 MySqlSelectQueryBuilderBase<MySqlSelectHKT, TTableName, TSelection, TSelectMode, TPreparedQueryHKT, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields>, QueryPromise<TResult> {
}
export declare class MySqlSelectBase<TTableName extends string | undefined, TSelection, TSelectMode extends SelectMode, TPreparedQueryHKT extends PreparedQueryHKTBase, 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 MySqlSelectQueryBuilderBase<MySqlSelectHKT, TTableName, TSelection, TSelectMode, TPreparedQueryHKT, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields> {
static readonly [entityKind]: string;
prepare(): MySqlSelectPrepare<this>;
execute: ReturnType<this["prepare"]>["execute"];
private createIterator;
iterator: ReturnType<this["prepare"]>["iterator"];
}
/**
* 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/mysql-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: MySqlCreateSetOperatorFn;
/**
* 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/mysql-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: MySqlCreateSetOperatorFn;
/**
* 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/mysql-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: MySqlCreateSetOperatorFn;
/**
* 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/mysql-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: MySqlCreateSetOperatorFn;
/**
* 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/mysql-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: MySqlCreateSetOperatorFn;
/**
* 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/mysql-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: MySqlCreateSetOperatorFn;

View File

@ -0,0 +1,753 @@
import { entityKind } from "../../entity.js";
import type { MySqlColumn } from "../columns/index.js";
import type { MySqlDialect } from "../dialect.js";
import type { MySqlSession, PreparedQueryHKTBase } from "../session.js";
import type { SubqueryWithSelection } from "../subquery.js";
import { MySqlTable } from "../table.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 { ColumnsSelection, Placeholder, Query } from "../../sql/sql.js";
import { SQL } from "../../sql/sql.js";
import { Subquery } from "../../subquery.js";
import type { ValueOrArray } from "../../utils.js";
import type { IndexBuilder } from "../indexes.js";
import { MySqlViewBase } from "../view-base.js";
import type { CreateMySqlSelectFromBuilderMode, GetMySqlSetOperators, LockConfig, LockStrength, MySqlCreateSetOperatorFn, MySqlJoinFn, MySqlSelectConfig, MySqlSelectDynamic, MySqlSelectHKT, MySqlSelectHKTBase, MySqlSelectPrepare, MySqlSelectWithout, MySqlSetOperatorExcludedMethods, MySqlSetOperatorWithResult, SelectedFields, SetOperatorRightSelect } from "./select.types.js";
export type IndexForHint = IndexBuilder | string;
export type IndexConfig = {
useIndex?: IndexForHint | IndexForHint[];
forceIndex?: IndexForHint | IndexForHint[];
ignoreIndex?: IndexForHint | IndexForHint[];
};
export declare class MySqlSelectBuilder<TSelection extends SelectedFields | undefined, TPreparedQueryHKT extends PreparedQueryHKTBase, TBuilderMode extends 'db' | 'qb' = 'db'> {
static readonly [entityKind]: string;
private fields;
private session;
private dialect;
private withList;
private distinct;
constructor(config: {
fields: TSelection;
session: MySqlSession | undefined;
dialect: MySqlDialect;
withList?: Subquery[];
distinct?: boolean;
});
from<TFrom extends MySqlTable | Subquery | MySqlViewBase | SQL>(source: TFrom, onIndex?: TFrom extends MySqlTable ? IndexConfig : 'Index hint configuration is allowed only for MySqlTable and not for subqueries or views'): CreateMySqlSelectFromBuilderMode<TBuilderMode, GetSelectTableName<TFrom>, TSelection extends undefined ? GetSelectTableSelection<TFrom> : TSelection, TSelection extends undefined ? 'single' : 'partial', TPreparedQueryHKT>;
}
export declare abstract class MySqlSelectQueryBuilderBase<THKT extends MySqlSelectHKTBase, TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TPreparedQueryHKT extends PreparedQueryHKTBase, 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 hkt: THKT;
readonly tableName: TTableName;
readonly selection: TSelection;
readonly selectMode: TSelectMode;
readonly preparedQueryHKT: TPreparedQueryHKT;
readonly nullabilityMap: TNullabilityMap;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
readonly result: TResult;
readonly selectedFields: TSelectedFields;
};
protected config: MySqlSelectConfig;
protected joinsNotNullableMap: Record<string, boolean>;
private tableName;
private isPartialSelect;
protected dialect: MySqlDialect;
constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct, useIndex, forceIndex, ignoreIndex }: {
table: MySqlSelectConfig['table'];
fields: MySqlSelectConfig['fields'];
isPartialSelect: boolean;
session: MySqlSession | undefined;
dialect: MySqlDialect;
withList: Subquery[];
distinct: boolean | undefined;
useIndex?: string[];
forceIndex?: string[];
ignoreIndex?: string[];
});
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))
*
* // Select userId and petId with use index hint
* 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), {
* useIndex: ['pets_owner_id_index']
* })
* ```
*/
leftJoin: MySqlJoinFn<this, TDynamic, "left">;
/**
* Executes a `right join` operation by adding another table to the current query.
*
* Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User | null; pets: Pet }[] = await db.select()
* .from(users)
* .rightJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number | null; petId: number }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .rightJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId with use index hint
* 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), {
* useIndex: ['pets_owner_id_index']
* })
* ```
*/
rightJoin: MySqlJoinFn<this, TDynamic, "right">;
/**
* Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
*
* Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User; pets: Pet }[] = await db.select()
* .from(users)
* .innerJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .innerJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId with use index hint
* 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), {
* useIndex: ['pets_owner_id_index']
* })
* ```
*/
innerJoin: MySqlJoinFn<this, TDynamic, "inner">;
/**
* Executes a `full join` operation by combining rows from two tables into a new table.
*
* Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User | null; pets: Pet | null }[] = await db.select()
* .from(users)
* .fullJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number | null; petId: number | null }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .fullJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId with use index hint
* 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), {
* useIndex: ['pets_owner_id_index']
* })
* ```
*/
fullJoin: MySqlJoinFn<this, TDynamic, "full">;
private createSetOperator;
/**
* Adds `union` set operator to the query.
*
* Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
*
* @example
*
* ```ts
* // Select all unique names from customers and users tables
* await db.select({ name: users.name })
* .from(users)
* .union(
* db.select({ name: customers.name }).from(customers)
* );
* // or
* import { union } from 'drizzle-orm/mysql-core'
*
* await union(
* db.select({ name: users.name }).from(users),
* db.select({ name: customers.name }).from(customers)
* );
* ```
*/
union: <TValue extends MySqlSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetMySqlSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => MySqlSelectWithout<this, TDynamic, MySqlSetOperatorExcludedMethods, 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/mysql-core'
*
* await unionAll(
* db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
* );
* ```
*/
unionAll: <TValue extends MySqlSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetMySqlSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => MySqlSelectWithout<this, TDynamic, MySqlSetOperatorExcludedMethods, 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/mysql-core'
*
* await intersect(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
intersect: <TValue extends MySqlSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetMySqlSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => MySqlSelectWithout<this, TDynamic, MySqlSetOperatorExcludedMethods, 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/mysql-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 MySqlSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetMySqlSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => MySqlSelectWithout<this, TDynamic, MySqlSetOperatorExcludedMethods, 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/mysql-core'
*
* await except(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
except: <TValue extends MySqlSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetMySqlSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => MySqlSelectWithout<this, TDynamic, MySqlSetOperatorExcludedMethods, 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/mysql-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 MySqlSetOperatorWithResult<TResult>>(rightSelection: ((setOperators: GetMySqlSetOperators) => SetOperatorRightSelect<TValue, TResult>) | SetOperatorRightSelect<TValue, TResult>) => MySqlSelectWithout<this, TDynamic, MySqlSetOperatorExcludedMethods, 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): MySqlSelectWithout<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): MySqlSelectWithout<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<MySqlColumn | SQL | SQL.Aliased>): MySqlSelectWithout<this, TDynamic, 'groupBy'>;
groupBy(...columns: (MySqlColumn | SQL | SQL.Aliased)[]): MySqlSelectWithout<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<MySqlColumn | SQL | SQL.Aliased>): MySqlSelectWithout<this, TDynamic, 'orderBy'>;
orderBy(...columns: (MySqlColumn | SQL | SQL.Aliased)[]): MySqlSelectWithout<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): MySqlSelectWithout<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): MySqlSelectWithout<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://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html}
*
* @param strength the lock strength.
* @param config the lock configuration.
*/
for(strength: LockStrength, config?: LockConfig): MySqlSelectWithout<this, TDynamic, 'for'>;
toSQL(): Query;
as<TAlias extends string>(alias: TAlias): SubqueryWithSelection<this['_']['selectedFields'], TAlias>;
$dynamic(): MySqlSelectDynamic<this>;
}
export interface MySqlSelectBase<TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TPreparedQueryHKT extends PreparedQueryHKTBase, 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 MySqlSelectQueryBuilderBase<MySqlSelectHKT, TTableName, TSelection, TSelectMode, TPreparedQueryHKT, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields>, QueryPromise<TResult> {
}
export declare class MySqlSelectBase<TTableName extends string | undefined, TSelection, TSelectMode extends SelectMode, TPreparedQueryHKT extends PreparedQueryHKTBase, 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 MySqlSelectQueryBuilderBase<MySqlSelectHKT, TTableName, TSelection, TSelectMode, TPreparedQueryHKT, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields> {
static readonly [entityKind]: string;
prepare(): MySqlSelectPrepare<this>;
execute: ReturnType<this["prepare"]>["execute"];
private createIterator;
iterator: ReturnType<this["prepare"]>["iterator"];
}
/**
* 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/mysql-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: MySqlCreateSetOperatorFn;
/**
* 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/mysql-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: MySqlCreateSetOperatorFn;
/**
* 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/mysql-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: MySqlCreateSetOperatorFn;
/**
* 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/mysql-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: MySqlCreateSetOperatorFn;
/**
* 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/mysql-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: MySqlCreateSetOperatorFn;
/**
* 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/mysql-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: MySqlCreateSetOperatorFn;

View File

@ -0,0 +1,799 @@
import { entityKind, is } from "../../entity.js";
import { MySqlTable } from "../table.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 { applyMixins, getTableColumns, getTableLikeName, haveSameKeys, orderSelectedFields } from "../../utils.js";
import { ViewBaseConfig } from "../../view-common.js";
import { convertIndexToString, toArray } from "../utils.js";
import { MySqlViewBase } from "../view-base.js";
class MySqlSelectBuilder {
static [entityKind] = "MySqlSelectBuilder";
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;
}
from(source, onIndex) {
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, MySqlViewBase)) {
fields = source[ViewBaseConfig].selectedFields;
} else if (is(source, SQL)) {
fields = {};
} else {
fields = getTableColumns(source);
}
let useIndex = [];
let forceIndex = [];
let ignoreIndex = [];
if (is(source, MySqlTable) && onIndex && typeof onIndex !== "string") {
if (onIndex.useIndex) {
useIndex = convertIndexToString(toArray(onIndex.useIndex));
}
if (onIndex.forceIndex) {
forceIndex = convertIndexToString(toArray(onIndex.forceIndex));
}
if (onIndex.ignoreIndex) {
ignoreIndex = convertIndexToString(toArray(onIndex.ignoreIndex));
}
}
return new MySqlSelectBase(
{
table: source,
fields,
isPartialSelect,
session: this.session,
dialect: this.dialect,
withList: this.withList,
distinct: this.distinct,
useIndex,
forceIndex,
ignoreIndex
}
);
}
}
class MySqlSelectQueryBuilderBase extends TypedQueryBuilder {
static [entityKind] = "MySqlSelectQueryBuilder";
_;
config;
joinsNotNullableMap;
tableName;
isPartialSelect;
/** @internal */
session;
dialect;
constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct, useIndex, forceIndex, ignoreIndex }) {
super();
this.config = {
withList,
table,
fields: { ...fields },
distinct,
setOperators: [],
useIndex,
forceIndex,
ignoreIndex
};
this.isPartialSelect = isPartialSelect;
this.session = session;
this.dialect = dialect;
this._ = {
selectedFields: fields
};
this.tableName = getTableLikeName(table);
this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
}
createJoin(joinType) {
return (table, on, onIndex) => {
const baseTableName = this.tableName;
const tableName = getTableLikeName(table);
if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) {
throw new Error(`Alias "${tableName}" is already used in this query`);
}
if (!this.isPartialSelect) {
if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") {
this.config.fields = {
[baseTableName]: this.config.fields
};
}
if (typeof tableName === "string" && !is(table, SQL)) {
const selection = is(table, Subquery) ? table._.selectedFields : is(table, View) ? table[ViewBaseConfig].selectedFields : table[Table.Symbol.Columns];
this.config.fields[tableName] = selection;
}
}
if (typeof on === "function") {
on = on(
new Proxy(
this.config.fields,
new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
)
);
}
if (!this.config.joins) {
this.config.joins = [];
}
let useIndex = [];
let forceIndex = [];
let ignoreIndex = [];
if (is(table, MySqlTable) && onIndex && typeof onIndex !== "string") {
if (onIndex.useIndex) {
useIndex = convertIndexToString(toArray(onIndex.useIndex));
}
if (onIndex.forceIndex) {
forceIndex = convertIndexToString(toArray(onIndex.forceIndex));
}
if (onIndex.ignoreIndex) {
ignoreIndex = convertIndexToString(toArray(onIndex.ignoreIndex));
}
}
this.config.joins.push({ on, table, joinType, alias: tableName, useIndex, forceIndex, ignoreIndex });
if (typeof tableName === "string") {
switch (joinType) {
case "left": {
this.joinsNotNullableMap[tableName] = false;
break;
}
case "right": {
this.joinsNotNullableMap = Object.fromEntries(
Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
);
this.joinsNotNullableMap[tableName] = true;
break;
}
case "inner": {
this.joinsNotNullableMap[tableName] = true;
break;
}
case "full": {
this.joinsNotNullableMap = Object.fromEntries(
Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
);
this.joinsNotNullableMap[tableName] = false;
break;
}
}
}
return this;
};
}
/**
* Executes a `left join` operation by adding another table to the current query.
*
* Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User; pets: Pet | null }[] = await db.select()
* .from(users)
* .leftJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number | null }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .leftJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId with use index hint
* 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), {
* useIndex: ['pets_owner_id_index']
* })
* ```
*/
leftJoin = this.createJoin("left");
/**
* Executes a `right join` operation by adding another table to the current query.
*
* Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User | null; pets: Pet }[] = await db.select()
* .from(users)
* .rightJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number | null; petId: number }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .rightJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId with use index hint
* 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), {
* useIndex: ['pets_owner_id_index']
* })
* ```
*/
rightJoin = this.createJoin("right");
/**
* Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
*
* Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User; pets: Pet }[] = await db.select()
* .from(users)
* .innerJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .innerJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId with use index hint
* 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), {
* useIndex: ['pets_owner_id_index']
* })
* ```
*/
innerJoin = this.createJoin("inner");
/**
* Executes a `full join` operation by combining rows from two tables into a new table.
*
* Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User | null; pets: Pet | null }[] = await db.select()
* .from(users)
* .fullJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number | null; petId: number | null }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .fullJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId with use index hint
* 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), {
* useIndex: ['pets_owner_id_index']
* })
* ```
*/
fullJoin = this.createJoin("full");
createSetOperator(type, isAll) {
return (rightSelection) => {
const rightSelect = typeof rightSelection === "function" ? rightSelection(getMySqlSetOperators()) : 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/mysql-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/mysql-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/mysql-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/mysql-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/mysql-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/mysql-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://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html}
*
* @param strength the lock strength.
* @param config the lock configuration.
*/
for(strength, config = {}) {
this.config.lockingClause = { strength, config };
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildSelectQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
as(alias) {
return new Proxy(
new Subquery(this.getSQL(), this.config.fields, alias),
new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
);
}
/** @internal */
getSelectedFields() {
return new Proxy(
this.config.fields,
new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
);
}
$dynamic() {
return this;
}
}
class MySqlSelectBase extends MySqlSelectQueryBuilderBase {
static [entityKind] = "MySqlSelect";
prepare() {
if (!this.session) {
throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
}
const fieldsList = orderSelectedFields(this.config.fields);
const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), fieldsList);
query.joinsNotNullableMap = this.joinsNotNullableMap;
return query;
}
execute = (placeholderValues) => {
return this.prepare().execute(placeholderValues);
};
createIterator = () => {
const self = this;
return async function* (placeholderValues) {
yield* self.prepare().iterator(placeholderValues);
};
};
iterator = this.createIterator();
}
applyMixins(MySqlSelectBase, [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 getMySqlSetOperators = () => ({
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 {
MySqlSelectBase,
MySqlSelectBuilder,
MySqlSelectQueryBuilderBase,
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,144 @@
import type { MySqlColumn } from "../columns/index.cjs";
import type { MySqlTable, MySqlTableWithColumns } from "../table.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, View } from "../../sql/sql.cjs";
import type { Subquery } from "../../subquery.cjs";
import type { Table, UpdateTableConfig } from "../../table.cjs";
import type { Assume, ValidateShape } from "../../utils.cjs";
import type { MySqlPreparedQueryConfig, PreparedQueryHKTBase, PreparedQueryKind } from "../session.cjs";
import type { MySqlViewBase } from "../view-base.cjs";
import type { MySqlViewWithSelection } from "../view.cjs";
import type { IndexConfig, MySqlSelectBase, MySqlSelectQueryBuilderBase } from "./select.cjs";
export interface MySqlSelectJoinConfig {
on: SQL | undefined;
table: MySqlTable | Subquery | MySqlViewBase | SQL;
alias: string | undefined;
joinType: JoinType;
lateral?: boolean;
useIndex?: string[];
forceIndex?: string[];
ignoreIndex?: string[];
}
export type BuildAliasTable<TTable extends MySqlTable | View, TAlias extends string> = TTable extends Table ? MySqlTableWithColumns<UpdateTableConfig<TTable['_']['config'], {
name: TAlias;
columns: MapColumnsToTableAlias<TTable['_']['columns'], TAlias, 'mysql'>;
}>> : TTable extends View ? MySqlViewWithSelection<TAlias, TTable['_']['existing'], MapColumnsToTableAlias<TTable['_']['selectedFields'], TAlias, 'mysql'>> : never;
export interface MySqlSelectConfig {
withList?: Subquery[];
fields: Record<string, unknown>;
fieldsFlat?: SelectedFieldsOrdered;
where?: SQL;
having?: SQL;
table: MySqlTable | Subquery | MySqlViewBase | SQL;
limit?: number | Placeholder;
offset?: number | Placeholder;
joins?: MySqlSelectJoinConfig[];
orderBy?: (MySqlColumn | SQL | SQL.Aliased)[];
groupBy?: (MySqlColumn | SQL | SQL.Aliased)[];
lockingClause?: {
strength: LockStrength;
config: LockConfig;
};
distinct?: boolean;
setOperators: {
rightSelect: TypedQueryBuilder<any, any>;
type: SetOperator;
isAll: boolean;
orderBy?: (MySqlColumn | SQL | SQL.Aliased)[];
limit?: number | Placeholder;
offset?: number | Placeholder;
}[];
useIndex?: string[];
forceIndex?: string[];
ignoreIndex?: string[];
}
export type MySqlJoin<T extends AnyMySqlSelectQueryBuilder, TDynamic extends boolean, TJoinType extends JoinType, TJoinedTable extends MySqlTable | Subquery | MySqlViewBase | SQL, TJoinedName extends GetSelectTableName<TJoinedTable> = GetSelectTableName<TJoinedTable>> = T extends any ? MySqlSelectWithout<MySqlSelectKind<T['_']['hkt'], T['_']['tableName'], AppendToResult<T['_']['tableName'], T['_']['selection'], TJoinedName, TJoinedTable extends MySqlTable ? TJoinedTable['_']['columns'] : TJoinedTable extends Subquery ? Assume<TJoinedTable['_']['selectedFields'], SelectedFields> : never, T['_']['selectMode']>, T['_']['selectMode'] extends 'partial' ? T['_']['selectMode'] : 'multiple', T['_']['preparedQueryHKT'], AppendToNullabilityMap<T['_']['nullabilityMap'], TJoinedName, TJoinType>, TDynamic, T['_']['excludedMethods']>, TDynamic, T['_']['excludedMethods']> : never;
export type MySqlJoinFn<T extends AnyMySqlSelectQueryBuilder, TDynamic extends boolean, TJoinType extends JoinType> = <TJoinedTable extends MySqlTable | Subquery | MySqlViewBase | SQL, TJoinedName extends GetSelectTableName<TJoinedTable> = GetSelectTableName<TJoinedTable>>(table: TJoinedTable, on: ((aliases: T['_']['selection']) => SQL | undefined) | SQL | undefined, onIndex?: TJoinedTable extends MySqlTable ? IndexConfig : 'Index hint configuration is allowed only for MySqlTable and not for subqueries or views') => MySqlJoin<T, TDynamic, TJoinType, TJoinedTable, TJoinedName>;
export type SelectedFieldsFlat = SelectedFieldsFlatBase<MySqlColumn>;
export type SelectedFields = SelectedFieldsBase<MySqlColumn, MySqlTable>;
export type SelectedFieldsOrdered = SelectedFieldsOrderedBase<MySqlColumn>;
export type LockStrength = 'update' | 'share';
export type LockConfig = {
noWait: true;
skipLocked?: undefined;
} | {
noWait?: undefined;
skipLocked: true;
} | {
noWait?: undefined;
skipLocked?: undefined;
};
export interface MySqlSelectHKTBase {
tableName: string | undefined;
selection: unknown;
selectMode: SelectMode;
preparedQueryHKT: unknown;
nullabilityMap: unknown;
dynamic: boolean;
excludedMethods: string;
result: unknown;
selectedFields: unknown;
_type: unknown;
}
export type MySqlSelectKind<T extends MySqlSelectHKTBase, TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TPreparedQueryHKT extends PreparedQueryHKTBase, 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;
preparedQueryHKT: TPreparedQueryHKT;
nullabilityMap: TNullabilityMap;
dynamic: TDynamic;
excludedMethods: TExcludedMethods;
result: TResult;
selectedFields: TSelectedFields;
})['_type'];
export interface MySqlSelectQueryBuilderHKT extends MySqlSelectHKTBase {
_type: MySqlSelectQueryBuilderBase<MySqlSelectQueryBuilderHKT, this['tableName'], Assume<this['selection'], ColumnsSelection>, this['selectMode'], Assume<this['preparedQueryHKT'], PreparedQueryHKTBase>, Assume<this['nullabilityMap'], Record<string, JoinNullability>>, this['dynamic'], this['excludedMethods'], Assume<this['result'], any[]>, Assume<this['selectedFields'], ColumnsSelection>>;
}
export interface MySqlSelectHKT extends MySqlSelectHKTBase {
_type: MySqlSelectBase<this['tableName'], Assume<this['selection'], ColumnsSelection>, this['selectMode'], Assume<this['preparedQueryHKT'], PreparedQueryHKTBase>, Assume<this['nullabilityMap'], Record<string, JoinNullability>>, this['dynamic'], this['excludedMethods'], Assume<this['result'], any[]>, Assume<this['selectedFields'], ColumnsSelection>>;
}
export type MySqlSetOperatorExcludedMethods = 'where' | 'having' | 'groupBy' | 'session' | 'leftJoin' | 'rightJoin' | 'innerJoin' | 'fullJoin' | 'for';
export type MySqlSelectWithout<T extends AnyMySqlSelectQueryBuilder, TDynamic extends boolean, K extends keyof T & string, TResetExcluded extends boolean = false> = TDynamic extends true ? T : Omit<MySqlSelectKind<T['_']['hkt'], T['_']['tableName'], T['_']['selection'], T['_']['selectMode'], T['_']['preparedQueryHKT'], T['_']['nullabilityMap'], TDynamic, TResetExcluded extends true ? K : T['_']['excludedMethods'] | K, T['_']['result'], T['_']['selectedFields']>, TResetExcluded extends true ? K : T['_']['excludedMethods'] | K>;
export type MySqlSelectPrepare<T extends AnyMySqlSelect> = PreparedQueryKind<T['_']['preparedQueryHKT'], MySqlPreparedQueryConfig & {
execute: T['_']['result'];
iterator: T['_']['result'][number];
}, true>;
export type MySqlSelectDynamic<T extends AnyMySqlSelectQueryBuilder> = MySqlSelectKind<T['_']['hkt'], T['_']['tableName'], T['_']['selection'], T['_']['selectMode'], T['_']['preparedQueryHKT'], T['_']['nullabilityMap'], true, never, T['_']['result'], T['_']['selectedFields']>;
export type CreateMySqlSelectFromBuilderMode<TBuilderMode extends 'db' | 'qb', TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TPreparedQueryHKT extends PreparedQueryHKTBase> = TBuilderMode extends 'db' ? MySqlSelectBase<TTableName, TSelection, TSelectMode, TPreparedQueryHKT> : MySqlSelectQueryBuilderBase<MySqlSelectQueryBuilderHKT, TTableName, TSelection, TSelectMode, TPreparedQueryHKT>;
export type MySqlSelectQueryBuilder<THKT extends MySqlSelectHKTBase = MySqlSelectQueryBuilderHKT, TTableName extends string | undefined = string | undefined, TSelection extends ColumnsSelection = ColumnsSelection, TSelectMode extends SelectMode = SelectMode, TPreparedQueryHKT extends PreparedQueryHKTBase = PreparedQueryHKTBase, TNullabilityMap extends Record<string, JoinNullability> = Record<string, JoinNullability>, TResult extends any[] = unknown[], TSelectedFields extends ColumnsSelection = ColumnsSelection> = MySqlSelectQueryBuilderBase<THKT, TTableName, TSelection, TSelectMode, TPreparedQueryHKT, TNullabilityMap, true, never, TResult, TSelectedFields>;
export type AnyMySqlSelectQueryBuilder = MySqlSelectQueryBuilderBase<any, any, any, any, any, any, any, any, any>;
export type AnyMySqlSetOperatorInterface = MySqlSetOperatorInterface<any, any, any, any, any, any, any, any, any>;
export interface MySqlSetOperatorInterface<TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TPreparedQueryHKT extends PreparedQueryHKTBase = PreparedQueryHKTBase, 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: MySqlSelectHKT;
readonly tableName: TTableName;
readonly selection: TSelection;
readonly selectMode: TSelectMode;
readonly preparedQueryHKT: TPreparedQueryHKT;
readonly nullabilityMap: TNullabilityMap;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
readonly result: TResult;
readonly selectedFields: TSelectedFields;
};
}
export type MySqlSetOperatorWithResult<TResult extends any[]> = MySqlSetOperatorInterface<any, any, any, any, any, any, any, TResult, any>;
export type MySqlSelect<TTableName extends string | undefined = string | undefined, TSelection extends ColumnsSelection = Record<string, any>, TSelectMode extends SelectMode = SelectMode, TNullabilityMap extends Record<string, JoinNullability> = Record<string, JoinNullability>> = MySqlSelectBase<TTableName, TSelection, TSelectMode, PreparedQueryHKTBase, TNullabilityMap, true, never>;
export type AnyMySqlSelect = MySqlSelectBase<any, any, any, any, any, any, any, any>;
export type MySqlSetOperator<TTableName extends string | undefined = string | undefined, TSelection extends ColumnsSelection = Record<string, any>, TSelectMode extends SelectMode = SelectMode, TPreparedQueryHKT extends PreparedQueryHKTBase = PreparedQueryHKTBase, TNullabilityMap extends Record<string, JoinNullability> = Record<string, JoinNullability>> = MySqlSelectBase<TTableName, TSelection, TSelectMode, TPreparedQueryHKT, TNullabilityMap, true, MySqlSetOperatorExcludedMethods>;
export type SetOperatorRightSelect<TValue extends MySqlSetOperatorWithResult<TResult>, TResult extends any[]> = TValue extends MySqlSetOperatorInterface<any, any, any, any, any, any, any, infer TValueResult, any> ? ValidateShape<TValueResult[number], TResult[number], TypedQueryBuilder<any, TValueResult>> : TValue;
export type SetOperatorRestSelect<TValue extends readonly MySqlSetOperatorWithResult<TResult>[], TResult extends any[]> = TValue extends [infer First, ...infer Rest] ? First extends MySqlSetOperatorInterface<any, any, any, any, any, any, any, infer TValueResult, any> ? Rest extends AnyMySqlSetOperatorInterface[] ? [
ValidateShape<TValueResult[number], TResult[number], TypedQueryBuilder<any, TValueResult>>,
...SetOperatorRestSelect<Rest, TResult>
] : ValidateShape<TValueResult[number], TResult[number], TypedQueryBuilder<any, TValueResult>[]> : never : TValue;
export type MySqlCreateSetOperatorFn = <TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TValue extends MySqlSetOperatorWithResult<TResult>, TRest extends MySqlSetOperatorWithResult<TResult>[], TPreparedQueryHKT extends PreparedQueryHKTBase = PreparedQueryHKTBase, 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: MySqlSetOperatorInterface<TTableName, TSelection, TSelectMode, TPreparedQueryHKT, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields>, rightSelect: SetOperatorRightSelect<TValue, TResult>, ...restSelects: SetOperatorRestSelect<TRest, TResult>) => MySqlSelectWithout<MySqlSelectBase<TTableName, TSelection, TSelectMode, TPreparedQueryHKT, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields>, false, MySqlSetOperatorExcludedMethods, true>;
export type GetMySqlSetOperators = {
union: MySqlCreateSetOperatorFn;
intersect: MySqlCreateSetOperatorFn;
except: MySqlCreateSetOperatorFn;
unionAll: MySqlCreateSetOperatorFn;
intersectAll: MySqlCreateSetOperatorFn;
exceptAll: MySqlCreateSetOperatorFn;
};

View File

@ -0,0 +1,144 @@
import type { MySqlColumn } from "../columns/index.js";
import type { MySqlTable, MySqlTableWithColumns } from "../table.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, View } from "../../sql/sql.js";
import type { Subquery } from "../../subquery.js";
import type { Table, UpdateTableConfig } from "../../table.js";
import type { Assume, ValidateShape } from "../../utils.js";
import type { MySqlPreparedQueryConfig, PreparedQueryHKTBase, PreparedQueryKind } from "../session.js";
import type { MySqlViewBase } from "../view-base.js";
import type { MySqlViewWithSelection } from "../view.js";
import type { IndexConfig, MySqlSelectBase, MySqlSelectQueryBuilderBase } from "./select.js";
export interface MySqlSelectJoinConfig {
on: SQL | undefined;
table: MySqlTable | Subquery | MySqlViewBase | SQL;
alias: string | undefined;
joinType: JoinType;
lateral?: boolean;
useIndex?: string[];
forceIndex?: string[];
ignoreIndex?: string[];
}
export type BuildAliasTable<TTable extends MySqlTable | View, TAlias extends string> = TTable extends Table ? MySqlTableWithColumns<UpdateTableConfig<TTable['_']['config'], {
name: TAlias;
columns: MapColumnsToTableAlias<TTable['_']['columns'], TAlias, 'mysql'>;
}>> : TTable extends View ? MySqlViewWithSelection<TAlias, TTable['_']['existing'], MapColumnsToTableAlias<TTable['_']['selectedFields'], TAlias, 'mysql'>> : never;
export interface MySqlSelectConfig {
withList?: Subquery[];
fields: Record<string, unknown>;
fieldsFlat?: SelectedFieldsOrdered;
where?: SQL;
having?: SQL;
table: MySqlTable | Subquery | MySqlViewBase | SQL;
limit?: number | Placeholder;
offset?: number | Placeholder;
joins?: MySqlSelectJoinConfig[];
orderBy?: (MySqlColumn | SQL | SQL.Aliased)[];
groupBy?: (MySqlColumn | SQL | SQL.Aliased)[];
lockingClause?: {
strength: LockStrength;
config: LockConfig;
};
distinct?: boolean;
setOperators: {
rightSelect: TypedQueryBuilder<any, any>;
type: SetOperator;
isAll: boolean;
orderBy?: (MySqlColumn | SQL | SQL.Aliased)[];
limit?: number | Placeholder;
offset?: number | Placeholder;
}[];
useIndex?: string[];
forceIndex?: string[];
ignoreIndex?: string[];
}
export type MySqlJoin<T extends AnyMySqlSelectQueryBuilder, TDynamic extends boolean, TJoinType extends JoinType, TJoinedTable extends MySqlTable | Subquery | MySqlViewBase | SQL, TJoinedName extends GetSelectTableName<TJoinedTable> = GetSelectTableName<TJoinedTable>> = T extends any ? MySqlSelectWithout<MySqlSelectKind<T['_']['hkt'], T['_']['tableName'], AppendToResult<T['_']['tableName'], T['_']['selection'], TJoinedName, TJoinedTable extends MySqlTable ? TJoinedTable['_']['columns'] : TJoinedTable extends Subquery ? Assume<TJoinedTable['_']['selectedFields'], SelectedFields> : never, T['_']['selectMode']>, T['_']['selectMode'] extends 'partial' ? T['_']['selectMode'] : 'multiple', T['_']['preparedQueryHKT'], AppendToNullabilityMap<T['_']['nullabilityMap'], TJoinedName, TJoinType>, TDynamic, T['_']['excludedMethods']>, TDynamic, T['_']['excludedMethods']> : never;
export type MySqlJoinFn<T extends AnyMySqlSelectQueryBuilder, TDynamic extends boolean, TJoinType extends JoinType> = <TJoinedTable extends MySqlTable | Subquery | MySqlViewBase | SQL, TJoinedName extends GetSelectTableName<TJoinedTable> = GetSelectTableName<TJoinedTable>>(table: TJoinedTable, on: ((aliases: T['_']['selection']) => SQL | undefined) | SQL | undefined, onIndex?: TJoinedTable extends MySqlTable ? IndexConfig : 'Index hint configuration is allowed only for MySqlTable and not for subqueries or views') => MySqlJoin<T, TDynamic, TJoinType, TJoinedTable, TJoinedName>;
export type SelectedFieldsFlat = SelectedFieldsFlatBase<MySqlColumn>;
export type SelectedFields = SelectedFieldsBase<MySqlColumn, MySqlTable>;
export type SelectedFieldsOrdered = SelectedFieldsOrderedBase<MySqlColumn>;
export type LockStrength = 'update' | 'share';
export type LockConfig = {
noWait: true;
skipLocked?: undefined;
} | {
noWait?: undefined;
skipLocked: true;
} | {
noWait?: undefined;
skipLocked?: undefined;
};
export interface MySqlSelectHKTBase {
tableName: string | undefined;
selection: unknown;
selectMode: SelectMode;
preparedQueryHKT: unknown;
nullabilityMap: unknown;
dynamic: boolean;
excludedMethods: string;
result: unknown;
selectedFields: unknown;
_type: unknown;
}
export type MySqlSelectKind<T extends MySqlSelectHKTBase, TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TPreparedQueryHKT extends PreparedQueryHKTBase, 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;
preparedQueryHKT: TPreparedQueryHKT;
nullabilityMap: TNullabilityMap;
dynamic: TDynamic;
excludedMethods: TExcludedMethods;
result: TResult;
selectedFields: TSelectedFields;
})['_type'];
export interface MySqlSelectQueryBuilderHKT extends MySqlSelectHKTBase {
_type: MySqlSelectQueryBuilderBase<MySqlSelectQueryBuilderHKT, this['tableName'], Assume<this['selection'], ColumnsSelection>, this['selectMode'], Assume<this['preparedQueryHKT'], PreparedQueryHKTBase>, Assume<this['nullabilityMap'], Record<string, JoinNullability>>, this['dynamic'], this['excludedMethods'], Assume<this['result'], any[]>, Assume<this['selectedFields'], ColumnsSelection>>;
}
export interface MySqlSelectHKT extends MySqlSelectHKTBase {
_type: MySqlSelectBase<this['tableName'], Assume<this['selection'], ColumnsSelection>, this['selectMode'], Assume<this['preparedQueryHKT'], PreparedQueryHKTBase>, Assume<this['nullabilityMap'], Record<string, JoinNullability>>, this['dynamic'], this['excludedMethods'], Assume<this['result'], any[]>, Assume<this['selectedFields'], ColumnsSelection>>;
}
export type MySqlSetOperatorExcludedMethods = 'where' | 'having' | 'groupBy' | 'session' | 'leftJoin' | 'rightJoin' | 'innerJoin' | 'fullJoin' | 'for';
export type MySqlSelectWithout<T extends AnyMySqlSelectQueryBuilder, TDynamic extends boolean, K extends keyof T & string, TResetExcluded extends boolean = false> = TDynamic extends true ? T : Omit<MySqlSelectKind<T['_']['hkt'], T['_']['tableName'], T['_']['selection'], T['_']['selectMode'], T['_']['preparedQueryHKT'], T['_']['nullabilityMap'], TDynamic, TResetExcluded extends true ? K : T['_']['excludedMethods'] | K, T['_']['result'], T['_']['selectedFields']>, TResetExcluded extends true ? K : T['_']['excludedMethods'] | K>;
export type MySqlSelectPrepare<T extends AnyMySqlSelect> = PreparedQueryKind<T['_']['preparedQueryHKT'], MySqlPreparedQueryConfig & {
execute: T['_']['result'];
iterator: T['_']['result'][number];
}, true>;
export type MySqlSelectDynamic<T extends AnyMySqlSelectQueryBuilder> = MySqlSelectKind<T['_']['hkt'], T['_']['tableName'], T['_']['selection'], T['_']['selectMode'], T['_']['preparedQueryHKT'], T['_']['nullabilityMap'], true, never, T['_']['result'], T['_']['selectedFields']>;
export type CreateMySqlSelectFromBuilderMode<TBuilderMode extends 'db' | 'qb', TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TPreparedQueryHKT extends PreparedQueryHKTBase> = TBuilderMode extends 'db' ? MySqlSelectBase<TTableName, TSelection, TSelectMode, TPreparedQueryHKT> : MySqlSelectQueryBuilderBase<MySqlSelectQueryBuilderHKT, TTableName, TSelection, TSelectMode, TPreparedQueryHKT>;
export type MySqlSelectQueryBuilder<THKT extends MySqlSelectHKTBase = MySqlSelectQueryBuilderHKT, TTableName extends string | undefined = string | undefined, TSelection extends ColumnsSelection = ColumnsSelection, TSelectMode extends SelectMode = SelectMode, TPreparedQueryHKT extends PreparedQueryHKTBase = PreparedQueryHKTBase, TNullabilityMap extends Record<string, JoinNullability> = Record<string, JoinNullability>, TResult extends any[] = unknown[], TSelectedFields extends ColumnsSelection = ColumnsSelection> = MySqlSelectQueryBuilderBase<THKT, TTableName, TSelection, TSelectMode, TPreparedQueryHKT, TNullabilityMap, true, never, TResult, TSelectedFields>;
export type AnyMySqlSelectQueryBuilder = MySqlSelectQueryBuilderBase<any, any, any, any, any, any, any, any, any>;
export type AnyMySqlSetOperatorInterface = MySqlSetOperatorInterface<any, any, any, any, any, any, any, any, any>;
export interface MySqlSetOperatorInterface<TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TPreparedQueryHKT extends PreparedQueryHKTBase = PreparedQueryHKTBase, 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: MySqlSelectHKT;
readonly tableName: TTableName;
readonly selection: TSelection;
readonly selectMode: TSelectMode;
readonly preparedQueryHKT: TPreparedQueryHKT;
readonly nullabilityMap: TNullabilityMap;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
readonly result: TResult;
readonly selectedFields: TSelectedFields;
};
}
export type MySqlSetOperatorWithResult<TResult extends any[]> = MySqlSetOperatorInterface<any, any, any, any, any, any, any, TResult, any>;
export type MySqlSelect<TTableName extends string | undefined = string | undefined, TSelection extends ColumnsSelection = Record<string, any>, TSelectMode extends SelectMode = SelectMode, TNullabilityMap extends Record<string, JoinNullability> = Record<string, JoinNullability>> = MySqlSelectBase<TTableName, TSelection, TSelectMode, PreparedQueryHKTBase, TNullabilityMap, true, never>;
export type AnyMySqlSelect = MySqlSelectBase<any, any, any, any, any, any, any, any>;
export type MySqlSetOperator<TTableName extends string | undefined = string | undefined, TSelection extends ColumnsSelection = Record<string, any>, TSelectMode extends SelectMode = SelectMode, TPreparedQueryHKT extends PreparedQueryHKTBase = PreparedQueryHKTBase, TNullabilityMap extends Record<string, JoinNullability> = Record<string, JoinNullability>> = MySqlSelectBase<TTableName, TSelection, TSelectMode, TPreparedQueryHKT, TNullabilityMap, true, MySqlSetOperatorExcludedMethods>;
export type SetOperatorRightSelect<TValue extends MySqlSetOperatorWithResult<TResult>, TResult extends any[]> = TValue extends MySqlSetOperatorInterface<any, any, any, any, any, any, any, infer TValueResult, any> ? ValidateShape<TValueResult[number], TResult[number], TypedQueryBuilder<any, TValueResult>> : TValue;
export type SetOperatorRestSelect<TValue extends readonly MySqlSetOperatorWithResult<TResult>[], TResult extends any[]> = TValue extends [infer First, ...infer Rest] ? First extends MySqlSetOperatorInterface<any, any, any, any, any, any, any, infer TValueResult, any> ? Rest extends AnyMySqlSetOperatorInterface[] ? [
ValidateShape<TValueResult[number], TResult[number], TypedQueryBuilder<any, TValueResult>>,
...SetOperatorRestSelect<Rest, TResult>
] : ValidateShape<TValueResult[number], TResult[number], TypedQueryBuilder<any, TValueResult>[]> : never : TValue;
export type MySqlCreateSetOperatorFn = <TTableName extends string | undefined, TSelection extends ColumnsSelection, TSelectMode extends SelectMode, TValue extends MySqlSetOperatorWithResult<TResult>, TRest extends MySqlSetOperatorWithResult<TResult>[], TPreparedQueryHKT extends PreparedQueryHKTBase = PreparedQueryHKTBase, 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: MySqlSetOperatorInterface<TTableName, TSelection, TSelectMode, TPreparedQueryHKT, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields>, rightSelect: SetOperatorRightSelect<TValue, TResult>, ...restSelects: SetOperatorRestSelect<TRest, TResult>) => MySqlSelectWithout<MySqlSelectBase<TTableName, TSelection, TSelectMode, TPreparedQueryHKT, TNullabilityMap, TDynamic, TExcludedMethods, TResult, TSelectedFields>, false, MySqlSetOperatorExcludedMethods, true>;
export type GetMySqlSetOperators = {
union: MySqlCreateSetOperatorFn;
intersect: MySqlCreateSetOperatorFn;
except: MySqlCreateSetOperatorFn;
unionAll: MySqlCreateSetOperatorFn;
intersectAll: MySqlCreateSetOperatorFn;
exceptAll: MySqlCreateSetOperatorFn;
};

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,141 @@
"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, {
MySqlUpdateBase: () => MySqlUpdateBase,
MySqlUpdateBuilder: () => MySqlUpdateBuilder
});
module.exports = __toCommonJS(update_exports);
var import_entity = require("../../entity.cjs");
var import_query_promise = require("../../query-promise.cjs");
var import_selection_proxy = require("../../selection-proxy.cjs");
var import_table = require("../../table.cjs");
var import_utils = require("../../utils.cjs");
class MySqlUpdateBuilder {
constructor(table, session, dialect, withList) {
this.table = table;
this.session = session;
this.dialect = dialect;
this.withList = withList;
}
static [import_entity.entityKind] = "MySqlUpdateBuilder";
set(values) {
return new MySqlUpdateBase(this.table, (0, import_utils.mapUpdateSet)(this.table, values), this.session, this.dialect, this.withList);
}
}
class MySqlUpdateBase extends import_query_promise.QueryPromise {
constructor(table, set, session, dialect, withList) {
super();
this.session = session;
this.dialect = dialect;
this.config = { set, table, withList };
}
static [import_entity.entityKind] = "MySqlUpdate";
config;
/**
* 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
* db.update(cars).set({ color: 'red' })
* .where(eq(cars.color, 'green'));
* // or
* 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
* 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
* db.update(cars).set({ color: 'red' })
* .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where) {
this.config.where = where;
return this;
}
orderBy(...columns) {
if (typeof columns[0] === "function") {
const orderBy = columns[0](
new Proxy(
this.config.table[import_table.Table.Symbol.Columns],
new import_selection_proxy.SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
)
);
const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
this.config.orderBy = orderByArray;
} else {
const orderByArray = columns;
this.config.orderBy = orderByArray;
}
return this;
}
limit(limit) {
this.config.limit = limit;
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildUpdateQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
prepare() {
return this.session.prepareQuery(
this.dialect.sqlToQuery(this.getSQL()),
this.config.returning
);
}
execute = (placeholderValues) => {
return this.prepare().execute(placeholderValues);
};
createIterator = () => {
const self = this;
return async function* (placeholderValues) {
yield* self.prepare().iterator(placeholderValues);
};
};
iterator = this.createIterator();
$dynamic() {
return this;
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
MySqlUpdateBase,
MySqlUpdateBuilder
});
//# sourceMappingURL=update.cjs.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,102 @@
import type { GetColumnData } from "../../column.cjs";
import { entityKind } from "../../entity.cjs";
import type { MySqlDialect } from "../dialect.cjs";
import type { AnyMySqlQueryResultHKT, MySqlPreparedQueryConfig, MySqlQueryResultHKT, MySqlQueryResultKind, MySqlSession, PreparedQueryHKTBase, PreparedQueryKind } from "../session.cjs";
import type { MySqlTable } from "../table.cjs";
import { QueryPromise } from "../../query-promise.cjs";
import type { Placeholder, Query, SQL, SQLWrapper } from "../../sql/sql.cjs";
import type { Subquery } from "../../subquery.cjs";
import { type UpdateSet, type ValueOrArray } from "../../utils.cjs";
import type { MySqlColumn } from "../columns/common.cjs";
import type { SelectedFieldsOrdered } from "./select.types.cjs";
export interface MySqlUpdateConfig {
where?: SQL | undefined;
limit?: number | Placeholder;
orderBy?: (MySqlColumn | SQL | SQL.Aliased)[];
set: UpdateSet;
table: MySqlTable;
returning?: SelectedFieldsOrdered;
withList?: Subquery[];
}
export type MySqlUpdateSetSource<TTable extends MySqlTable> = {
[Key in keyof TTable['$inferInsert']]?: GetColumnData<TTable['_']['columns'][Key], 'query'> | SQL | undefined;
} & {};
export declare class MySqlUpdateBuilder<TTable extends MySqlTable, TQueryResult extends MySqlQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase> {
private table;
private session;
private dialect;
private withList?;
static readonly [entityKind]: string;
readonly _: {
readonly table: TTable;
};
constructor(table: TTable, session: MySqlSession, dialect: MySqlDialect, withList?: Subquery[] | undefined);
set(values: MySqlUpdateSetSource<TTable>): MySqlUpdateBase<TTable, TQueryResult, TPreparedQueryHKT>;
}
export type MySqlUpdateWithout<T extends AnyMySqlUpdateBase, TDynamic extends boolean, K extends keyof T & string> = TDynamic extends true ? T : Omit<MySqlUpdateBase<T['_']['table'], T['_']['queryResult'], T['_']['preparedQueryHKT'], TDynamic, T['_']['excludedMethods'] | K>, T['_']['excludedMethods'] | K>;
export type MySqlUpdatePrepare<T extends AnyMySqlUpdateBase> = PreparedQueryKind<T['_']['preparedQueryHKT'], MySqlPreparedQueryConfig & {
execute: MySqlQueryResultKind<T['_']['queryResult'], never>;
iterator: never;
}, true>;
export type MySqlUpdateDynamic<T extends AnyMySqlUpdateBase> = MySqlUpdate<T['_']['table'], T['_']['queryResult'], T['_']['preparedQueryHKT']>;
export type MySqlUpdate<TTable extends MySqlTable = MySqlTable, TQueryResult extends MySqlQueryResultHKT = AnyMySqlQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase = PreparedQueryHKTBase> = MySqlUpdateBase<TTable, TQueryResult, TPreparedQueryHKT, true, never>;
export type AnyMySqlUpdateBase = MySqlUpdateBase<any, any, any, any, any>;
export interface MySqlUpdateBase<TTable extends MySqlTable, TQueryResult extends MySqlQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<MySqlQueryResultKind<TQueryResult, never>>, SQLWrapper {
readonly _: {
readonly table: TTable;
readonly queryResult: TQueryResult;
readonly preparedQueryHKT: TPreparedQueryHKT;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
};
}
export declare class MySqlUpdateBase<TTable extends MySqlTable, TQueryResult extends MySqlQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<MySqlQueryResultKind<TQueryResult, never>> implements SQLWrapper {
private session;
private dialect;
static readonly [entityKind]: string;
private config;
constructor(table: TTable, set: UpdateSet, session: MySqlSession, dialect: MySqlDialect, withList?: Subquery[]);
/**
* 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
* db.update(cars).set({ color: 'red' })
* .where(eq(cars.color, 'green'));
* // or
* 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
* 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
* db.update(cars).set({ color: 'red' })
* .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where: SQL | undefined): MySqlUpdateWithout<this, TDynamic, 'where'>;
orderBy(builder: (updateTable: TTable) => ValueOrArray<MySqlColumn | SQL | SQL.Aliased>): MySqlUpdateWithout<this, TDynamic, 'orderBy'>;
orderBy(...columns: (MySqlColumn | SQL | SQL.Aliased)[]): MySqlUpdateWithout<this, TDynamic, 'orderBy'>;
limit(limit: number | Placeholder): MySqlUpdateWithout<this, TDynamic, 'limit'>;
toSQL(): Query;
prepare(): MySqlUpdatePrepare<this>;
execute: ReturnType<this['prepare']>['execute'];
private createIterator;
iterator: ReturnType<this["prepare"]>["iterator"];
$dynamic(): MySqlUpdateDynamic<this>;
}

View File

@ -0,0 +1,102 @@
import type { GetColumnData } from "../../column.js";
import { entityKind } from "../../entity.js";
import type { MySqlDialect } from "../dialect.js";
import type { AnyMySqlQueryResultHKT, MySqlPreparedQueryConfig, MySqlQueryResultHKT, MySqlQueryResultKind, MySqlSession, PreparedQueryHKTBase, PreparedQueryKind } from "../session.js";
import type { MySqlTable } from "../table.js";
import { QueryPromise } from "../../query-promise.js";
import type { Placeholder, Query, SQL, SQLWrapper } from "../../sql/sql.js";
import type { Subquery } from "../../subquery.js";
import { type UpdateSet, type ValueOrArray } from "../../utils.js";
import type { MySqlColumn } from "../columns/common.js";
import type { SelectedFieldsOrdered } from "./select.types.js";
export interface MySqlUpdateConfig {
where?: SQL | undefined;
limit?: number | Placeholder;
orderBy?: (MySqlColumn | SQL | SQL.Aliased)[];
set: UpdateSet;
table: MySqlTable;
returning?: SelectedFieldsOrdered;
withList?: Subquery[];
}
export type MySqlUpdateSetSource<TTable extends MySqlTable> = {
[Key in keyof TTable['$inferInsert']]?: GetColumnData<TTable['_']['columns'][Key], 'query'> | SQL | undefined;
} & {};
export declare class MySqlUpdateBuilder<TTable extends MySqlTable, TQueryResult extends MySqlQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase> {
private table;
private session;
private dialect;
private withList?;
static readonly [entityKind]: string;
readonly _: {
readonly table: TTable;
};
constructor(table: TTable, session: MySqlSession, dialect: MySqlDialect, withList?: Subquery[] | undefined);
set(values: MySqlUpdateSetSource<TTable>): MySqlUpdateBase<TTable, TQueryResult, TPreparedQueryHKT>;
}
export type MySqlUpdateWithout<T extends AnyMySqlUpdateBase, TDynamic extends boolean, K extends keyof T & string> = TDynamic extends true ? T : Omit<MySqlUpdateBase<T['_']['table'], T['_']['queryResult'], T['_']['preparedQueryHKT'], TDynamic, T['_']['excludedMethods'] | K>, T['_']['excludedMethods'] | K>;
export type MySqlUpdatePrepare<T extends AnyMySqlUpdateBase> = PreparedQueryKind<T['_']['preparedQueryHKT'], MySqlPreparedQueryConfig & {
execute: MySqlQueryResultKind<T['_']['queryResult'], never>;
iterator: never;
}, true>;
export type MySqlUpdateDynamic<T extends AnyMySqlUpdateBase> = MySqlUpdate<T['_']['table'], T['_']['queryResult'], T['_']['preparedQueryHKT']>;
export type MySqlUpdate<TTable extends MySqlTable = MySqlTable, TQueryResult extends MySqlQueryResultHKT = AnyMySqlQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase = PreparedQueryHKTBase> = MySqlUpdateBase<TTable, TQueryResult, TPreparedQueryHKT, true, never>;
export type AnyMySqlUpdateBase = MySqlUpdateBase<any, any, any, any, any>;
export interface MySqlUpdateBase<TTable extends MySqlTable, TQueryResult extends MySqlQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<MySqlQueryResultKind<TQueryResult, never>>, SQLWrapper {
readonly _: {
readonly table: TTable;
readonly queryResult: TQueryResult;
readonly preparedQueryHKT: TPreparedQueryHKT;
readonly dynamic: TDynamic;
readonly excludedMethods: TExcludedMethods;
};
}
export declare class MySqlUpdateBase<TTable extends MySqlTable, TQueryResult extends MySqlQueryResultHKT, TPreparedQueryHKT extends PreparedQueryHKTBase, TDynamic extends boolean = false, TExcludedMethods extends string = never> extends QueryPromise<MySqlQueryResultKind<TQueryResult, never>> implements SQLWrapper {
private session;
private dialect;
static readonly [entityKind]: string;
private config;
constructor(table: TTable, set: UpdateSet, session: MySqlSession, dialect: MySqlDialect, withList?: Subquery[]);
/**
* 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
* db.update(cars).set({ color: 'red' })
* .where(eq(cars.color, 'green'));
* // or
* 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
* 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
* db.update(cars).set({ color: 'red' })
* .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where: SQL | undefined): MySqlUpdateWithout<this, TDynamic, 'where'>;
orderBy(builder: (updateTable: TTable) => ValueOrArray<MySqlColumn | SQL | SQL.Aliased>): MySqlUpdateWithout<this, TDynamic, 'orderBy'>;
orderBy(...columns: (MySqlColumn | SQL | SQL.Aliased)[]): MySqlUpdateWithout<this, TDynamic, 'orderBy'>;
limit(limit: number | Placeholder): MySqlUpdateWithout<this, TDynamic, 'limit'>;
toSQL(): Query;
prepare(): MySqlUpdatePrepare<this>;
execute: ReturnType<this['prepare']>['execute'];
private createIterator;
iterator: ReturnType<this["prepare"]>["iterator"];
$dynamic(): MySqlUpdateDynamic<this>;
}

View File

@ -0,0 +1,116 @@
import { entityKind } from "../../entity.js";
import { QueryPromise } from "../../query-promise.js";
import { SelectionProxyHandler } from "../../selection-proxy.js";
import { Table } from "../../table.js";
import { mapUpdateSet } from "../../utils.js";
class MySqlUpdateBuilder {
constructor(table, session, dialect, withList) {
this.table = table;
this.session = session;
this.dialect = dialect;
this.withList = withList;
}
static [entityKind] = "MySqlUpdateBuilder";
set(values) {
return new MySqlUpdateBase(this.table, mapUpdateSet(this.table, values), this.session, this.dialect, this.withList);
}
}
class MySqlUpdateBase extends QueryPromise {
constructor(table, set, session, dialect, withList) {
super();
this.session = session;
this.dialect = dialect;
this.config = { set, table, withList };
}
static [entityKind] = "MySqlUpdate";
config;
/**
* 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
* db.update(cars).set({ color: 'red' })
* .where(eq(cars.color, 'green'));
* // or
* 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
* 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
* db.update(cars).set({ color: 'red' })
* .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where) {
this.config.where = where;
return this;
}
orderBy(...columns) {
if (typeof columns[0] === "function") {
const orderBy = columns[0](
new Proxy(
this.config.table[Table.Symbol.Columns],
new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
)
);
const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
this.config.orderBy = orderByArray;
} else {
const orderByArray = columns;
this.config.orderBy = orderByArray;
}
return this;
}
limit(limit) {
this.config.limit = limit;
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildUpdateQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
return rest;
}
prepare() {
return this.session.prepareQuery(
this.dialect.sqlToQuery(this.getSQL()),
this.config.returning
);
}
execute = (placeholderValues) => {
return this.prepare().execute(placeholderValues);
};
createIterator = () => {
const self = this;
return async function* (placeholderValues) {
yield* self.prepare().iterator(placeholderValues);
};
};
iterator = this.createIterator();
$dynamic() {
return this;
}
}
export {
MySqlUpdateBase,
MySqlUpdateBuilder
};
//# sourceMappingURL=update.js.map

File diff suppressed because one or more lines are too long