db.js 10 KB

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