db.cjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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, except, desc) => {
  11. if (from && typeof from === "object" || typeof from === "function") {
  12. for (let key of __getOwnPropNames(from))
  13. if (!__hasOwnProp.call(to, key) && key !== except)
  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 db_exports = {};
  20. __export(db_exports, {
  21. PgDatabase: () => PgDatabase,
  22. withReplicas: () => withReplicas
  23. });
  24. module.exports = __toCommonJS(db_exports);
  25. var import_entity = require("../entity.cjs");
  26. var import_query_builders = require("./query-builders/index.cjs");
  27. var import_selection_proxy = require("../selection-proxy.cjs");
  28. var import_sql = require("../sql/sql.cjs");
  29. var import_subquery = require("../subquery.cjs");
  30. var import_count = require("./query-builders/count.cjs");
  31. var import_query = require("./query-builders/query.cjs");
  32. var import_raw = require("./query-builders/raw.cjs");
  33. var import_refresh_materialized_view = require("./query-builders/refresh-materialized-view.cjs");
  34. class PgDatabase {
  35. constructor(dialect, session, schema) {
  36. this.dialect = dialect;
  37. this.session = session;
  38. this._ = schema ? {
  39. schema: schema.schema,
  40. fullSchema: schema.fullSchema,
  41. tableNamesMap: schema.tableNamesMap,
  42. session
  43. } : {
  44. schema: void 0,
  45. fullSchema: {},
  46. tableNamesMap: {},
  47. session
  48. };
  49. this.query = {};
  50. if (this._.schema) {
  51. for (const [tableName, columns] of Object.entries(this._.schema)) {
  52. this.query[tableName] = new import_query.RelationalQueryBuilder(
  53. schema.fullSchema,
  54. this._.schema,
  55. this._.tableNamesMap,
  56. schema.fullSchema[tableName],
  57. columns,
  58. dialect,
  59. session
  60. );
  61. }
  62. }
  63. this.$cache = { invalidate: async (_params) => {
  64. } };
  65. }
  66. static [import_entity.entityKind] = "PgDatabase";
  67. query;
  68. /**
  69. * Creates a subquery that defines a temporary named result set as a CTE.
  70. *
  71. * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.
  72. *
  73. * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
  74. *
  75. * @param alias The alias for the subquery.
  76. *
  77. * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.
  78. *
  79. * @example
  80. *
  81. * ```ts
  82. * // Create a subquery with alias 'sq' and use it in the select query
  83. * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
  84. *
  85. * const result = await db.with(sq).select().from(sq);
  86. * ```
  87. *
  88. * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:
  89. *
  90. * ```ts
  91. * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query
  92. * const sq = db.$with('sq').as(db.select({
  93. * name: sql<string>`upper(${users.name})`.as('name'),
  94. * })
  95. * .from(users));
  96. *
  97. * const result = await db.with(sq).select({ name: sq.name }).from(sq);
  98. * ```
  99. */
  100. $with = (alias, selection) => {
  101. const self = this;
  102. const as = (qb) => {
  103. if (typeof qb === "function") {
  104. qb = qb(new import_query_builders.QueryBuilder(self.dialect));
  105. }
  106. return new Proxy(
  107. new import_subquery.WithSubquery(
  108. qb.getSQL(),
  109. selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}),
  110. alias,
  111. true
  112. ),
  113. new import_selection_proxy.SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
  114. );
  115. };
  116. return { as };
  117. };
  118. $count(source, filters) {
  119. return new import_count.PgCountBuilder({ source, filters, session: this.session });
  120. }
  121. $cache;
  122. /**
  123. * Incorporates a previously defined CTE (using `$with`) into the main query.
  124. *
  125. * This method allows the main query to reference a temporary named result set.
  126. *
  127. * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
  128. *
  129. * @param queries The CTEs to incorporate into the main query.
  130. *
  131. * @example
  132. *
  133. * ```ts
  134. * // Define a subquery 'sq' as a CTE using $with
  135. * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
  136. *
  137. * // Incorporate the CTE 'sq' into the main query and select from it
  138. * const result = await db.with(sq).select().from(sq);
  139. * ```
  140. */
  141. with(...queries) {
  142. const self = this;
  143. function select(fields) {
  144. return new import_query_builders.PgSelectBuilder({
  145. fields: fields ?? void 0,
  146. session: self.session,
  147. dialect: self.dialect,
  148. withList: queries
  149. });
  150. }
  151. function selectDistinct(fields) {
  152. return new import_query_builders.PgSelectBuilder({
  153. fields: fields ?? void 0,
  154. session: self.session,
  155. dialect: self.dialect,
  156. withList: queries,
  157. distinct: true
  158. });
  159. }
  160. function selectDistinctOn(on, fields) {
  161. return new import_query_builders.PgSelectBuilder({
  162. fields: fields ?? void 0,
  163. session: self.session,
  164. dialect: self.dialect,
  165. withList: queries,
  166. distinct: { on }
  167. });
  168. }
  169. function update(table) {
  170. return new import_query_builders.PgUpdateBuilder(table, self.session, self.dialect, queries);
  171. }
  172. function insert(table) {
  173. return new import_query_builders.PgInsertBuilder(table, self.session, self.dialect, queries);
  174. }
  175. function delete_(table) {
  176. return new import_query_builders.PgDeleteBase(table, self.session, self.dialect, queries);
  177. }
  178. return { select, selectDistinct, selectDistinctOn, update, insert, delete: delete_ };
  179. }
  180. select(fields) {
  181. return new import_query_builders.PgSelectBuilder({
  182. fields: fields ?? void 0,
  183. session: this.session,
  184. dialect: this.dialect
  185. });
  186. }
  187. selectDistinct(fields) {
  188. return new import_query_builders.PgSelectBuilder({
  189. fields: fields ?? void 0,
  190. session: this.session,
  191. dialect: this.dialect,
  192. distinct: true
  193. });
  194. }
  195. selectDistinctOn(on, fields) {
  196. return new import_query_builders.PgSelectBuilder({
  197. fields: fields ?? void 0,
  198. session: this.session,
  199. dialect: this.dialect,
  200. distinct: { on }
  201. });
  202. }
  203. /**
  204. * Creates an update query.
  205. *
  206. * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.
  207. *
  208. * Use `.set()` method to specify which values to update.
  209. *
  210. * See docs: {@link https://orm.drizzle.team/docs/update}
  211. *
  212. * @param table The table to update.
  213. *
  214. * @example
  215. *
  216. * ```ts
  217. * // Update all rows in the 'cars' table
  218. * await db.update(cars).set({ color: 'red' });
  219. *
  220. * // Update rows with filters and conditions
  221. * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));
  222. *
  223. * // Update with returning clause
  224. * const updatedCar: Car[] = await db.update(cars)
  225. * .set({ color: 'red' })
  226. * .where(eq(cars.id, 1))
  227. * .returning();
  228. * ```
  229. */
  230. update(table) {
  231. return new import_query_builders.PgUpdateBuilder(table, this.session, this.dialect);
  232. }
  233. /**
  234. * Creates an insert query.
  235. *
  236. * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.
  237. *
  238. * See docs: {@link https://orm.drizzle.team/docs/insert}
  239. *
  240. * @param table The table to insert into.
  241. *
  242. * @example
  243. *
  244. * ```ts
  245. * // Insert one row
  246. * await db.insert(cars).values({ brand: 'BMW' });
  247. *
  248. * // Insert multiple rows
  249. * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);
  250. *
  251. * // Insert with returning clause
  252. * const insertedCar: Car[] = await db.insert(cars)
  253. * .values({ brand: 'BMW' })
  254. * .returning();
  255. * ```
  256. */
  257. insert(table) {
  258. return new import_query_builders.PgInsertBuilder(table, this.session, this.dialect);
  259. }
  260. /**
  261. * Creates a delete query.
  262. *
  263. * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.
  264. *
  265. * See docs: {@link https://orm.drizzle.team/docs/delete}
  266. *
  267. * @param table The table to delete from.
  268. *
  269. * @example
  270. *
  271. * ```ts
  272. * // Delete all rows in the 'cars' table
  273. * await db.delete(cars);
  274. *
  275. * // Delete rows with filters and conditions
  276. * await db.delete(cars).where(eq(cars.color, 'green'));
  277. *
  278. * // Delete with returning clause
  279. * const deletedCar: Car[] = await db.delete(cars)
  280. * .where(eq(cars.id, 1))
  281. * .returning();
  282. * ```
  283. */
  284. delete(table) {
  285. return new import_query_builders.PgDeleteBase(table, this.session, this.dialect);
  286. }
  287. refreshMaterializedView(view) {
  288. return new import_refresh_materialized_view.PgRefreshMaterializedView(view, this.session, this.dialect);
  289. }
  290. authToken;
  291. execute(query) {
  292. const sequel = typeof query === "string" ? import_sql.sql.raw(query) : query.getSQL();
  293. const builtQuery = this.dialect.sqlToQuery(sequel);
  294. const prepared = this.session.prepareQuery(
  295. builtQuery,
  296. void 0,
  297. void 0,
  298. false
  299. );
  300. return new import_raw.PgRaw(
  301. () => prepared.execute(void 0, this.authToken),
  302. sequel,
  303. builtQuery,
  304. (result) => prepared.mapResult(result, true)
  305. );
  306. }
  307. transaction(transaction, config) {
  308. return this.session.transaction(transaction, config);
  309. }
  310. }
  311. const withReplicas = (primary, replicas, getReplica = () => replicas[Math.floor(Math.random() * replicas.length)]) => {
  312. const select = (...args) => getReplica(replicas).select(...args);
  313. const selectDistinct = (...args) => getReplica(replicas).selectDistinct(...args);
  314. const selectDistinctOn = (...args) => getReplica(replicas).selectDistinctOn(...args);
  315. const $count = (...args) => getReplica(replicas).$count(...args);
  316. const _with = (...args) => getReplica(replicas).with(...args);
  317. const $with = (arg) => getReplica(replicas).$with(arg);
  318. const update = (...args) => primary.update(...args);
  319. const insert = (...args) => primary.insert(...args);
  320. const $delete = (...args) => primary.delete(...args);
  321. const execute = (...args) => primary.execute(...args);
  322. const transaction = (...args) => primary.transaction(...args);
  323. const refreshMaterializedView = (...args) => primary.refreshMaterializedView(...args);
  324. return {
  325. ...primary,
  326. update,
  327. insert,
  328. delete: $delete,
  329. execute,
  330. transaction,
  331. refreshMaterializedView,
  332. $primary: primary,
  333. $replicas: replicas,
  334. select,
  335. selectDistinct,
  336. selectDistinctOn,
  337. $count,
  338. $with,
  339. with: _with,
  340. get query() {
  341. return getReplica(replicas).query;
  342. }
  343. };
  344. };
  345. // Annotate the CommonJS export names for ESM import in node:
  346. 0 && (module.exports = {
  347. PgDatabase,
  348. withReplicas
  349. });
  350. //# sourceMappingURL=db.cjs.map