db.cjs 11 KB

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