insert.cjs 7.8 KB

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