db.cjs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. MySqlDatabase: () => MySqlDatabase,
  22. withReplicas: () => withReplicas
  23. });
  24. module.exports = __toCommonJS(db_exports);
  25. var import_entity = require("../entity.cjs");
  26. var import_selection_proxy = require("../selection-proxy.cjs");
  27. var import_sql = require("../sql/sql.cjs");
  28. var import_subquery = require("../subquery.cjs");
  29. var import_count = require("./query-builders/count.cjs");
  30. var import_query_builders = require("./query-builders/index.cjs");
  31. var import_query = require("./query-builders/query.cjs");
  32. class MySqlDatabase {
  33. constructor(dialect, session, schema, mode) {
  34. this.dialect = dialect;
  35. this.session = session;
  36. this.mode = mode;
  37. this._ = schema ? {
  38. schema: schema.schema,
  39. fullSchema: schema.fullSchema,
  40. tableNamesMap: schema.tableNamesMap
  41. } : {
  42. schema: void 0,
  43. fullSchema: {},
  44. tableNamesMap: {}
  45. };
  46. this.query = {};
  47. if (this._.schema) {
  48. for (const [tableName, columns] of Object.entries(this._.schema)) {
  49. this.query[tableName] = new import_query.RelationalQueryBuilder(
  50. schema.fullSchema,
  51. this._.schema,
  52. this._.tableNamesMap,
  53. schema.fullSchema[tableName],
  54. columns,
  55. dialect,
  56. session,
  57. this.mode
  58. );
  59. }
  60. }
  61. this.$cache = { invalidate: async (_params) => {
  62. } };
  63. }
  64. static [import_entity.entityKind] = "MySqlDatabase";
  65. query;
  66. /**
  67. * Creates a subquery that defines a temporary named result set as a CTE.
  68. *
  69. * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.
  70. *
  71. * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
  72. *
  73. * @param alias The alias for the subquery.
  74. *
  75. * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.
  76. *
  77. * @example
  78. *
  79. * ```ts
  80. * // Create a subquery with alias 'sq' and use it in the select query
  81. * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
  82. *
  83. * const result = await db.with(sq).select().from(sq);
  84. * ```
  85. *
  86. * 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:
  87. *
  88. * ```ts
  89. * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query
  90. * const sq = db.$with('sq').as(db.select({
  91. * name: sql<string>`upper(${users.name})`.as('name'),
  92. * })
  93. * .from(users));
  94. *
  95. * const result = await db.with(sq).select({ name: sq.name }).from(sq);
  96. * ```
  97. */
  98. $with = (alias, selection) => {
  99. const self = this;
  100. const as = (qb) => {
  101. if (typeof qb === "function") {
  102. qb = qb(new import_query_builders.QueryBuilder(self.dialect));
  103. }
  104. return new Proxy(
  105. new import_subquery.WithSubquery(
  106. qb.getSQL(),
  107. selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}),
  108. alias,
  109. true
  110. ),
  111. new import_selection_proxy.SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
  112. );
  113. };
  114. return { as };
  115. };
  116. $count(source, filters) {
  117. return new import_count.MySqlCountBuilder({ source, filters, session: this.session });
  118. }
  119. $cache;
  120. /**
  121. * Incorporates a previously defined CTE (using `$with`) into the main query.
  122. *
  123. * This method allows the main query to reference a temporary named result set.
  124. *
  125. * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
  126. *
  127. * @param queries The CTEs to incorporate into the main query.
  128. *
  129. * @example
  130. *
  131. * ```ts
  132. * // Define a subquery 'sq' as a CTE using $with
  133. * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
  134. *
  135. * // Incorporate the CTE 'sq' into the main query and select from it
  136. * const result = await db.with(sq).select().from(sq);
  137. * ```
  138. */
  139. with(...queries) {
  140. const self = this;
  141. function select(fields) {
  142. return new import_query_builders.MySqlSelectBuilder({
  143. fields: fields ?? void 0,
  144. session: self.session,
  145. dialect: self.dialect,
  146. withList: queries
  147. });
  148. }
  149. function selectDistinct(fields) {
  150. return new import_query_builders.MySqlSelectBuilder({
  151. fields: fields ?? void 0,
  152. session: self.session,
  153. dialect: self.dialect,
  154. withList: queries,
  155. distinct: true
  156. });
  157. }
  158. function update(table) {
  159. return new import_query_builders.MySqlUpdateBuilder(table, self.session, self.dialect, queries);
  160. }
  161. function delete_(table) {
  162. return new import_query_builders.MySqlDeleteBase(table, self.session, self.dialect, queries);
  163. }
  164. return { select, selectDistinct, update, delete: delete_ };
  165. }
  166. select(fields) {
  167. return new import_query_builders.MySqlSelectBuilder({ fields: fields ?? void 0, session: this.session, dialect: this.dialect });
  168. }
  169. selectDistinct(fields) {
  170. return new import_query_builders.MySqlSelectBuilder({
  171. fields: fields ?? void 0,
  172. session: this.session,
  173. dialect: this.dialect,
  174. distinct: true
  175. });
  176. }
  177. /**
  178. * Creates an update query.
  179. *
  180. * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.
  181. *
  182. * Use `.set()` method to specify which values to update.
  183. *
  184. * See docs: {@link https://orm.drizzle.team/docs/update}
  185. *
  186. * @param table The table to update.
  187. *
  188. * @example
  189. *
  190. * ```ts
  191. * // Update all rows in the 'cars' table
  192. * await db.update(cars).set({ color: 'red' });
  193. *
  194. * // Update rows with filters and conditions
  195. * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));
  196. * ```
  197. */
  198. update(table) {
  199. return new import_query_builders.MySqlUpdateBuilder(table, this.session, this.dialect);
  200. }
  201. /**
  202. * Creates an insert query.
  203. *
  204. * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.
  205. *
  206. * See docs: {@link https://orm.drizzle.team/docs/insert}
  207. *
  208. * @param table The table to insert into.
  209. *
  210. * @example
  211. *
  212. * ```ts
  213. * // Insert one row
  214. * await db.insert(cars).values({ brand: 'BMW' });
  215. *
  216. * // Insert multiple rows
  217. * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);
  218. * ```
  219. */
  220. insert(table) {
  221. return new import_query_builders.MySqlInsertBuilder(table, this.session, this.dialect);
  222. }
  223. /**
  224. * Creates a delete query.
  225. *
  226. * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.
  227. *
  228. * See docs: {@link https://orm.drizzle.team/docs/delete}
  229. *
  230. * @param table The table to delete from.
  231. *
  232. * @example
  233. *
  234. * ```ts
  235. * // Delete all rows in the 'cars' table
  236. * await db.delete(cars);
  237. *
  238. * // Delete rows with filters and conditions
  239. * await db.delete(cars).where(eq(cars.color, 'green'));
  240. * ```
  241. */
  242. delete(table) {
  243. return new import_query_builders.MySqlDeleteBase(table, this.session, this.dialect);
  244. }
  245. execute(query) {
  246. return this.session.execute(typeof query === "string" ? import_sql.sql.raw(query) : query.getSQL());
  247. }
  248. transaction(transaction, config) {
  249. return this.session.transaction(transaction, config);
  250. }
  251. }
  252. const withReplicas = (primary, replicas, getReplica = () => replicas[Math.floor(Math.random() * replicas.length)]) => {
  253. const select = (...args) => getReplica(replicas).select(...args);
  254. const selectDistinct = (...args) => getReplica(replicas).selectDistinct(...args);
  255. const $count = (...args) => getReplica(replicas).$count(...args);
  256. const $with = (...args) => getReplica(replicas).with(...args);
  257. const update = (...args) => primary.update(...args);
  258. const insert = (...args) => primary.insert(...args);
  259. const $delete = (...args) => primary.delete(...args);
  260. const execute = (...args) => primary.execute(...args);
  261. const transaction = (...args) => primary.transaction(...args);
  262. return {
  263. ...primary,
  264. update,
  265. insert,
  266. delete: $delete,
  267. execute,
  268. transaction,
  269. $primary: primary,
  270. $replicas: replicas,
  271. select,
  272. selectDistinct,
  273. $count,
  274. with: $with,
  275. get query() {
  276. return getReplica(replicas).query;
  277. }
  278. };
  279. };
  280. // Annotate the CommonJS export names for ESM import in node:
  281. 0 && (module.exports = {
  282. MySqlDatabase,
  283. withReplicas
  284. });
  285. //# sourceMappingURL=db.cjs.map