insert.cjs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. MySqlInsertBase: () => MySqlInsertBase,
  22. MySqlInsertBuilder: () => MySqlInsertBuilder
  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_utils = require("../../utils.cjs");
  30. var import_utils2 = require("../utils.cjs");
  31. var import_query_builder = require("./query-builder.cjs");
  32. class MySqlInsertBuilder {
  33. constructor(table, session, dialect) {
  34. this.table = table;
  35. this.session = session;
  36. this.dialect = dialect;
  37. }
  38. static [import_entity.entityKind] = "MySqlInsertBuilder";
  39. shouldIgnore = false;
  40. ignore() {
  41. this.shouldIgnore = true;
  42. return this;
  43. }
  44. values(values) {
  45. values = Array.isArray(values) ? values : [values];
  46. if (values.length === 0) {
  47. throw new Error("values() must be called with at least one value");
  48. }
  49. const mappedValues = values.map((entry) => {
  50. const result = {};
  51. const cols = this.table[import_table.Table.Symbol.Columns];
  52. for (const colKey of Object.keys(entry)) {
  53. const colValue = entry[colKey];
  54. result[colKey] = (0, import_entity.is)(colValue, import_sql.SQL) ? colValue : new import_sql.Param(colValue, cols[colKey]);
  55. }
  56. return result;
  57. });
  58. return new MySqlInsertBase(this.table, mappedValues, this.shouldIgnore, this.session, this.dialect);
  59. }
  60. select(selectQuery) {
  61. const select = typeof selectQuery === "function" ? selectQuery(new import_query_builder.QueryBuilder()) : selectQuery;
  62. if (!(0, import_entity.is)(select, import_sql.SQL) && !(0, import_utils.haveSameKeys)(this.table[import_table.Columns], select._.selectedFields)) {
  63. throw new Error(
  64. "Insert select error: selected fields are not the same or are in a different order compared to the table definition"
  65. );
  66. }
  67. return new MySqlInsertBase(this.table, select, this.shouldIgnore, this.session, this.dialect, true);
  68. }
  69. }
  70. class MySqlInsertBase extends import_query_promise.QueryPromise {
  71. constructor(table, values, ignore, session, dialect, select) {
  72. super();
  73. this.session = session;
  74. this.dialect = dialect;
  75. this.config = { table, values, select, ignore };
  76. }
  77. static [import_entity.entityKind] = "MySqlInsert";
  78. config;
  79. cacheConfig;
  80. /**
  81. * Adds an `on duplicate key update` clause to the query.
  82. *
  83. * Calling this method will update the row if any unique index conflicts. MySQL will automatically determine the conflict target based on the primary key and unique indexes.
  84. *
  85. * See docs: {@link https://orm.drizzle.team/docs/insert#on-duplicate-key-update}
  86. *
  87. * @param config The `set` clause
  88. *
  89. * @example
  90. * ```ts
  91. * await db.insert(cars)
  92. * .values({ id: 1, brand: 'BMW'})
  93. * .onDuplicateKeyUpdate({ set: { brand: 'Porsche' }});
  94. * ```
  95. *
  96. * While MySQL does not directly support doing nothing on conflict, you can perform a no-op by setting any column's value to itself and achieve the same effect:
  97. *
  98. * ```ts
  99. * import { sql } from 'drizzle-orm';
  100. *
  101. * await db.insert(cars)
  102. * .values({ id: 1, brand: 'BMW' })
  103. * .onDuplicateKeyUpdate({ set: { id: sql`id` } });
  104. * ```
  105. */
  106. onDuplicateKeyUpdate(config) {
  107. const setSql = this.dialect.buildUpdateSet(this.config.table, (0, import_utils.mapUpdateSet)(this.config.table, config.set));
  108. this.config.onConflict = import_sql.sql`update ${setSql}`;
  109. return this;
  110. }
  111. $returningId() {
  112. const returning = [];
  113. for (const [key, value] of Object.entries(this.config.table[import_table.Table.Symbol.Columns])) {
  114. if (value.primary) {
  115. returning.push({ field: value, path: [key] });
  116. }
  117. }
  118. this.config.returning = returning;
  119. return this;
  120. }
  121. /** @internal */
  122. getSQL() {
  123. return this.dialect.buildInsertQuery(this.config).sql;
  124. }
  125. toSQL() {
  126. const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
  127. return rest;
  128. }
  129. prepare() {
  130. const { sql: sql2, generatedIds } = this.dialect.buildInsertQuery(this.config);
  131. return this.session.prepareQuery(
  132. this.dialect.sqlToQuery(sql2),
  133. void 0,
  134. void 0,
  135. generatedIds,
  136. this.config.returning,
  137. {
  138. type: "insert",
  139. tables: (0, import_utils2.extractUsedTable)(this.config.table)
  140. },
  141. this.cacheConfig
  142. );
  143. }
  144. execute = (placeholderValues) => {
  145. return this.prepare().execute(placeholderValues);
  146. };
  147. createIterator = () => {
  148. const self = this;
  149. return async function* (placeholderValues) {
  150. yield* self.prepare().iterator(placeholderValues);
  151. };
  152. };
  153. iterator = this.createIterator();
  154. $dynamic() {
  155. return this;
  156. }
  157. }
  158. // Annotate the CommonJS export names for ESM import in node:
  159. 0 && (module.exports = {
  160. MySqlInsertBase,
  161. MySqlInsertBuilder
  162. });
  163. //# sourceMappingURL=insert.cjs.map