select.cjs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  1. "use strict";
  2. var __defProp = Object.defineProperty;
  3. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  4. var __getOwnPropNames = Object.getOwnPropertyNames;
  5. var __hasOwnProp = Object.prototype.hasOwnProperty;
  6. var __export = (target, all) => {
  7. for (var name in all)
  8. __defProp(target, name, { get: all[name], enumerable: true });
  9. };
  10. var __copyProps = (to, from, except2, desc) => {
  11. if (from && typeof from === "object" || typeof from === "function") {
  12. for (let key of __getOwnPropNames(from))
  13. if (!__hasOwnProp.call(to, key) && key !== except2)
  14. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  15. }
  16. return to;
  17. };
  18. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  19. var select_exports = {};
  20. __export(select_exports, {
  21. MySqlSelectBase: () => MySqlSelectBase,
  22. MySqlSelectBuilder: () => MySqlSelectBuilder,
  23. MySqlSelectQueryBuilderBase: () => MySqlSelectQueryBuilderBase,
  24. except: () => except,
  25. exceptAll: () => exceptAll,
  26. intersect: () => intersect,
  27. intersectAll: () => intersectAll,
  28. union: () => union,
  29. unionAll: () => unionAll
  30. });
  31. module.exports = __toCommonJS(select_exports);
  32. var import_entity = require("../../entity.cjs");
  33. var import_table = require("../table.cjs");
  34. var import_query_builder = require("../../query-builders/query-builder.cjs");
  35. var import_query_promise = require("../../query-promise.cjs");
  36. var import_selection_proxy = require("../../selection-proxy.cjs");
  37. var import_sql = require("../../sql/sql.cjs");
  38. var import_subquery = require("../../subquery.cjs");
  39. var import_table2 = require("../../table.cjs");
  40. var import_utils = require("../../utils.cjs");
  41. var import_view_common = require("../../view-common.cjs");
  42. var import_utils2 = require("../utils.cjs");
  43. var import_view_base = require("../view-base.cjs");
  44. class MySqlSelectBuilder {
  45. static [import_entity.entityKind] = "MySqlSelectBuilder";
  46. fields;
  47. session;
  48. dialect;
  49. withList = [];
  50. distinct;
  51. constructor(config) {
  52. this.fields = config.fields;
  53. this.session = config.session;
  54. this.dialect = config.dialect;
  55. if (config.withList) {
  56. this.withList = config.withList;
  57. }
  58. this.distinct = config.distinct;
  59. }
  60. from(source, onIndex) {
  61. const isPartialSelect = !!this.fields;
  62. let fields;
  63. if (this.fields) {
  64. fields = this.fields;
  65. } else if ((0, import_entity.is)(source, import_subquery.Subquery)) {
  66. fields = Object.fromEntries(
  67. Object.keys(source._.selectedFields).map((key) => [key, source[key]])
  68. );
  69. } else if ((0, import_entity.is)(source, import_view_base.MySqlViewBase)) {
  70. fields = source[import_view_common.ViewBaseConfig].selectedFields;
  71. } else if ((0, import_entity.is)(source, import_sql.SQL)) {
  72. fields = {};
  73. } else {
  74. fields = (0, import_utils.getTableColumns)(source);
  75. }
  76. let useIndex = [];
  77. let forceIndex = [];
  78. let ignoreIndex = [];
  79. if ((0, import_entity.is)(source, import_table.MySqlTable) && onIndex && typeof onIndex !== "string") {
  80. if (onIndex.useIndex) {
  81. useIndex = (0, import_utils2.convertIndexToString)((0, import_utils2.toArray)(onIndex.useIndex));
  82. }
  83. if (onIndex.forceIndex) {
  84. forceIndex = (0, import_utils2.convertIndexToString)((0, import_utils2.toArray)(onIndex.forceIndex));
  85. }
  86. if (onIndex.ignoreIndex) {
  87. ignoreIndex = (0, import_utils2.convertIndexToString)((0, import_utils2.toArray)(onIndex.ignoreIndex));
  88. }
  89. }
  90. return new MySqlSelectBase(
  91. {
  92. table: source,
  93. fields,
  94. isPartialSelect,
  95. session: this.session,
  96. dialect: this.dialect,
  97. withList: this.withList,
  98. distinct: this.distinct,
  99. useIndex,
  100. forceIndex,
  101. ignoreIndex
  102. }
  103. );
  104. }
  105. }
  106. class MySqlSelectQueryBuilderBase extends import_query_builder.TypedQueryBuilder {
  107. static [import_entity.entityKind] = "MySqlSelectQueryBuilder";
  108. _;
  109. config;
  110. joinsNotNullableMap;
  111. tableName;
  112. isPartialSelect;
  113. /** @internal */
  114. session;
  115. dialect;
  116. cacheConfig = void 0;
  117. usedTables = /* @__PURE__ */ new Set();
  118. constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct, useIndex, forceIndex, ignoreIndex }) {
  119. super();
  120. this.config = {
  121. withList,
  122. table,
  123. fields: { ...fields },
  124. distinct,
  125. setOperators: [],
  126. useIndex,
  127. forceIndex,
  128. ignoreIndex
  129. };
  130. this.isPartialSelect = isPartialSelect;
  131. this.session = session;
  132. this.dialect = dialect;
  133. this._ = {
  134. selectedFields: fields,
  135. config: this.config
  136. };
  137. this.tableName = (0, import_utils.getTableLikeName)(table);
  138. this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
  139. for (const item of (0, import_utils2.extractUsedTable)(table)) this.usedTables.add(item);
  140. }
  141. /** @internal */
  142. getUsedTables() {
  143. return [...this.usedTables];
  144. }
  145. createJoin(joinType, lateral) {
  146. return (table, a, b) => {
  147. const isCrossJoin = joinType === "cross";
  148. let on = isCrossJoin ? void 0 : a;
  149. const onIndex = isCrossJoin ? a : b;
  150. const baseTableName = this.tableName;
  151. const tableName = (0, import_utils.getTableLikeName)(table);
  152. for (const item of (0, import_utils2.extractUsedTable)(table)) this.usedTables.add(item);
  153. if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) {
  154. throw new Error(`Alias "${tableName}" is already used in this query`);
  155. }
  156. if (!this.isPartialSelect) {
  157. if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") {
  158. this.config.fields = {
  159. [baseTableName]: this.config.fields
  160. };
  161. }
  162. if (typeof tableName === "string" && !(0, import_entity.is)(table, import_sql.SQL)) {
  163. 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];
  164. this.config.fields[tableName] = selection;
  165. }
  166. }
  167. if (typeof on === "function") {
  168. on = on(
  169. new Proxy(
  170. this.config.fields,
  171. new import_selection_proxy.SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
  172. )
  173. );
  174. }
  175. if (!this.config.joins) {
  176. this.config.joins = [];
  177. }
  178. let useIndex = [];
  179. let forceIndex = [];
  180. let ignoreIndex = [];
  181. if ((0, import_entity.is)(table, import_table.MySqlTable) && onIndex && typeof onIndex !== "string") {
  182. if (onIndex.useIndex) {
  183. useIndex = (0, import_utils2.convertIndexToString)((0, import_utils2.toArray)(onIndex.useIndex));
  184. }
  185. if (onIndex.forceIndex) {
  186. forceIndex = (0, import_utils2.convertIndexToString)((0, import_utils2.toArray)(onIndex.forceIndex));
  187. }
  188. if (onIndex.ignoreIndex) {
  189. ignoreIndex = (0, import_utils2.convertIndexToString)((0, import_utils2.toArray)(onIndex.ignoreIndex));
  190. }
  191. }
  192. this.config.joins.push({ on, table, joinType, alias: tableName, useIndex, forceIndex, ignoreIndex, lateral });
  193. if (typeof tableName === "string") {
  194. switch (joinType) {
  195. case "left": {
  196. this.joinsNotNullableMap[tableName] = false;
  197. break;
  198. }
  199. case "right": {
  200. this.joinsNotNullableMap = Object.fromEntries(
  201. Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
  202. );
  203. this.joinsNotNullableMap[tableName] = true;
  204. break;
  205. }
  206. case "cross":
  207. case "inner": {
  208. this.joinsNotNullableMap[tableName] = true;
  209. break;
  210. }
  211. }
  212. }
  213. return this;
  214. };
  215. }
  216. /**
  217. * Executes a `left join` operation by adding another table to the current query.
  218. *
  219. * 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.
  220. *
  221. * See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
  222. *
  223. * @param table the table to join.
  224. * @param on the `on` clause.
  225. * @param onIndex index hint.
  226. *
  227. * @example
  228. *
  229. * ```ts
  230. * // Select all users and their pets
  231. * const usersWithPets: { user: User; pets: Pet | null; }[] = await db.select()
  232. * .from(users)
  233. * .leftJoin(pets, eq(users.id, pets.ownerId))
  234. *
  235. * // Select userId and petId
  236. * const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({
  237. * userId: users.id,
  238. * petId: pets.id,
  239. * })
  240. * .from(users)
  241. * .leftJoin(pets, eq(users.id, pets.ownerId))
  242. *
  243. * // Select userId and petId with use index hint
  244. * const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({
  245. * userId: users.id,
  246. * petId: pets.id,
  247. * })
  248. * .from(users)
  249. * .leftJoin(pets, eq(users.id, pets.ownerId), {
  250. * useIndex: ['pets_owner_id_index']
  251. * })
  252. * ```
  253. */
  254. leftJoin = this.createJoin("left", false);
  255. /**
  256. * Executes a `left join lateral` operation by adding subquery to the current query.
  257. *
  258. * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
  259. *
  260. * 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.
  261. *
  262. * See docs: {@link https://orm.drizzle.team/docs/joins#left-join-lateral}
  263. *
  264. * @param table the subquery to join.
  265. * @param on the `on` clause.
  266. */
  267. leftJoinLateral = this.createJoin("left", true);
  268. /**
  269. * Executes a `right join` operation by adding another table to the current query.
  270. *
  271. * 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.
  272. *
  273. * See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
  274. *
  275. * @param table the table to join.
  276. * @param on the `on` clause.
  277. * @param onIndex index hint.
  278. *
  279. * @example
  280. *
  281. * ```ts
  282. * // Select all users and their pets
  283. * const usersWithPets: { user: User | null; pets: Pet; }[] = await db.select()
  284. * .from(users)
  285. * .rightJoin(pets, eq(users.id, pets.ownerId))
  286. *
  287. * // Select userId and petId
  288. * const usersIdsAndPetIds: { userId: number | null; petId: number; }[] = await db.select({
  289. * userId: users.id,
  290. * petId: pets.id,
  291. * })
  292. * .from(users)
  293. * .rightJoin(pets, eq(users.id, pets.ownerId))
  294. *
  295. * // Select userId and petId with use index hint
  296. * const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({
  297. * userId: users.id,
  298. * petId: pets.id,
  299. * })
  300. * .from(users)
  301. * .leftJoin(pets, eq(users.id, pets.ownerId), {
  302. * useIndex: ['pets_owner_id_index']
  303. * })
  304. * ```
  305. */
  306. rightJoin = this.createJoin("right", false);
  307. /**
  308. * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
  309. *
  310. * 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.
  311. *
  312. * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
  313. *
  314. * @param table the table to join.
  315. * @param on the `on` clause.
  316. * @param onIndex index hint.
  317. *
  318. * @example
  319. *
  320. * ```ts
  321. * // Select all users and their pets
  322. * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
  323. * .from(users)
  324. * .innerJoin(pets, eq(users.id, pets.ownerId))
  325. *
  326. * // Select userId and petId
  327. * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
  328. * userId: users.id,
  329. * petId: pets.id,
  330. * })
  331. * .from(users)
  332. * .innerJoin(pets, eq(users.id, pets.ownerId))
  333. *
  334. * // Select userId and petId with use index hint
  335. * const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({
  336. * userId: users.id,
  337. * petId: pets.id,
  338. * })
  339. * .from(users)
  340. * .leftJoin(pets, eq(users.id, pets.ownerId), {
  341. * useIndex: ['pets_owner_id_index']
  342. * })
  343. * ```
  344. */
  345. innerJoin = this.createJoin("inner", false);
  346. /**
  347. * Executes an `inner join lateral` operation, creating a new table by combining rows from two queries that have matching values.
  348. *
  349. * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
  350. *
  351. * 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.
  352. *
  353. * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join-lateral}
  354. *
  355. * @param table the subquery to join.
  356. * @param on the `on` clause.
  357. */
  358. innerJoinLateral = this.createJoin("inner", true);
  359. /**
  360. * Executes a `cross join` operation by combining rows from two tables into a new table.
  361. *
  362. * Calling this method retrieves all rows from both main and joined tables, merging all rows from each table.
  363. *
  364. * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join}
  365. *
  366. * @param table the table to join.
  367. * @param onIndex index hint.
  368. *
  369. * @example
  370. *
  371. * ```ts
  372. * // Select all users, each user with every pet
  373. * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
  374. * .from(users)
  375. * .crossJoin(pets)
  376. *
  377. * // Select userId and petId
  378. * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
  379. * userId: users.id,
  380. * petId: pets.id,
  381. * })
  382. * .from(users)
  383. * .crossJoin(pets)
  384. *
  385. * // Select userId and petId with use index hint
  386. * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
  387. * userId: users.id,
  388. * petId: pets.id,
  389. * })
  390. * .from(users)
  391. * .crossJoin(pets, {
  392. * useIndex: ['pets_owner_id_index']
  393. * })
  394. * ```
  395. */
  396. crossJoin = this.createJoin("cross", false);
  397. /**
  398. * Executes a `cross join lateral` operation by combining rows from two queries into a new table.
  399. *
  400. * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
  401. *
  402. * Calling this method retrieves all rows from both main and joined queries, merging all rows from each query.
  403. *
  404. * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join-lateral}
  405. *
  406. * @param table the query to join.
  407. */
  408. crossJoinLateral = this.createJoin("cross", true);
  409. createSetOperator(type, isAll) {
  410. return (rightSelection) => {
  411. const rightSelect = typeof rightSelection === "function" ? rightSelection(getMySqlSetOperators()) : rightSelection;
  412. if (!(0, import_utils.haveSameKeys)(this.getSelectedFields(), rightSelect.getSelectedFields())) {
  413. throw new Error(
  414. "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
  415. );
  416. }
  417. this.config.setOperators.push({ type, isAll, rightSelect });
  418. return this;
  419. };
  420. }
  421. /**
  422. * Adds `union` set operator to the query.
  423. *
  424. * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
  425. *
  426. * See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
  427. *
  428. * @example
  429. *
  430. * ```ts
  431. * // Select all unique names from customers and users tables
  432. * await db.select({ name: users.name })
  433. * .from(users)
  434. * .union(
  435. * db.select({ name: customers.name }).from(customers)
  436. * );
  437. * // or
  438. * import { union } from 'drizzle-orm/mysql-core'
  439. *
  440. * await union(
  441. * db.select({ name: users.name }).from(users),
  442. * db.select({ name: customers.name }).from(customers)
  443. * );
  444. * ```
  445. */
  446. union = this.createSetOperator("union", false);
  447. /**
  448. * Adds `union all` set operator to the query.
  449. *
  450. * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
  451. *
  452. * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
  453. *
  454. * @example
  455. *
  456. * ```ts
  457. * // Select all transaction ids from both online and in-store sales
  458. * await db.select({ transaction: onlineSales.transactionId })
  459. * .from(onlineSales)
  460. * .unionAll(
  461. * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
  462. * );
  463. * // or
  464. * import { unionAll } from 'drizzle-orm/mysql-core'
  465. *
  466. * await unionAll(
  467. * db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
  468. * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
  469. * );
  470. * ```
  471. */
  472. unionAll = this.createSetOperator("union", true);
  473. /**
  474. * Adds `intersect` set operator to the query.
  475. *
  476. * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
  477. *
  478. * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
  479. *
  480. * @example
  481. *
  482. * ```ts
  483. * // Select course names that are offered in both departments A and B
  484. * await db.select({ courseName: depA.courseName })
  485. * .from(depA)
  486. * .intersect(
  487. * db.select({ courseName: depB.courseName }).from(depB)
  488. * );
  489. * // or
  490. * import { intersect } from 'drizzle-orm/mysql-core'
  491. *
  492. * await intersect(
  493. * db.select({ courseName: depA.courseName }).from(depA),
  494. * db.select({ courseName: depB.courseName }).from(depB)
  495. * );
  496. * ```
  497. */
  498. intersect = this.createSetOperator("intersect", false);
  499. /**
  500. * Adds `intersect all` set operator to the query.
  501. *
  502. * Calling this method will retain only the rows that are present in both result sets including all duplicates.
  503. *
  504. * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect-all}
  505. *
  506. * @example
  507. *
  508. * ```ts
  509. * // Select all products and quantities that are ordered by both regular and VIP customers
  510. * await db.select({
  511. * productId: regularCustomerOrders.productId,
  512. * quantityOrdered: regularCustomerOrders.quantityOrdered
  513. * })
  514. * .from(regularCustomerOrders)
  515. * .intersectAll(
  516. * db.select({
  517. * productId: vipCustomerOrders.productId,
  518. * quantityOrdered: vipCustomerOrders.quantityOrdered
  519. * })
  520. * .from(vipCustomerOrders)
  521. * );
  522. * // or
  523. * import { intersectAll } from 'drizzle-orm/mysql-core'
  524. *
  525. * await intersectAll(
  526. * db.select({
  527. * productId: regularCustomerOrders.productId,
  528. * quantityOrdered: regularCustomerOrders.quantityOrdered
  529. * })
  530. * .from(regularCustomerOrders),
  531. * db.select({
  532. * productId: vipCustomerOrders.productId,
  533. * quantityOrdered: vipCustomerOrders.quantityOrdered
  534. * })
  535. * .from(vipCustomerOrders)
  536. * );
  537. * ```
  538. */
  539. intersectAll = this.createSetOperator("intersect", true);
  540. /**
  541. * Adds `except` set operator to the query.
  542. *
  543. * 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.
  544. *
  545. * See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
  546. *
  547. * @example
  548. *
  549. * ```ts
  550. * // Select all courses offered in department A but not in department B
  551. * await db.select({ courseName: depA.courseName })
  552. * .from(depA)
  553. * .except(
  554. * db.select({ courseName: depB.courseName }).from(depB)
  555. * );
  556. * // or
  557. * import { except } from 'drizzle-orm/mysql-core'
  558. *
  559. * await except(
  560. * db.select({ courseName: depA.courseName }).from(depA),
  561. * db.select({ courseName: depB.courseName }).from(depB)
  562. * );
  563. * ```
  564. */
  565. except = this.createSetOperator("except", false);
  566. /**
  567. * Adds `except all` set operator to the query.
  568. *
  569. * 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.
  570. *
  571. * See docs: {@link https://orm.drizzle.team/docs/set-operations#except-all}
  572. *
  573. * @example
  574. *
  575. * ```ts
  576. * // Select all products that are ordered by regular customers but not by VIP customers
  577. * await db.select({
  578. * productId: regularCustomerOrders.productId,
  579. * quantityOrdered: regularCustomerOrders.quantityOrdered,
  580. * })
  581. * .from(regularCustomerOrders)
  582. * .exceptAll(
  583. * db.select({
  584. * productId: vipCustomerOrders.productId,
  585. * quantityOrdered: vipCustomerOrders.quantityOrdered,
  586. * })
  587. * .from(vipCustomerOrders)
  588. * );
  589. * // or
  590. * import { exceptAll } from 'drizzle-orm/mysql-core'
  591. *
  592. * await exceptAll(
  593. * db.select({
  594. * productId: regularCustomerOrders.productId,
  595. * quantityOrdered: regularCustomerOrders.quantityOrdered
  596. * })
  597. * .from(regularCustomerOrders),
  598. * db.select({
  599. * productId: vipCustomerOrders.productId,
  600. * quantityOrdered: vipCustomerOrders.quantityOrdered
  601. * })
  602. * .from(vipCustomerOrders)
  603. * );
  604. * ```
  605. */
  606. exceptAll = this.createSetOperator("except", true);
  607. /** @internal */
  608. addSetOperators(setOperators) {
  609. this.config.setOperators.push(...setOperators);
  610. return this;
  611. }
  612. /**
  613. * Adds a `where` clause to the query.
  614. *
  615. * Calling this method will select only those rows that fulfill a specified condition.
  616. *
  617. * See docs: {@link https://orm.drizzle.team/docs/select#filtering}
  618. *
  619. * @param where the `where` clause.
  620. *
  621. * @example
  622. * You can use conditional operators and `sql function` to filter the rows to be selected.
  623. *
  624. * ```ts
  625. * // Select all cars with green color
  626. * await db.select().from(cars).where(eq(cars.color, 'green'));
  627. * // or
  628. * await db.select().from(cars).where(sql`${cars.color} = 'green'`)
  629. * ```
  630. *
  631. * You can logically combine conditional operators with `and()` and `or()` operators:
  632. *
  633. * ```ts
  634. * // Select all BMW cars with a green color
  635. * await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
  636. *
  637. * // Select all cars with the green or blue color
  638. * await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
  639. * ```
  640. */
  641. where(where) {
  642. if (typeof where === "function") {
  643. where = where(
  644. new Proxy(
  645. this.config.fields,
  646. new import_selection_proxy.SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
  647. )
  648. );
  649. }
  650. this.config.where = where;
  651. return this;
  652. }
  653. /**
  654. * Adds a `having` clause to the query.
  655. *
  656. * 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.
  657. *
  658. * See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
  659. *
  660. * @param having the `having` clause.
  661. *
  662. * @example
  663. *
  664. * ```ts
  665. * // Select all brands with more than one car
  666. * await db.select({
  667. * brand: cars.brand,
  668. * count: sql<number>`cast(count(${cars.id}) as int)`,
  669. * })
  670. * .from(cars)
  671. * .groupBy(cars.brand)
  672. * .having(({ count }) => gt(count, 1));
  673. * ```
  674. */
  675. having(having) {
  676. if (typeof having === "function") {
  677. having = having(
  678. new Proxy(
  679. this.config.fields,
  680. new import_selection_proxy.SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
  681. )
  682. );
  683. }
  684. this.config.having = having;
  685. return this;
  686. }
  687. groupBy(...columns) {
  688. if (typeof columns[0] === "function") {
  689. const groupBy = columns[0](
  690. new Proxy(
  691. this.config.fields,
  692. new import_selection_proxy.SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
  693. )
  694. );
  695. this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
  696. } else {
  697. this.config.groupBy = columns;
  698. }
  699. return this;
  700. }
  701. orderBy(...columns) {
  702. if (typeof columns[0] === "function") {
  703. const orderBy = columns[0](
  704. new Proxy(
  705. this.config.fields,
  706. new import_selection_proxy.SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
  707. )
  708. );
  709. const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
  710. if (this.config.setOperators.length > 0) {
  711. this.config.setOperators.at(-1).orderBy = orderByArray;
  712. } else {
  713. this.config.orderBy = orderByArray;
  714. }
  715. } else {
  716. const orderByArray = columns;
  717. if (this.config.setOperators.length > 0) {
  718. this.config.setOperators.at(-1).orderBy = orderByArray;
  719. } else {
  720. this.config.orderBy = orderByArray;
  721. }
  722. }
  723. return this;
  724. }
  725. /**
  726. * Adds a `limit` clause to the query.
  727. *
  728. * Calling this method will set the maximum number of rows that will be returned by this query.
  729. *
  730. * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
  731. *
  732. * @param limit the `limit` clause.
  733. *
  734. * @example
  735. *
  736. * ```ts
  737. * // Get the first 10 people from this query.
  738. * await db.select().from(people).limit(10);
  739. * ```
  740. */
  741. limit(limit) {
  742. if (this.config.setOperators.length > 0) {
  743. this.config.setOperators.at(-1).limit = limit;
  744. } else {
  745. this.config.limit = limit;
  746. }
  747. return this;
  748. }
  749. /**
  750. * Adds an `offset` clause to the query.
  751. *
  752. * Calling this method will skip a number of rows when returning results from this query.
  753. *
  754. * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
  755. *
  756. * @param offset the `offset` clause.
  757. *
  758. * @example
  759. *
  760. * ```ts
  761. * // Get the 10th-20th people from this query.
  762. * await db.select().from(people).offset(10).limit(10);
  763. * ```
  764. */
  765. offset(offset) {
  766. if (this.config.setOperators.length > 0) {
  767. this.config.setOperators.at(-1).offset = offset;
  768. } else {
  769. this.config.offset = offset;
  770. }
  771. return this;
  772. }
  773. /**
  774. * Adds a `for` clause to the query.
  775. *
  776. * Calling this method will specify a lock strength for this query that controls how strictly it acquires exclusive access to the rows being queried.
  777. *
  778. * See docs: {@link https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html}
  779. *
  780. * @param strength the lock strength.
  781. * @param config the lock configuration.
  782. */
  783. for(strength, config = {}) {
  784. this.config.lockingClause = { strength, config };
  785. return this;
  786. }
  787. /** @internal */
  788. getSQL() {
  789. return this.dialect.buildSelectQuery(this.config);
  790. }
  791. toSQL() {
  792. const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
  793. return rest;
  794. }
  795. as(alias) {
  796. const usedTables = [];
  797. usedTables.push(...(0, import_utils2.extractUsedTable)(this.config.table));
  798. if (this.config.joins) {
  799. for (const it of this.config.joins) usedTables.push(...(0, import_utils2.extractUsedTable)(it.table));
  800. }
  801. return new Proxy(
  802. new import_subquery.Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]),
  803. new import_selection_proxy.SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
  804. );
  805. }
  806. /** @internal */
  807. getSelectedFields() {
  808. return new Proxy(
  809. this.config.fields,
  810. new import_selection_proxy.SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
  811. );
  812. }
  813. $dynamic() {
  814. return this;
  815. }
  816. $withCache(config) {
  817. this.cacheConfig = config === void 0 ? { config: {}, enable: true, autoInvalidate: true } : config === false ? { enable: false } : { enable: true, autoInvalidate: true, ...config };
  818. return this;
  819. }
  820. }
  821. class MySqlSelectBase extends MySqlSelectQueryBuilderBase {
  822. static [import_entity.entityKind] = "MySqlSelect";
  823. prepare() {
  824. if (!this.session) {
  825. throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
  826. }
  827. const fieldsList = (0, import_utils.orderSelectedFields)(this.config.fields);
  828. const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), fieldsList, void 0, void 0, void 0, {
  829. type: "select",
  830. tables: [...this.usedTables]
  831. }, this.cacheConfig);
  832. query.joinsNotNullableMap = this.joinsNotNullableMap;
  833. return query;
  834. }
  835. execute = (placeholderValues) => {
  836. return this.prepare().execute(placeholderValues);
  837. };
  838. createIterator = () => {
  839. const self = this;
  840. return async function* (placeholderValues) {
  841. yield* self.prepare().iterator(placeholderValues);
  842. };
  843. };
  844. iterator = this.createIterator();
  845. }
  846. (0, import_utils.applyMixins)(MySqlSelectBase, [import_query_promise.QueryPromise]);
  847. function createSetOperator(type, isAll) {
  848. return (leftSelect, rightSelect, ...restSelects) => {
  849. const setOperators = [rightSelect, ...restSelects].map((select) => ({
  850. type,
  851. isAll,
  852. rightSelect: select
  853. }));
  854. for (const setOperator of setOperators) {
  855. if (!(0, import_utils.haveSameKeys)(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {
  856. throw new Error(
  857. "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
  858. );
  859. }
  860. }
  861. return leftSelect.addSetOperators(setOperators);
  862. };
  863. }
  864. const getMySqlSetOperators = () => ({
  865. union,
  866. unionAll,
  867. intersect,
  868. intersectAll,
  869. except,
  870. exceptAll
  871. });
  872. const union = createSetOperator("union", false);
  873. const unionAll = createSetOperator("union", true);
  874. const intersect = createSetOperator("intersect", false);
  875. const intersectAll = createSetOperator("intersect", true);
  876. const except = createSetOperator("except", false);
  877. const exceptAll = createSetOperator("except", true);
  878. // Annotate the CommonJS export names for ESM import in node:
  879. 0 && (module.exports = {
  880. MySqlSelectBase,
  881. MySqlSelectBuilder,
  882. MySqlSelectQueryBuilderBase,
  883. except,
  884. exceptAll,
  885. intersect,
  886. intersectAll,
  887. union,
  888. unionAll
  889. });
  890. //# sourceMappingURL=select.cjs.map