insert.cjs 8.2 KB

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