db.cjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. BaseSQLiteDatabase: () => BaseSQLiteDatabase,
  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_query_builders = require("./query-builders/index.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 BaseSQLiteDatabase {
  34. constructor(resultKind, dialect, session, schema) {
  35. this.resultKind = resultKind;
  36. this.dialect = dialect;
  37. this.session = session;
  38. this._ = schema ? {
  39. schema: schema.schema,
  40. fullSchema: schema.fullSchema,
  41. tableNamesMap: schema.tableNamesMap
  42. } : {
  43. schema: void 0,
  44. fullSchema: {},
  45. tableNamesMap: {}
  46. };
  47. this.query = {};
  48. const query = this.query;
  49. if (this._.schema) {
  50. for (const [tableName, columns] of Object.entries(this._.schema)) {
  51. query[tableName] = new import_query.RelationalQueryBuilder(
  52. resultKind,
  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] = "BaseSQLiteDatabase";
  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.SQLiteCountBuilder({ source, filters, session: this.session });
  120. }
  121. /**
  122. * Incorporates a previously defined CTE (using `$with`) into the main query.
  123. *
  124. * This method allows the main query to reference a temporary named result set.
  125. *
  126. * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
  127. *
  128. * @param queries The CTEs to incorporate into the main query.
  129. *
  130. * @example
  131. *
  132. * ```ts
  133. * // Define a subquery 'sq' as a CTE using $with
  134. * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
  135. *
  136. * // Incorporate the CTE 'sq' into the main query and select from it
  137. * const result = await db.with(sq).select().from(sq);
  138. * ```
  139. */
  140. with(...queries) {
  141. const self = this;
  142. function select(fields) {
  143. return new import_query_builders.SQLiteSelectBuilder({
  144. fields: fields ?? void 0,
  145. session: self.session,
  146. dialect: self.dialect,
  147. withList: queries
  148. });
  149. }
  150. function selectDistinct(fields) {
  151. return new import_query_builders.SQLiteSelectBuilder({
  152. fields: fields ?? void 0,
  153. session: self.session,
  154. dialect: self.dialect,
  155. withList: queries,
  156. distinct: true
  157. });
  158. }
  159. function update(table) {
  160. return new import_query_builders.SQLiteUpdateBuilder(table, self.session, self.dialect, queries);
  161. }
  162. function insert(into) {
  163. return new import_query_builders.SQLiteInsertBuilder(into, self.session, self.dialect, queries);
  164. }
  165. function delete_(from) {
  166. return new import_query_builders.SQLiteDeleteBase(from, self.session, self.dialect, queries);
  167. }
  168. return { select, selectDistinct, update, insert, delete: delete_ };
  169. }
  170. select(fields) {
  171. return new import_query_builders.SQLiteSelectBuilder({ fields: fields ?? void 0, session: this.session, dialect: this.dialect });
  172. }
  173. selectDistinct(fields) {
  174. return new import_query_builders.SQLiteSelectBuilder({
  175. fields: fields ?? void 0,
  176. session: this.session,
  177. dialect: this.dialect,
  178. distinct: true
  179. });
  180. }
  181. /**
  182. * Creates an update query.
  183. *
  184. * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.
  185. *
  186. * Use `.set()` method to specify which values to update.
  187. *
  188. * See docs: {@link https://orm.drizzle.team/docs/update}
  189. *
  190. * @param table The table to update.
  191. *
  192. * @example
  193. *
  194. * ```ts
  195. * // Update all rows in the 'cars' table
  196. * await db.update(cars).set({ color: 'red' });
  197. *
  198. * // Update rows with filters and conditions
  199. * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));
  200. *
  201. * // Update with returning clause
  202. * const updatedCar: Car[] = await db.update(cars)
  203. * .set({ color: 'red' })
  204. * .where(eq(cars.id, 1))
  205. * .returning();
  206. * ```
  207. */
  208. update(table) {
  209. return new import_query_builders.SQLiteUpdateBuilder(table, this.session, this.dialect);
  210. }
  211. $cache;
  212. /**
  213. * Creates an insert query.
  214. *
  215. * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.
  216. *
  217. * See docs: {@link https://orm.drizzle.team/docs/insert}
  218. *
  219. * @param table The table to insert into.
  220. *
  221. * @example
  222. *
  223. * ```ts
  224. * // Insert one row
  225. * await db.insert(cars).values({ brand: 'BMW' });
  226. *
  227. * // Insert multiple rows
  228. * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);
  229. *
  230. * // Insert with returning clause
  231. * const insertedCar: Car[] = await db.insert(cars)
  232. * .values({ brand: 'BMW' })
  233. * .returning();
  234. * ```
  235. */
  236. insert(into) {
  237. return new import_query_builders.SQLiteInsertBuilder(into, this.session, this.dialect);
  238. }
  239. /**
  240. * Creates a delete query.
  241. *
  242. * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.
  243. *
  244. * See docs: {@link https://orm.drizzle.team/docs/delete}
  245. *
  246. * @param table The table to delete from.
  247. *
  248. * @example
  249. *
  250. * ```ts
  251. * // Delete all rows in the 'cars' table
  252. * await db.delete(cars);
  253. *
  254. * // Delete rows with filters and conditions
  255. * await db.delete(cars).where(eq(cars.color, 'green'));
  256. *
  257. * // Delete with returning clause
  258. * const deletedCar: Car[] = await db.delete(cars)
  259. * .where(eq(cars.id, 1))
  260. * .returning();
  261. * ```
  262. */
  263. delete(from) {
  264. return new import_query_builders.SQLiteDeleteBase(from, this.session, this.dialect);
  265. }
  266. run(query) {
  267. const sequel = typeof query === "string" ? import_sql.sql.raw(query) : query.getSQL();
  268. if (this.resultKind === "async") {
  269. return new import_raw.SQLiteRaw(
  270. async () => this.session.run(sequel),
  271. () => sequel,
  272. "run",
  273. this.dialect,
  274. this.session.extractRawRunValueFromBatchResult.bind(this.session)
  275. );
  276. }
  277. return this.session.run(sequel);
  278. }
  279. all(query) {
  280. const sequel = typeof query === "string" ? import_sql.sql.raw(query) : query.getSQL();
  281. if (this.resultKind === "async") {
  282. return new import_raw.SQLiteRaw(
  283. async () => this.session.all(sequel),
  284. () => sequel,
  285. "all",
  286. this.dialect,
  287. this.session.extractRawAllValueFromBatchResult.bind(this.session)
  288. );
  289. }
  290. return this.session.all(sequel);
  291. }
  292. get(query) {
  293. const sequel = typeof query === "string" ? import_sql.sql.raw(query) : query.getSQL();
  294. if (this.resultKind === "async") {
  295. return new import_raw.SQLiteRaw(
  296. async () => this.session.get(sequel),
  297. () => sequel,
  298. "get",
  299. this.dialect,
  300. this.session.extractRawGetValueFromBatchResult.bind(this.session)
  301. );
  302. }
  303. return this.session.get(sequel);
  304. }
  305. values(query) {
  306. const sequel = typeof query === "string" ? import_sql.sql.raw(query) : query.getSQL();
  307. if (this.resultKind === "async") {
  308. return new import_raw.SQLiteRaw(
  309. async () => this.session.values(sequel),
  310. () => sequel,
  311. "values",
  312. this.dialect,
  313. this.session.extractRawValuesValueFromBatchResult.bind(this.session)
  314. );
  315. }
  316. return this.session.values(sequel);
  317. }
  318. transaction(transaction, config) {
  319. return this.session.transaction(transaction, config);
  320. }
  321. }
  322. const withReplicas = (primary, replicas, getReplica = () => replicas[Math.floor(Math.random() * replicas.length)]) => {
  323. const select = (...args) => getReplica(replicas).select(...args);
  324. const selectDistinct = (...args) => getReplica(replicas).selectDistinct(...args);
  325. const $count = (...args) => getReplica(replicas).$count(...args);
  326. const $with = (...args) => getReplica(replicas).with(...args);
  327. const update = (...args) => primary.update(...args);
  328. const insert = (...args) => primary.insert(...args);
  329. const $delete = (...args) => primary.delete(...args);
  330. const run = (...args) => primary.run(...args);
  331. const all = (...args) => primary.all(...args);
  332. const get = (...args) => primary.get(...args);
  333. const values = (...args) => primary.values(...args);
  334. const transaction = (...args) => primary.transaction(...args);
  335. return {
  336. ...primary,
  337. update,
  338. insert,
  339. delete: $delete,
  340. run,
  341. all,
  342. get,
  343. values,
  344. transaction,
  345. $primary: primary,
  346. $replicas: replicas,
  347. select,
  348. selectDistinct,
  349. $count,
  350. with: $with,
  351. get query() {
  352. return getReplica(replicas).query;
  353. }
  354. };
  355. };
  356. // Annotate the CommonJS export names for ESM import in node:
  357. 0 && (module.exports = {
  358. BaseSQLiteDatabase,
  359. withReplicas
  360. });
  361. //# sourceMappingURL=db.cjs.map