| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890 |
- "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;
- cacheConfig = void 0;
- usedTables = /* @__PURE__ */ new Set();
- 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,
- config: this.config
- };
- this.tableName = (0, import_utils.getTableLikeName)(table);
- this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
- for (const item of (0, import_utils2.extractUsedTable)(table)) this.usedTables.add(item);
- }
- /** @internal */
- getUsedTables() {
- return [...this.usedTables];
- }
- createJoin(joinType, lateral) {
- return (table, a, b) => {
- const isCrossJoin = joinType === "cross";
- let on = isCrossJoin ? void 0 : a;
- const onIndex = isCrossJoin ? a : b;
- const baseTableName = this.tableName;
- const tableName = (0, import_utils.getTableLikeName)(table);
- for (const item of (0, import_utils2.extractUsedTable)(table)) this.usedTables.add(item);
- 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, lateral });
- if (typeof tableName === "string") {
- switch (joinType) {
- case "left": {
- this.joinsNotNullableMap[tableName] = false;
- break;
- }
- case "right": {
- this.joinsNotNullableMap = Object.fromEntries(
- Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
- );
- this.joinsNotNullableMap[tableName] = true;
- break;
- }
- case "cross":
- case "inner": {
- this.joinsNotNullableMap[tableName] = true;
- break;
- }
- }
- }
- 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.
- * @param onIndex index hint.
- *
- * @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", false);
- /**
- * Executes a `left join lateral` operation by adding subquery to the current query.
- *
- * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
- *
- * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
- *
- * See docs: {@link https://orm.drizzle.team/docs/joins#left-join-lateral}
- *
- * @param table the subquery to join.
- * @param on the `on` clause.
- */
- leftJoinLateral = this.createJoin("left", true);
- /**
- * Executes a `right join` operation by adding another table to the current query.
- *
- * Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
- *
- * See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
- *
- * @param table the table to join.
- * @param on the `on` clause.
- * @param onIndex index hint.
- *
- * @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", false);
- /**
- * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
- *
- * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
- *
- * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
- *
- * @param table the table to join.
- * @param on the `on` clause.
- * @param onIndex index hint.
- *
- * @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", false);
- /**
- * Executes an `inner join lateral` operation, creating a new table by combining rows from two queries that have matching values.
- *
- * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
- *
- * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
- *
- * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join-lateral}
- *
- * @param table the subquery to join.
- * @param on the `on` clause.
- */
- innerJoinLateral = this.createJoin("inner", true);
- /**
- * Executes a `cross join` operation by combining rows from two tables into a new table.
- *
- * Calling this method retrieves all rows from both main and joined tables, merging all rows from each table.
- *
- * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join}
- *
- * @param table the table to join.
- * @param onIndex index hint.
- *
- * @example
- *
- * ```ts
- * // Select all users, each user with every pet
- * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
- * .from(users)
- * .crossJoin(pets)
- *
- * // Select userId and petId
- * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
- * userId: users.id,
- * petId: pets.id,
- * })
- * .from(users)
- * .crossJoin(pets)
- *
- * // Select userId and petId with use index hint
- * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
- * userId: users.id,
- * petId: pets.id,
- * })
- * .from(users)
- * .crossJoin(pets, {
- * useIndex: ['pets_owner_id_index']
- * })
- * ```
- */
- crossJoin = this.createJoin("cross", false);
- /**
- * Executes a `cross join lateral` operation by combining rows from two queries into a new table.
- *
- * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
- *
- * Calling this method retrieves all rows from both main and joined queries, merging all rows from each query.
- *
- * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join-lateral}
- *
- * @param table the query to join.
- */
- crossJoinLateral = this.createJoin("cross", true);
- createSetOperator(type, isAll) {
- return (rightSelection) => {
- const rightSelect = typeof rightSelection === "function" ? rightSelection(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) {
- const usedTables = [];
- usedTables.push(...(0, import_utils2.extractUsedTable)(this.config.table));
- if (this.config.joins) {
- for (const it of this.config.joins) usedTables.push(...(0, import_utils2.extractUsedTable)(it.table));
- }
- return new Proxy(
- new import_subquery.Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]),
- new import_selection_proxy.SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
- );
- }
- /** @internal */
- getSelectedFields() {
- return new Proxy(
- this.config.fields,
- new import_selection_proxy.SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
- );
- }
- $dynamic() {
- return this;
- }
- $withCache(config) {
- this.cacheConfig = config === void 0 ? { config: {}, enable: true, autoInvalidate: true } : config === false ? { enable: false } : { enable: true, autoInvalidate: true, ...config };
- 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, void 0, void 0, void 0, {
- type: "select",
- tables: [...this.usedTables]
- }, this.cacheConfig);
- 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
|