update.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. import { entityKind, is } from "../../entity.js";
  2. import { GelTable } from "../table.js";
  3. import { QueryPromise } from "../../query-promise.js";
  4. import { SelectionProxyHandler } from "../../selection-proxy.js";
  5. import { SQL } from "../../sql/sql.js";
  6. import { Subquery } from "../../subquery.js";
  7. import { Table } from "../../table.js";
  8. import {
  9. getTableLikeName,
  10. mapUpdateSet,
  11. orderSelectedFields
  12. } from "../../utils.js";
  13. import { ViewBaseConfig } from "../../view-common.js";
  14. import { extractUsedTable } from "../utils.js";
  15. class GelUpdateBuilder {
  16. constructor(table, session, dialect, withList) {
  17. this.table = table;
  18. this.session = session;
  19. this.dialect = dialect;
  20. this.withList = withList;
  21. }
  22. static [entityKind] = "GelUpdateBuilder";
  23. authToken;
  24. setToken(token) {
  25. this.authToken = token;
  26. return this;
  27. }
  28. set(values) {
  29. return new GelUpdateBase(
  30. this.table,
  31. mapUpdateSet(this.table, values),
  32. this.session,
  33. this.dialect,
  34. this.withList
  35. );
  36. }
  37. }
  38. class GelUpdateBase extends QueryPromise {
  39. constructor(table, set, session, dialect, withList) {
  40. super();
  41. this.session = session;
  42. this.dialect = dialect;
  43. this.config = { set, table, withList, joins: [] };
  44. this.tableName = getTableLikeName(table);
  45. this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
  46. }
  47. static [entityKind] = "GelUpdate";
  48. config;
  49. tableName;
  50. joinsNotNullableMap;
  51. from(source) {
  52. const tableName = getTableLikeName(source);
  53. if (typeof tableName === "string") {
  54. this.joinsNotNullableMap[tableName] = true;
  55. }
  56. this.config.from = source;
  57. return this;
  58. }
  59. getTableLikeFields(table) {
  60. if (is(table, GelTable)) {
  61. return table[Table.Symbol.Columns];
  62. } else if (is(table, Subquery)) {
  63. return table._.selectedFields;
  64. }
  65. return table[ViewBaseConfig].selectedFields;
  66. }
  67. createJoin(joinType) {
  68. return (table, on) => {
  69. const tableName = getTableLikeName(table);
  70. if (typeof tableName === "string" && this.config.joins.some((join) => join.alias === tableName)) {
  71. throw new Error(`Alias "${tableName}" is already used in this query`);
  72. }
  73. if (typeof on === "function") {
  74. const from = this.config.from && !is(this.config.from, SQL) ? this.getTableLikeFields(this.config.from) : void 0;
  75. on = on(
  76. new Proxy(
  77. this.config.table[Table.Symbol.Columns],
  78. new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
  79. ),
  80. from && new Proxy(
  81. from,
  82. new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
  83. )
  84. );
  85. }
  86. this.config.joins.push({ on, table, joinType, alias: tableName });
  87. if (typeof tableName === "string") {
  88. switch (joinType) {
  89. case "left": {
  90. this.joinsNotNullableMap[tableName] = false;
  91. break;
  92. }
  93. case "right": {
  94. this.joinsNotNullableMap = Object.fromEntries(
  95. Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
  96. );
  97. this.joinsNotNullableMap[tableName] = true;
  98. break;
  99. }
  100. case "inner": {
  101. this.joinsNotNullableMap[tableName] = true;
  102. break;
  103. }
  104. case "full": {
  105. this.joinsNotNullableMap = Object.fromEntries(
  106. Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
  107. );
  108. this.joinsNotNullableMap[tableName] = false;
  109. break;
  110. }
  111. }
  112. }
  113. return this;
  114. };
  115. }
  116. leftJoin = this.createJoin("left");
  117. rightJoin = this.createJoin("right");
  118. innerJoin = this.createJoin("inner");
  119. fullJoin = this.createJoin("full");
  120. /**
  121. * Adds a 'where' clause to the query.
  122. *
  123. * Calling this method will update only those rows that fulfill a specified condition.
  124. *
  125. * See docs: {@link https://orm.drizzle.team/docs/update}
  126. *
  127. * @param where the 'where' clause.
  128. *
  129. * @example
  130. * You can use conditional operators and `sql function` to filter the rows to be updated.
  131. *
  132. * ```ts
  133. * // Update all cars with green color
  134. * await db.update(cars).set({ color: 'red' })
  135. * .where(eq(cars.color, 'green'));
  136. * // or
  137. * await db.update(cars).set({ color: 'red' })
  138. * .where(sql`${cars.color} = 'green'`)
  139. * ```
  140. *
  141. * You can logically combine conditional operators with `and()` and `or()` operators:
  142. *
  143. * ```ts
  144. * // Update all BMW cars with a green color
  145. * await db.update(cars).set({ color: 'red' })
  146. * .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
  147. *
  148. * // Update all cars with the green or blue color
  149. * await db.update(cars).set({ color: 'red' })
  150. * .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
  151. * ```
  152. */
  153. where(where) {
  154. this.config.where = where;
  155. return this;
  156. }
  157. returning(fields) {
  158. if (!fields) {
  159. fields = Object.assign({}, this.config.table[Table.Symbol.Columns]);
  160. if (this.config.from) {
  161. const tableName = getTableLikeName(this.config.from);
  162. if (typeof tableName === "string" && this.config.from && !is(this.config.from, SQL)) {
  163. const fromFields = this.getTableLikeFields(this.config.from);
  164. fields[tableName] = fromFields;
  165. }
  166. for (const join of this.config.joins) {
  167. const tableName2 = getTableLikeName(join.table);
  168. if (typeof tableName2 === "string" && !is(join.table, SQL)) {
  169. const fromFields = this.getTableLikeFields(join.table);
  170. fields[tableName2] = fromFields;
  171. }
  172. }
  173. }
  174. }
  175. this.config.returning = orderSelectedFields(fields);
  176. return this;
  177. }
  178. /** @internal */
  179. getSQL() {
  180. return this.dialect.buildUpdateQuery(this.config);
  181. }
  182. toSQL() {
  183. const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
  184. return rest;
  185. }
  186. /** @internal */
  187. _prepare(name) {
  188. const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, void 0, {
  189. type: "update",
  190. tables: extractUsedTable(this.config.table)
  191. });
  192. query.joinsNotNullableMap = this.joinsNotNullableMap;
  193. return query;
  194. }
  195. prepare(name) {
  196. return this._prepare(name);
  197. }
  198. execute = (placeholderValues) => {
  199. return this._prepare().execute(placeholderValues);
  200. };
  201. $dynamic() {
  202. return this;
  203. }
  204. }
  205. export {
  206. GelUpdateBase,
  207. GelUpdateBuilder
  208. };
  209. //# sourceMappingURL=update.js.map