insert.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. import { entityKind, is } from "../../entity.js";
  2. import { QueryPromise } from "../../query-promise.js";
  3. import { Param, SQL, sql } from "../../sql/sql.js";
  4. import { Columns, Table } from "../../table.js";
  5. import { haveSameKeys, mapUpdateSet } from "../../utils.js";
  6. import { extractUsedTable } from "../utils.js";
  7. import { QueryBuilder } from "./query-builder.js";
  8. class MySqlInsertBuilder {
  9. constructor(table, session, dialect) {
  10. this.table = table;
  11. this.session = session;
  12. this.dialect = dialect;
  13. }
  14. static [entityKind] = "MySqlInsertBuilder";
  15. shouldIgnore = false;
  16. ignore() {
  17. this.shouldIgnore = true;
  18. return this;
  19. }
  20. values(values) {
  21. values = Array.isArray(values) ? values : [values];
  22. if (values.length === 0) {
  23. throw new Error("values() must be called with at least one value");
  24. }
  25. const mappedValues = values.map((entry) => {
  26. const result = {};
  27. const cols = this.table[Table.Symbol.Columns];
  28. for (const colKey of Object.keys(entry)) {
  29. const colValue = entry[colKey];
  30. result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
  31. }
  32. return result;
  33. });
  34. return new MySqlInsertBase(this.table, mappedValues, this.shouldIgnore, this.session, this.dialect);
  35. }
  36. select(selectQuery) {
  37. const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder()) : selectQuery;
  38. if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) {
  39. throw new Error(
  40. "Insert select error: selected fields are not the same or are in a different order compared to the table definition"
  41. );
  42. }
  43. return new MySqlInsertBase(this.table, select, this.shouldIgnore, this.session, this.dialect, true);
  44. }
  45. }
  46. class MySqlInsertBase extends QueryPromise {
  47. constructor(table, values, ignore, session, dialect, select) {
  48. super();
  49. this.session = session;
  50. this.dialect = dialect;
  51. this.config = { table, values, select, ignore };
  52. }
  53. static [entityKind] = "MySqlInsert";
  54. config;
  55. cacheConfig;
  56. /**
  57. * Adds an `on duplicate key update` clause to the query.
  58. *
  59. * 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.
  60. *
  61. * See docs: {@link https://orm.drizzle.team/docs/insert#on-duplicate-key-update}
  62. *
  63. * @param config The `set` clause
  64. *
  65. * @example
  66. * ```ts
  67. * await db.insert(cars)
  68. * .values({ id: 1, brand: 'BMW'})
  69. * .onDuplicateKeyUpdate({ set: { brand: 'Porsche' }});
  70. * ```
  71. *
  72. * 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:
  73. *
  74. * ```ts
  75. * import { sql } from 'drizzle-orm';
  76. *
  77. * await db.insert(cars)
  78. * .values({ id: 1, brand: 'BMW' })
  79. * .onDuplicateKeyUpdate({ set: { id: sql`id` } });
  80. * ```
  81. */
  82. onDuplicateKeyUpdate(config) {
  83. const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
  84. this.config.onConflict = sql`update ${setSql}`;
  85. return this;
  86. }
  87. $returningId() {
  88. const returning = [];
  89. for (const [key, value] of Object.entries(this.config.table[Table.Symbol.Columns])) {
  90. if (value.primary) {
  91. returning.push({ field: value, path: [key] });
  92. }
  93. }
  94. this.config.returning = returning;
  95. return this;
  96. }
  97. /** @internal */
  98. getSQL() {
  99. return this.dialect.buildInsertQuery(this.config).sql;
  100. }
  101. toSQL() {
  102. const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
  103. return rest;
  104. }
  105. prepare() {
  106. const { sql: sql2, generatedIds } = this.dialect.buildInsertQuery(this.config);
  107. return this.session.prepareQuery(
  108. this.dialect.sqlToQuery(sql2),
  109. void 0,
  110. void 0,
  111. generatedIds,
  112. this.config.returning,
  113. {
  114. type: "insert",
  115. tables: extractUsedTable(this.config.table)
  116. },
  117. this.cacheConfig
  118. );
  119. }
  120. execute = (placeholderValues) => {
  121. return this.prepare().execute(placeholderValues);
  122. };
  123. createIterator = () => {
  124. const self = this;
  125. return async function* (placeholderValues) {
  126. yield* self.prepare().iterator(placeholderValues);
  127. };
  128. };
  129. iterator = this.createIterator();
  130. $dynamic() {
  131. return this;
  132. }
  133. }
  134. export {
  135. MySqlInsertBase,
  136. MySqlInsertBuilder
  137. };
  138. //# sourceMappingURL=insert.js.map