select.cjs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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. SQLiteSelectBase: () => SQLiteSelectBase,
  22. SQLiteSelectBuilder: () => SQLiteSelectBuilder,
  23. SQLiteSelectQueryBuilderBase: () => SQLiteSelectQueryBuilderBase,
  24. except: () => except,
  25. intersect: () => intersect,
  26. union: () => union,
  27. unionAll: () => unionAll
  28. });
  29. module.exports = __toCommonJS(select_exports);
  30. var import_entity = require("../../entity.cjs");
  31. var import_query_builder = require("../../query-builders/query-builder.cjs");
  32. var import_query_promise = require("../../query-promise.cjs");
  33. var import_selection_proxy = require("../../selection-proxy.cjs");
  34. var import_sql = require("../../sql/sql.cjs");
  35. var import_subquery = require("../../subquery.cjs");
  36. var import_table = require("../../table.cjs");
  37. var import_utils = require("../../utils.cjs");
  38. var import_view_common = require("../../view-common.cjs");
  39. var import_utils2 = require("../utils.cjs");
  40. var import_view_base = require("../view-base.cjs");
  41. class SQLiteSelectBuilder {
  42. static [import_entity.entityKind] = "SQLiteSelectBuilder";
  43. fields;
  44. session;
  45. dialect;
  46. withList;
  47. distinct;
  48. constructor(config) {
  49. this.fields = config.fields;
  50. this.session = config.session;
  51. this.dialect = config.dialect;
  52. this.withList = config.withList;
  53. this.distinct = config.distinct;
  54. }
  55. from(source) {
  56. const isPartialSelect = !!this.fields;
  57. let fields;
  58. if (this.fields) {
  59. fields = this.fields;
  60. } else if ((0, import_entity.is)(source, import_subquery.Subquery)) {
  61. fields = Object.fromEntries(
  62. Object.keys(source._.selectedFields).map((key) => [key, source[key]])
  63. );
  64. } else if ((0, import_entity.is)(source, import_view_base.SQLiteViewBase)) {
  65. fields = source[import_view_common.ViewBaseConfig].selectedFields;
  66. } else if ((0, import_entity.is)(source, import_sql.SQL)) {
  67. fields = {};
  68. } else {
  69. fields = (0, import_utils.getTableColumns)(source);
  70. }
  71. return new SQLiteSelectBase({
  72. table: source,
  73. fields,
  74. isPartialSelect,
  75. session: this.session,
  76. dialect: this.dialect,
  77. withList: this.withList,
  78. distinct: this.distinct
  79. });
  80. }
  81. }
  82. class SQLiteSelectQueryBuilderBase extends import_query_builder.TypedQueryBuilder {
  83. static [import_entity.entityKind] = "SQLiteSelectQueryBuilder";
  84. _;
  85. /** @internal */
  86. config;
  87. joinsNotNullableMap;
  88. tableName;
  89. isPartialSelect;
  90. session;
  91. dialect;
  92. cacheConfig = void 0;
  93. usedTables = /* @__PURE__ */ new Set();
  94. constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }) {
  95. super();
  96. this.config = {
  97. withList,
  98. table,
  99. fields: { ...fields },
  100. distinct,
  101. setOperators: []
  102. };
  103. this.isPartialSelect = isPartialSelect;
  104. this.session = session;
  105. this.dialect = dialect;
  106. this._ = {
  107. selectedFields: fields,
  108. config: this.config
  109. };
  110. this.tableName = (0, import_utils.getTableLikeName)(table);
  111. this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
  112. for (const item of (0, import_utils2.extractUsedTable)(table)) this.usedTables.add(item);
  113. }
  114. /** @internal */
  115. getUsedTables() {
  116. return [...this.usedTables];
  117. }
  118. createJoin(joinType) {
  119. return (table, on) => {
  120. const baseTableName = this.tableName;
  121. const tableName = (0, import_utils.getTableLikeName)(table);
  122. for (const item of (0, import_utils2.extractUsedTable)(table)) this.usedTables.add(item);
  123. if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) {
  124. throw new Error(`Alias "${tableName}" is already used in this query`);
  125. }
  126. if (!this.isPartialSelect) {
  127. if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") {
  128. this.config.fields = {
  129. [baseTableName]: this.config.fields
  130. };
  131. }
  132. if (typeof tableName === "string" && !(0, import_entity.is)(table, import_sql.SQL)) {
  133. const selection = (0, import_entity.is)(table, import_subquery.Subquery) ? table._.selectedFields : (0, import_entity.is)(table, import_sql.View) ? table[import_view_common.ViewBaseConfig].selectedFields : table[import_table.Table.Symbol.Columns];
  134. this.config.fields[tableName] = selection;
  135. }
  136. }
  137. if (typeof on === "function") {
  138. on = on(
  139. new Proxy(
  140. this.config.fields,
  141. new import_selection_proxy.SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
  142. )
  143. );
  144. }
  145. if (!this.config.joins) {
  146. this.config.joins = [];
  147. }
  148. this.config.joins.push({ on, table, joinType, alias: tableName });
  149. if (typeof tableName === "string") {
  150. switch (joinType) {
  151. case "left": {
  152. this.joinsNotNullableMap[tableName] = false;
  153. break;
  154. }
  155. case "right": {
  156. this.joinsNotNullableMap = Object.fromEntries(
  157. Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
  158. );
  159. this.joinsNotNullableMap[tableName] = true;
  160. break;
  161. }
  162. case "cross":
  163. case "inner": {
  164. this.joinsNotNullableMap[tableName] = true;
  165. break;
  166. }
  167. case "full": {
  168. this.joinsNotNullableMap = Object.fromEntries(
  169. Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
  170. );
  171. this.joinsNotNullableMap[tableName] = false;
  172. break;
  173. }
  174. }
  175. }
  176. return this;
  177. };
  178. }
  179. /**
  180. * Executes a `left join` operation by adding another table to the current query.
  181. *
  182. * 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.
  183. *
  184. * See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
  185. *
  186. * @param table the table to join.
  187. * @param on the `on` clause.
  188. *
  189. * @example
  190. *
  191. * ```ts
  192. * // Select all users and their pets
  193. * const usersWithPets: { user: User; pets: Pet | null; }[] = await db.select()
  194. * .from(users)
  195. * .leftJoin(pets, eq(users.id, pets.ownerId))
  196. *
  197. * // Select userId and petId
  198. * const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({
  199. * userId: users.id,
  200. * petId: pets.id,
  201. * })
  202. * .from(users)
  203. * .leftJoin(pets, eq(users.id, pets.ownerId))
  204. * ```
  205. */
  206. leftJoin = this.createJoin("left");
  207. /**
  208. * Executes a `right join` operation by adding another table to the current query.
  209. *
  210. * 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.
  211. *
  212. * See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
  213. *
  214. * @param table the table to join.
  215. * @param on the `on` clause.
  216. *
  217. * @example
  218. *
  219. * ```ts
  220. * // Select all users and their pets
  221. * const usersWithPets: { user: User | null; pets: Pet; }[] = await db.select()
  222. * .from(users)
  223. * .rightJoin(pets, eq(users.id, pets.ownerId))
  224. *
  225. * // Select userId and petId
  226. * const usersIdsAndPetIds: { userId: number | null; petId: number; }[] = await db.select({
  227. * userId: users.id,
  228. * petId: pets.id,
  229. * })
  230. * .from(users)
  231. * .rightJoin(pets, eq(users.id, pets.ownerId))
  232. * ```
  233. */
  234. rightJoin = this.createJoin("right");
  235. /**
  236. * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
  237. *
  238. * 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.
  239. *
  240. * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
  241. *
  242. * @param table the table to join.
  243. * @param on the `on` clause.
  244. *
  245. * @example
  246. *
  247. * ```ts
  248. * // Select all users and their pets
  249. * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
  250. * .from(users)
  251. * .innerJoin(pets, eq(users.id, pets.ownerId))
  252. *
  253. * // Select userId and petId
  254. * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
  255. * userId: users.id,
  256. * petId: pets.id,
  257. * })
  258. * .from(users)
  259. * .innerJoin(pets, eq(users.id, pets.ownerId))
  260. * ```
  261. */
  262. innerJoin = this.createJoin("inner");
  263. /**
  264. * Executes a `full join` operation by combining rows from two tables into a new table.
  265. *
  266. * 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.
  267. *
  268. * See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
  269. *
  270. * @param table the table to join.
  271. * @param on the `on` clause.
  272. *
  273. * @example
  274. *
  275. * ```ts
  276. * // Select all users and their pets
  277. * const usersWithPets: { user: User | null; pets: Pet | null; }[] = await db.select()
  278. * .from(users)
  279. * .fullJoin(pets, eq(users.id, pets.ownerId))
  280. *
  281. * // Select userId and petId
  282. * const usersIdsAndPetIds: { userId: number | null; petId: number | null; }[] = await db.select({
  283. * userId: users.id,
  284. * petId: pets.id,
  285. * })
  286. * .from(users)
  287. * .fullJoin(pets, eq(users.id, pets.ownerId))
  288. * ```
  289. */
  290. fullJoin = this.createJoin("full");
  291. /**
  292. * Executes a `cross join` operation by combining rows from two tables into a new table.
  293. *
  294. * Calling this method retrieves all rows from both main and joined tables, merging all rows from each table.
  295. *
  296. * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join}
  297. *
  298. * @param table the table to join.
  299. *
  300. * @example
  301. *
  302. * ```ts
  303. * // Select all users, each user with every pet
  304. * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
  305. * .from(users)
  306. * .crossJoin(pets)
  307. *
  308. * // Select userId and petId
  309. * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
  310. * userId: users.id,
  311. * petId: pets.id,
  312. * })
  313. * .from(users)
  314. * .crossJoin(pets)
  315. * ```
  316. */
  317. crossJoin = this.createJoin("cross");
  318. createSetOperator(type, isAll) {
  319. return (rightSelection) => {
  320. const rightSelect = typeof rightSelection === "function" ? rightSelection(getSQLiteSetOperators()) : rightSelection;
  321. if (!(0, import_utils.haveSameKeys)(this.getSelectedFields(), rightSelect.getSelectedFields())) {
  322. throw new Error(
  323. "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
  324. );
  325. }
  326. this.config.setOperators.push({ type, isAll, rightSelect });
  327. return this;
  328. };
  329. }
  330. /**
  331. * Adds `union` set operator to the query.
  332. *
  333. * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
  334. *
  335. * See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
  336. *
  337. * @example
  338. *
  339. * ```ts
  340. * // Select all unique names from customers and users tables
  341. * await db.select({ name: users.name })
  342. * .from(users)
  343. * .union(
  344. * db.select({ name: customers.name }).from(customers)
  345. * );
  346. * // or
  347. * import { union } from 'drizzle-orm/sqlite-core'
  348. *
  349. * await union(
  350. * db.select({ name: users.name }).from(users),
  351. * db.select({ name: customers.name }).from(customers)
  352. * );
  353. * ```
  354. */
  355. union = this.createSetOperator("union", false);
  356. /**
  357. * Adds `union all` set operator to the query.
  358. *
  359. * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
  360. *
  361. * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
  362. *
  363. * @example
  364. *
  365. * ```ts
  366. * // Select all transaction ids from both online and in-store sales
  367. * await db.select({ transaction: onlineSales.transactionId })
  368. * .from(onlineSales)
  369. * .unionAll(
  370. * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
  371. * );
  372. * // or
  373. * import { unionAll } from 'drizzle-orm/sqlite-core'
  374. *
  375. * await unionAll(
  376. * db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
  377. * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
  378. * );
  379. * ```
  380. */
  381. unionAll = this.createSetOperator("union", true);
  382. /**
  383. * Adds `intersect` set operator to the query.
  384. *
  385. * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
  386. *
  387. * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
  388. *
  389. * @example
  390. *
  391. * ```ts
  392. * // Select course names that are offered in both departments A and B
  393. * await db.select({ courseName: depA.courseName })
  394. * .from(depA)
  395. * .intersect(
  396. * db.select({ courseName: depB.courseName }).from(depB)
  397. * );
  398. * // or
  399. * import { intersect } from 'drizzle-orm/sqlite-core'
  400. *
  401. * await intersect(
  402. * db.select({ courseName: depA.courseName }).from(depA),
  403. * db.select({ courseName: depB.courseName }).from(depB)
  404. * );
  405. * ```
  406. */
  407. intersect = this.createSetOperator("intersect", false);
  408. /**
  409. * Adds `except` set operator to the query.
  410. *
  411. * 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.
  412. *
  413. * See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
  414. *
  415. * @example
  416. *
  417. * ```ts
  418. * // Select all courses offered in department A but not in department B
  419. * await db.select({ courseName: depA.courseName })
  420. * .from(depA)
  421. * .except(
  422. * db.select({ courseName: depB.courseName }).from(depB)
  423. * );
  424. * // or
  425. * import { except } from 'drizzle-orm/sqlite-core'
  426. *
  427. * await except(
  428. * db.select({ courseName: depA.courseName }).from(depA),
  429. * db.select({ courseName: depB.courseName }).from(depB)
  430. * );
  431. * ```
  432. */
  433. except = this.createSetOperator("except", false);
  434. /** @internal */
  435. addSetOperators(setOperators) {
  436. this.config.setOperators.push(...setOperators);
  437. return this;
  438. }
  439. /**
  440. * Adds a `where` clause to the query.
  441. *
  442. * Calling this method will select only those rows that fulfill a specified condition.
  443. *
  444. * See docs: {@link https://orm.drizzle.team/docs/select#filtering}
  445. *
  446. * @param where the `where` clause.
  447. *
  448. * @example
  449. * You can use conditional operators and `sql function` to filter the rows to be selected.
  450. *
  451. * ```ts
  452. * // Select all cars with green color
  453. * await db.select().from(cars).where(eq(cars.color, 'green'));
  454. * // or
  455. * await db.select().from(cars).where(sql`${cars.color} = 'green'`)
  456. * ```
  457. *
  458. * You can logically combine conditional operators with `and()` and `or()` operators:
  459. *
  460. * ```ts
  461. * // Select all BMW cars with a green color
  462. * await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
  463. *
  464. * // Select all cars with the green or blue color
  465. * await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
  466. * ```
  467. */
  468. where(where) {
  469. if (typeof where === "function") {
  470. where = where(
  471. new Proxy(
  472. this.config.fields,
  473. new import_selection_proxy.SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
  474. )
  475. );
  476. }
  477. this.config.where = where;
  478. return this;
  479. }
  480. /**
  481. * Adds a `having` clause to the query.
  482. *
  483. * 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.
  484. *
  485. * See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
  486. *
  487. * @param having the `having` clause.
  488. *
  489. * @example
  490. *
  491. * ```ts
  492. * // Select all brands with more than one car
  493. * await db.select({
  494. * brand: cars.brand,
  495. * count: sql<number>`cast(count(${cars.id}) as int)`,
  496. * })
  497. * .from(cars)
  498. * .groupBy(cars.brand)
  499. * .having(({ count }) => gt(count, 1));
  500. * ```
  501. */
  502. having(having) {
  503. if (typeof having === "function") {
  504. having = having(
  505. new Proxy(
  506. this.config.fields,
  507. new import_selection_proxy.SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
  508. )
  509. );
  510. }
  511. this.config.having = having;
  512. return this;
  513. }
  514. groupBy(...columns) {
  515. if (typeof columns[0] === "function") {
  516. const groupBy = columns[0](
  517. new Proxy(
  518. this.config.fields,
  519. new import_selection_proxy.SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
  520. )
  521. );
  522. this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
  523. } else {
  524. this.config.groupBy = columns;
  525. }
  526. return this;
  527. }
  528. orderBy(...columns) {
  529. if (typeof columns[0] === "function") {
  530. const orderBy = columns[0](
  531. new Proxy(
  532. this.config.fields,
  533. new import_selection_proxy.SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
  534. )
  535. );
  536. const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
  537. if (this.config.setOperators.length > 0) {
  538. this.config.setOperators.at(-1).orderBy = orderByArray;
  539. } else {
  540. this.config.orderBy = orderByArray;
  541. }
  542. } else {
  543. const orderByArray = columns;
  544. if (this.config.setOperators.length > 0) {
  545. this.config.setOperators.at(-1).orderBy = orderByArray;
  546. } else {
  547. this.config.orderBy = orderByArray;
  548. }
  549. }
  550. return this;
  551. }
  552. /**
  553. * Adds a `limit` clause to the query.
  554. *
  555. * Calling this method will set the maximum number of rows that will be returned by this query.
  556. *
  557. * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
  558. *
  559. * @param limit the `limit` clause.
  560. *
  561. * @example
  562. *
  563. * ```ts
  564. * // Get the first 10 people from this query.
  565. * await db.select().from(people).limit(10);
  566. * ```
  567. */
  568. limit(limit) {
  569. if (this.config.setOperators.length > 0) {
  570. this.config.setOperators.at(-1).limit = limit;
  571. } else {
  572. this.config.limit = limit;
  573. }
  574. return this;
  575. }
  576. /**
  577. * Adds an `offset` clause to the query.
  578. *
  579. * Calling this method will skip a number of rows when returning results from this query.
  580. *
  581. * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
  582. *
  583. * @param offset the `offset` clause.
  584. *
  585. * @example
  586. *
  587. * ```ts
  588. * // Get the 10th-20th people from this query.
  589. * await db.select().from(people).offset(10).limit(10);
  590. * ```
  591. */
  592. offset(offset) {
  593. if (this.config.setOperators.length > 0) {
  594. this.config.setOperators.at(-1).offset = offset;
  595. } else {
  596. this.config.offset = offset;
  597. }
  598. return this;
  599. }
  600. /** @internal */
  601. getSQL() {
  602. return this.dialect.buildSelectQuery(this.config);
  603. }
  604. toSQL() {
  605. const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
  606. return rest;
  607. }
  608. as(alias) {
  609. const usedTables = [];
  610. usedTables.push(...(0, import_utils2.extractUsedTable)(this.config.table));
  611. if (this.config.joins) {
  612. for (const it of this.config.joins) usedTables.push(...(0, import_utils2.extractUsedTable)(it.table));
  613. }
  614. return new Proxy(
  615. new import_subquery.Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]),
  616. new import_selection_proxy.SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
  617. );
  618. }
  619. /** @internal */
  620. getSelectedFields() {
  621. return new Proxy(
  622. this.config.fields,
  623. new import_selection_proxy.SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
  624. );
  625. }
  626. $dynamic() {
  627. return this;
  628. }
  629. }
  630. class SQLiteSelectBase extends SQLiteSelectQueryBuilderBase {
  631. static [import_entity.entityKind] = "SQLiteSelect";
  632. /** @internal */
  633. _prepare(isOneTimeQuery = true) {
  634. if (!this.session) {
  635. throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
  636. }
  637. const fieldsList = (0, import_utils.orderSelectedFields)(this.config.fields);
  638. const query = this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](
  639. this.dialect.sqlToQuery(this.getSQL()),
  640. fieldsList,
  641. "all",
  642. true,
  643. void 0,
  644. {
  645. type: "select",
  646. tables: [...this.usedTables]
  647. },
  648. this.cacheConfig
  649. );
  650. query.joinsNotNullableMap = this.joinsNotNullableMap;
  651. return query;
  652. }
  653. $withCache(config) {
  654. this.cacheConfig = config === void 0 ? { config: {}, enable: true, autoInvalidate: true } : config === false ? { enable: false } : { enable: true, autoInvalidate: true, ...config };
  655. return this;
  656. }
  657. prepare() {
  658. return this._prepare(false);
  659. }
  660. run = (placeholderValues) => {
  661. return this._prepare().run(placeholderValues);
  662. };
  663. all = (placeholderValues) => {
  664. return this._prepare().all(placeholderValues);
  665. };
  666. get = (placeholderValues) => {
  667. return this._prepare().get(placeholderValues);
  668. };
  669. values = (placeholderValues) => {
  670. return this._prepare().values(placeholderValues);
  671. };
  672. async execute() {
  673. return this.all();
  674. }
  675. }
  676. (0, import_utils.applyMixins)(SQLiteSelectBase, [import_query_promise.QueryPromise]);
  677. function createSetOperator(type, isAll) {
  678. return (leftSelect, rightSelect, ...restSelects) => {
  679. const setOperators = [rightSelect, ...restSelects].map((select) => ({
  680. type,
  681. isAll,
  682. rightSelect: select
  683. }));
  684. for (const setOperator of setOperators) {
  685. if (!(0, import_utils.haveSameKeys)(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {
  686. throw new Error(
  687. "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
  688. );
  689. }
  690. }
  691. return leftSelect.addSetOperators(setOperators);
  692. };
  693. }
  694. const getSQLiteSetOperators = () => ({
  695. union,
  696. unionAll,
  697. intersect,
  698. except
  699. });
  700. const union = createSetOperator("union", false);
  701. const unionAll = createSetOperator("union", true);
  702. const intersect = createSetOperator("intersect", false);
  703. const except = createSetOperator("except", false);
  704. // Annotate the CommonJS export names for ESM import in node:
  705. 0 && (module.exports = {
  706. SQLiteSelectBase,
  707. SQLiteSelectBuilder,
  708. SQLiteSelectQueryBuilderBase,
  709. except,
  710. intersect,
  711. union,
  712. unionAll
  713. });
  714. //# sourceMappingURL=select.cjs.map