insert.cjs 8.5 KB

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