insert.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. import { entityKind, is } from "../../entity.js";
  2. import { QueryPromise } from "../../query-promise.js";
  3. import { SelectionProxyHandler } from "../../selection-proxy.js";
  4. import { Param, SQL, sql } from "../../sql/sql.js";
  5. import { Columns, getTableName, Table } from "../../table.js";
  6. import { tracer } from "../../tracing.js";
  7. import { haveSameKeys, mapUpdateSet, orderSelectedFields } from "../../utils.js";
  8. import { extractUsedTable } from "../utils.js";
  9. import { QueryBuilder } from "./query-builder.js";
  10. class PgInsertBuilder {
  11. constructor(table, session, dialect, withList, overridingSystemValue_) {
  12. this.table = table;
  13. this.session = session;
  14. this.dialect = dialect;
  15. this.withList = withList;
  16. this.overridingSystemValue_ = overridingSystemValue_;
  17. }
  18. static [entityKind] = "PgInsertBuilder";
  19. authToken;
  20. /** @internal */
  21. setToken(token) {
  22. this.authToken = token;
  23. return this;
  24. }
  25. overridingSystemValue() {
  26. this.overridingSystemValue_ = true;
  27. return this;
  28. }
  29. values(values) {
  30. values = Array.isArray(values) ? values : [values];
  31. if (values.length === 0) {
  32. throw new Error("values() must be called with at least one value");
  33. }
  34. const mappedValues = values.map((entry) => {
  35. const result = {};
  36. const cols = this.table[Table.Symbol.Columns];
  37. for (const colKey of Object.keys(entry)) {
  38. const colValue = entry[colKey];
  39. result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
  40. }
  41. return result;
  42. });
  43. return new PgInsertBase(
  44. this.table,
  45. mappedValues,
  46. this.session,
  47. this.dialect,
  48. this.withList,
  49. false,
  50. this.overridingSystemValue_
  51. ).setToken(this.authToken);
  52. }
  53. select(selectQuery) {
  54. const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder()) : selectQuery;
  55. if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) {
  56. throw new Error(
  57. "Insert select error: selected fields are not the same or are in a different order compared to the table definition"
  58. );
  59. }
  60. return new PgInsertBase(this.table, select, this.session, this.dialect, this.withList, true);
  61. }
  62. }
  63. class PgInsertBase extends QueryPromise {
  64. constructor(table, values, session, dialect, withList, select, overridingSystemValue_) {
  65. super();
  66. this.session = session;
  67. this.dialect = dialect;
  68. this.config = { table, values, withList, select, overridingSystemValue_ };
  69. }
  70. static [entityKind] = "PgInsert";
  71. config;
  72. cacheConfig;
  73. returning(fields = this.config.table[Table.Symbol.Columns]) {
  74. this.config.returningFields = fields;
  75. this.config.returning = orderSelectedFields(fields);
  76. return this;
  77. }
  78. /**
  79. * Adds an `on conflict do nothing` clause to the query.
  80. *
  81. * Calling this method simply avoids inserting a row as its alternative action.
  82. *
  83. * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}
  84. *
  85. * @param config The `target` and `where` clauses.
  86. *
  87. * @example
  88. * ```ts
  89. * // Insert one row and cancel the insert if there's a conflict
  90. * await db.insert(cars)
  91. * .values({ id: 1, brand: 'BMW' })
  92. * .onConflictDoNothing();
  93. *
  94. * // Explicitly specify conflict target
  95. * await db.insert(cars)
  96. * .values({ id: 1, brand: 'BMW' })
  97. * .onConflictDoNothing({ target: cars.id });
  98. * ```
  99. */
  100. onConflictDoNothing(config = {}) {
  101. if (config.target === void 0) {
  102. this.config.onConflict = sql`do nothing`;
  103. } else {
  104. let targetColumn = "";
  105. targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target));
  106. const whereSql = config.where ? sql` where ${config.where}` : void 0;
  107. this.config.onConflict = sql`(${sql.raw(targetColumn)})${whereSql} do nothing`;
  108. }
  109. return this;
  110. }
  111. /**
  112. * Adds an `on conflict do update` clause to the query.
  113. *
  114. * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.
  115. *
  116. * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}
  117. *
  118. * @param config The `target`, `set` and `where` clauses.
  119. *
  120. * @example
  121. * ```ts
  122. * // Update the row if there's a conflict
  123. * await db.insert(cars)
  124. * .values({ id: 1, brand: 'BMW' })
  125. * .onConflictDoUpdate({
  126. * target: cars.id,
  127. * set: { brand: 'Porsche' }
  128. * });
  129. *
  130. * // Upsert with 'where' clause
  131. * await db.insert(cars)
  132. * .values({ id: 1, brand: 'BMW' })
  133. * .onConflictDoUpdate({
  134. * target: cars.id,
  135. * set: { brand: 'newBMW' },
  136. * targetWhere: sql`${cars.createdAt} > '2023-01-01'::date`,
  137. * });
  138. * ```
  139. */
  140. onConflictDoUpdate(config) {
  141. if (config.where && (config.targetWhere || config.setWhere)) {
  142. throw new Error(
  143. 'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.'
  144. );
  145. }
  146. const whereSql = config.where ? sql` where ${config.where}` : void 0;
  147. const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : void 0;
  148. const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : void 0;
  149. const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
  150. let targetColumn = "";
  151. targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target));
  152. this.config.onConflict = sql`(${sql.raw(targetColumn)})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`;
  153. return this;
  154. }
  155. /** @internal */
  156. getSQL() {
  157. return this.dialect.buildInsertQuery(this.config);
  158. }
  159. toSQL() {
  160. const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
  161. return rest;
  162. }
  163. /** @internal */
  164. _prepare(name) {
  165. return tracer.startActiveSpan("drizzle.prepareQuery", () => {
  166. return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, void 0, {
  167. type: "insert",
  168. tables: extractUsedTable(this.config.table)
  169. }, this.cacheConfig);
  170. });
  171. }
  172. prepare(name) {
  173. return this._prepare(name);
  174. }
  175. authToken;
  176. /** @internal */
  177. setToken(token) {
  178. this.authToken = token;
  179. return this;
  180. }
  181. execute = (placeholderValues) => {
  182. return tracer.startActiveSpan("drizzle.operation", () => {
  183. return this._prepare().execute(placeholderValues, this.authToken);
  184. });
  185. };
  186. /** @internal */
  187. getSelectedFields() {
  188. return this.config.returningFields ? new Proxy(
  189. this.config.returningFields,
  190. new SelectionProxyHandler({
  191. alias: getTableName(this.config.table),
  192. sqlAliasedBehavior: "alias",
  193. sqlBehavior: "error"
  194. })
  195. ) : void 0;
  196. }
  197. $dynamic() {
  198. return this;
  199. }
  200. }
  201. export {
  202. PgInsertBase,
  203. PgInsertBuilder
  204. };
  205. //# sourceMappingURL=insert.js.map